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/ShareTinkerLog.java",
"retrieved_chunk": " final Handler inlineFence = getInlineFence();\n if (inlineFence != null) {\n final Message msg = Message.obtain(inlineFence, priority, args);\n inlineFence.handleMessage(msg);\n msg.recycle();\n } else {\n debugLog.e(tag, \"!! NO_LOG_IMPL !! Original Log: \" + fmt, values);\n }\n }\n private static void printLog(String tag, Throwable thr, String fmt, Object... values) {",
"score": 14.719196136352576
},
{
"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": 11.238462653779367
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " final Field field = findField(clazz, fieldName);\n return field.getInt(null);\n } catch (Throwable thr) {\n return defVal;\n }\n }\n}",
"score": 11.150926339061773
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " */\n public static void reduceFieldArray(Object instance, String fieldName, int reduceSize)\n throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n if (reduceSize <= 0) {\n return;\n }\n Field jlrField = findField(instance, fieldName);\n Object[] original = (Object[]) jlrField.get(instance);\n int finalLength = original.length - reduceSize;\n if (finalLength <= 0) {",
"score": 10.93445112068336
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " public static Field findField(Class<?> originClazz, String name) throws NoSuchFieldException {\n for (Class<?> clazz = originClazz; clazz != null; clazz = clazz.getSuperclass()) {\n try {\n Field field = clazz.getDeclaredField(name);\n if (!field.isAccessible()) {\n field.setAccessible(true);\n }\n return field;\n } catch (NoSuchFieldException e) {\n // ignore and search next",
"score": 10.229077208862899
}
] | 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": 95.22083091280058
},
{
"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": 93.83460343104944
},
{
"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": 86.14372987328834
},
{
"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": 73.79061518186177
},
{
"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": 70.92208505150714
}
] | 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/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": 113.39563618548345
},
{
"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": 110.75883360156338
},
{
"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": 105.43994324225571
},
{
"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": 85.81868208496887
},
{
"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": 85.65772699279624
}
] | 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": 106.71147338625703
},
{
"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": 85.29757188360522
},
{
"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": 85.21794654394077
},
{
"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": 83.91041682004575
},
{
"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": 81.46521139313157
}
] | 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/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": 32.65839794658723
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": " break;\n }\n }\n if (dynamicSectionOff == 0) {\n // No dynamic linking info, nothing to load\n return Collections.unmodifiableList(dependencies);\n }\n int i = 0;\n final List<Long> neededOffsets = new ArrayList<Long>();\n long vStringTableOff = 0;",
"score": 28.940441465322724
},
{
"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": 23.33283785668937
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java",
"retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {",
"score": 22.48577740837827
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": "import java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\npublic class ElfParser implements Closeable, Elf {\n private final int MAGIC = 0x464C457F;",
"score": 20.27002900765179
}
] | java | final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class); |
/*
* Tencent is pleased to support the open source community by making Tinker available.
*
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lib_sillyboy.tinker;
import android.os.Build;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TinkerLoadLibrary {
private static final String TAG = "Tinker.LoadLibrary";
public static void installNativeLibraryPath(ClassLoader classLoader, File folder)
throws Throwable {
if (folder == null || !folder.exists()) {
ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder);
return;
}
// android o sdk_int 26
// for android o preview sdk_int 25
if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0)
|| Build.VERSION.SDK_INT > 25) {
try {
V25.install(classLoader, folder);
} catch (Throwable throwable) {
// install fail, try to treat it as v23
// some preview N version may go here
ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23",
Build.VERSION.SDK_INT, throwable.getMessage());
V23.install(classLoader, folder);
}
} else if (Build.VERSION.SDK_INT >= 23) {
try {
V23.install(classLoader, folder);
} catch (Throwable throwable) {
// install fail, try to treat it as v14
ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14",
Build.VERSION.SDK_INT, throwable.getMessage());
V14.install(classLoader, folder);
}
} else if (Build.VERSION.SDK_INT >= 14) {
V14.install(classLoader, folder);
} else {
V4.install(classLoader, folder);
}
}
private static final class V4 {
private static void install(ClassLoader classLoader, File folder) throws Throwable {
String addPath = folder.getPath();
Field pathField = ShareReflectUtil.findField(classLoader, "libPath");
final String origLibPaths = (String) pathField.get(classLoader);
final String[] origLibPathSplit = origLibPaths.split(":");
final StringBuilder newLibPaths = new StringBuilder(addPath);
for (String origLibPath : origLibPathSplit) {
if (origLibPath == null || addPath.equals(origLibPath)) {
continue;
}
newLibPaths.append(':').append(origLibPath);
}
pathField.set(classLoader, newLibPaths.toString());
final Field | libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements"); |
final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader);
final Iterator<String> libPathElementIt = libraryPathElements.iterator();
while (libPathElementIt.hasNext()) {
final String libPath = libPathElementIt.next();
if (addPath.equals(libPath)) {
libPathElementIt.remove();
break;
}
}
libraryPathElements.add(0, addPath);
libraryPathElementsFiled.set(classLoader, libraryPathElements);
}
}
private static final class V14 {
private static void install(ClassLoader classLoader, File folder) throws Throwable {
final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList");
final Object dexPathList = pathListField.get(classLoader);
final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories");
final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList);
final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1);
newNativeLibDirList.add(folder);
for (File origNativeLibDir : origNativeLibDirs) {
if (!folder.equals(origNativeLibDir)) {
newNativeLibDirList.add(origNativeLibDir);
}
}
nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0]));
}
}
private static final class V23 {
private static void install(ClassLoader classLoader, File folder) throws Throwable {
final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList");
final Object dexPathList = pathListField.get(classLoader);
final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories");
List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList);
if (origLibDirs == null) {
origLibDirs = new ArrayList<>(2);
}
final Iterator<File> libDirIt = origLibDirs.iterator();
while (libDirIt.hasNext()) {
final File libDir = libDirIt.next();
if (folder.equals(libDir)) {
libDirIt.remove();
break;
}
}
origLibDirs.add(0, folder);
final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories");
List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList);
if (origSystemLibDirs == null) {
origSystemLibDirs = new ArrayList<>(2);
}
final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1);
newLibDirs.addAll(origLibDirs);
newLibDirs.addAll(origSystemLibDirs);
final Method makeElements = ShareReflectUtil.findMethod(dexPathList,
"makePathElements", List.class, File.class, List.class);
final ArrayList<IOException> suppressedExceptions = new ArrayList<>();
final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions);
final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements");
nativeLibraryPathElements.set(dexPathList, elements);
}
}
private static final class V25 {
private static void install(ClassLoader classLoader, File folder) throws Throwable {
final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList");
final Object dexPathList = pathListField.get(classLoader);
final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories");
List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList);
if (origLibDirs == null) {
origLibDirs = new ArrayList<>(2);
}
final Iterator<File> libDirIt = origLibDirs.iterator();
while (libDirIt.hasNext()) {
final File libDir = libDirIt.next();
if (folder.equals(libDir)) {
libDirIt.remove();
break;
}
}
origLibDirs.add(0, folder);
final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories");
List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList);
if (origSystemLibDirs == null) {
origSystemLibDirs = new ArrayList<>(2);
}
final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1);
newLibDirs.addAll(origLibDirs);
newLibDirs.addAll(origSystemLibDirs);
final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class);
final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs);
final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements");
nativeLibraryPathElements.set(dexPathList, elements);
}
}
}
| lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java | DarrenTianYe-android_dynamic_load_so-7a70027 | [
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": " }\n }\n throw new IllegalStateException(\"Could not map vma to file offset!\");\n }\n @Override\n public void close() throws IOException {\n this.channel.close();\n }\n protected String readString(final ByteBuffer buffer, long offset) throws IOException {\n final StringBuilder builder = new StringBuilder();",
"score": 17.1761359140172
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": " short c;\n while ((c = readByte(buffer, offset++)) != 0) {\n builder.append((char) c);\n }\n return builder.toString();\n }\n protected long readLong(final ByteBuffer buffer, final long offset) throws IOException {\n read(buffer, offset, 8);\n return buffer.getLong();\n }",
"score": 14.076874866397045
},
{
"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": 11.334928291082221
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " public static Field findField(Class<?> originClazz, String name) throws NoSuchFieldException {\n for (Class<?> clazz = originClazz; clazz != null; clazz = clazz.getSuperclass()) {\n try {\n Field field = clazz.getDeclaredField(name);\n if (!field.isAccessible()) {\n field.setAccessible(true);\n }\n return field;\n } catch (NoSuchFieldException e) {\n // ignore and search next",
"score": 11.125943409630565
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " final Field field = findField(clazz, fieldName);\n return field.getInt(null);\n } catch (Throwable thr) {\n return defVal;\n }\n }\n}",
"score": 10.011401992299238
}
] | 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/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": 59.61355724069663
},
{
"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": 50.84087602280833
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": "import java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\npublic class ElfParser implements Closeable, Elf {\n private final int MAGIC = 0x464C457F;",
"score": 50.30156955627775
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java",
"retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {",
"score": 47.6650801807148
},
{
"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": 35.10358592684646
}
] | java | ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); |
/**
* Copyright 2015 - 2016 KeepSafe Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lib_sillyboy.elf;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Elf32Header extends Elf.Header {
private final ElfParser parser;
public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {
this.bigEndian = bigEndian;
this.parser = parser;
final ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
type = parser.readHalf(buffer, 0x10);
phoff = parser.readWord(buffer, 0x1C);
shoff = | parser.readWord(buffer, 0x20); |
phentsize = parser.readHalf(buffer, 0x2A);
phnum = parser.readHalf(buffer, 0x2C);
shentsize = parser.readHalf(buffer, 0x2E);
shnum = parser.readHalf(buffer, 0x30);
shstrndx = parser.readHalf(buffer, 0x32);
}
@Override
public Elf.SectionHeader getSectionHeader(final int index) throws IOException {
return new Section32Header(parser, this, index);
}
@Override
public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {
return new Program32Header(parser, this, index);
}
@Override
public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)
throws IOException {
return new Dynamic32Structure(parser, this, baseOffset, index);
}
}
| lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java | DarrenTianYe-android_dynamic_load_so-7a70027 | [
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java",
"retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);",
"score": 121.72061066037143
},
{
"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": 93.99889079502294
},
{
"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": 93.79316872355449
},
{
"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": 90.37121889363544
},
{
"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": 88.39273421320814
}
] | 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": " final Field field = findField(clazz, fieldName);\n return field.getInt(null);\n } catch (Throwable thr) {\n return defVal;\n }\n }\n}",
"score": 11.608980312923347
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": " private static Handler getInlineFence() {\n synchronized (tinkerLogInlineFenceRef) {\n return tinkerLogInlineFenceRef[0];\n }\n }\n public static TinkerLogImp getDefaultImpl() {\n return debugLog;\n }\n public static void setTinkerLogImp(TinkerLogImp imp) {\n synchronized (tinkerLogImpRef) {",
"score": 11.254741789917416
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " */\n public static void reduceFieldArray(Object instance, String fieldName, int reduceSize)\n throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n if (reduceSize <= 0) {\n return;\n }\n Field jlrField = findField(instance, fieldName);\n Object[] original = (Object[]) jlrField.get(instance);\n int finalLength = original.length - reduceSize;\n if (finalLength <= 0) {",
"score": 11.170653474547892
},
{
"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": 10.829081452982475
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": " final Handler inlineFence = getInlineFence();\n if (inlineFence != null) {\n final Message msg = Message.obtain(inlineFence, priority, args);\n inlineFence.handleMessage(msg);\n msg.recycle();\n } else {\n debugLog.e(tag, \"!! NO_LOG_IMPL !! Original Log: \" + fmt, values);\n }\n }\n private static void printLog(String tag, Throwable thr, String fmt, Object... values) {",
"score": 10.693239036251432
}
] | 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/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": 37.609347304751125
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java",
"retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {",
"score": 30.836201375493857
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": " break;\n }\n }\n if (dynamicSectionOff == 0) {\n // No dynamic linking info, nothing to load\n return Collections.unmodifiableList(dependencies);\n }\n int i = 0;\n final List<Long> neededOffsets = new ArrayList<Long>();\n long vStringTableOff = 0;",
"score": 30.351114843375
},
{
"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": 26.690724715508843
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": "import java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\nimport java.nio.channels.FileChannel;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\npublic class ElfParser implements Closeable, Elf {\n private final int MAGIC = 0x464C457F;",
"score": 25.00819329946078
}
] | 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": 127.87151346510825
},
{
"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": 97.92105289425501
},
{
"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": 94.29338099286753
},
{
"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": 94.19121757296556
},
{
"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": 89.11100004219769
}
] | 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": 126.38636273600048
},
{
"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": 98.6440676765792
},
{
"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": 98.18028966291614
},
{
"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": 95.01639577519168
},
{
"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": 94.7666374558309
}
] | 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": 110.67229688913251
},
{
"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": 89.2461681081741
},
{
"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": 82.44217739685784
},
{
"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": 78.29192968387741
},
{
"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": 77.59268994590701
}
] | 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": 140.62816979281817
},
{
"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": 137.32363233607964
},
{
"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": 122.52880315724722
},
{
"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": 101.66893849120466
},
{
"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": 95.23834193584428
}
] | 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": 127.87151346510825
},
{
"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": 106.39667197756236
},
{
"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": 91.2146434592382
},
{
"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": 86.35783903257865
},
{
"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": 83.71484213732572
}
] | 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": 129.19596811069763
},
{
"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": 123.705346877226
},
{
"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": 109.43636415635396
},
{
"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": 96.82272536355978
},
{
"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": 93.7966737961722
}
] | java | parser.readWord(buffer, baseOffset + 0x8); |
/**
* Copyright 2015 - 2016 KeepSafe Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lib_sillyboy.elf;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Program64Header extends Elf.ProgramHeader {
public Program64Header(final ElfParser parser, final Elf.Header header, final long index)
throws IOException {
final ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
final long baseOffset = header.phoff + (index * header.phentsize);
type = parser.readWord(buffer, baseOffset);
| offset = parser.readLong(buffer, baseOffset + 0x8); |
vaddr = parser.readLong(buffer, baseOffset + 0x10);
memsz = parser.readLong(buffer, baseOffset + 0x28);
}
}
| lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java | DarrenTianYe-android_dynamic_load_so-7a70027 | [
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java",
"retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }",
"score": 115.69556415474197
},
{
"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": 109.59760632123037
},
{
"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": 104.69091341175522
},
{
"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": 89.69692760255789
},
{
"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": 86.83164869889754
}
] | 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": 145.35515307083324
},
{
"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": 137.9197853274264
},
{
"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": 119.83103238897037
},
{
"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": 103.99495131055257
},
{
"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": 100.968899743165
}
] | java | = parser.readWord(buffer, baseOffset + 0x14); |
/**
* Copyright 2015 - 2016 KeepSafe Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lib_sillyboy.elf;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class Program32Header extends Elf.ProgramHeader {
public Program32Header(final ElfParser parser, final Elf.Header header, final long index)
throws IOException {
final ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);
final long baseOffset = header.phoff + (index * header.phentsize);
type = parser.readWord(buffer, baseOffset);
| offset = parser.readWord(buffer, baseOffset + 0x4); |
vaddr = parser.readWord(buffer, baseOffset + 0x8);
memsz = parser.readWord(buffer, baseOffset + 0x14);
}
}
| lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java | DarrenTianYe-android_dynamic_load_so-7a70027 | [
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java",
"retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }",
"score": 112.45833257446223
},
{
"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": 112.4423551467664
},
{
"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": 98.21074765109785
},
{
"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": 92.72297916994548
},
{
"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": 89.69692760255789
}
] | java | offset = parser.readWord(buffer, baseOffset + 0x4); |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Decodable, Inc.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package co.decodable.sdk.pipeline.internal.config;
import co.decodable.sdk.pipeline.StartupMode;
import co.decodable.sdk.pipeline.util.Unmodifiable;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.ConsumerConfig;
public class StreamConfig {
/** Used by Flink to prefix all pass-through options for the Kafka producer/consumer. */
private static final String PROPERTIES_PREFIX = "properties.";
private final String id;
private final String name;
private final String bootstrapServers;
private final String topic;
private final StartupMode startupMode;
private final String transactionalIdPrefix;
private final String deliveryGuarantee;
@Unmodifiable private final Map<String, String> properties;
public StreamConfig(String id, String name, Map<String, String> properties) {
this.id = id;
this.name = name;
this.bootstrapServers =
properties.get(PROPERTIES_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG);
this.topic = properties.get("topic");
this.startupMode | = StartupMode.fromString(properties.get("scan.startup.mode")); |
this.transactionalIdPrefix = properties.get("sink.transactional-id-prefix");
this.deliveryGuarantee = properties.get("sink.delivery-guarantee");
this.properties =
properties.entrySet().stream()
.filter(e -> e.getKey().startsWith("properties"))
.collect(
Collectors.toUnmodifiableMap(e -> e.getKey().substring(11), e -> e.getValue()));
}
public String id() {
return id;
}
public String name() {
return name;
}
public String bootstrapServers() {
return bootstrapServers;
}
public String topic() {
return topic;
}
public StartupMode startupMode() {
return startupMode;
}
public String transactionalIdPrefix() {
return transactionalIdPrefix;
}
public String deliveryGuarantee() {
return deliveryGuarantee;
}
public Map<String, String> kafkaProperties() {
return properties;
}
}
| sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java | decodableco-decodable-pipeline-sdk-af78b8a | [
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java",
"retrieved_chunk": " private final String topic;\n public StreamConfiguration(String name) {\n this.name = name;\n this.id = getRandomId();\n this.topic = \"stream-00000000-\" + id;\n }\n private static String getRandomId() {\n int digits = 8;\n return String.format(\"%0\" + digits + \"x\", new BigInteger(digits * 4, new SecureRandom()));\n }",
"score": 62.56114515026291
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java",
"retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;",
"score": 56.74111270041755
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java",
"retrieved_chunk": " return new TestEnvironment(bootstrapServers, streams);\n }\n }\n private static final String STREAM_CONFIG_TEMPLATE =\n \"{\\n\"\n + \" \\\"properties\\\": {\\n\"\n + \" \\\"value.format\\\": \\\"debezium-json\\\",\\n\"\n + \" \\\"key.format\\\": \\\"json\\\",\\n\"\n + \" \\\"topic\\\": \\\"%s\\\",\\n\"\n + \" \\\"scan.startup.mode\\\": \\\"earliest-offset\\\",\\n\"",
"score": 51.07105104830921
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java",
"retrieved_chunk": " public String name() {\n return name;\n }\n public String id() {\n return id;\n }\n public String topic() {\n return topic;\n }\n }",
"score": 47.91735421407428
},
{
"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": 45.7247369361974
}
] | java | = StartupMode.fromString(properties.get("scan.startup.mode")); |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Decodable, Inc.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package co.decodable.sdk.pipeline.internal;
import co.decodable.sdk.pipeline.DecodableStreamSink;
import co.decodable.sdk.pipeline.DecodableStreamSinkBuilder;
import co.decodable.sdk.pipeline.EnvironmentAccess;
import co.decodable.sdk.pipeline.internal.config.StreamConfig;
import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
public class DecodableStreamSinkBuilderImpl<T> implements DecodableStreamSinkBuilder<T> {
private String streamId;
private String streamName;
private SerializationSchema<T> serializationSchema;
@Override
public DecodableStreamSinkBuilder<T> withStreamName(String streamName) {
this.streamName = streamName;
return this;
}
@Override
public DecodableStreamSinkBuilder<T> withStreamId(String streamId) {
this.streamId = streamId;
return this;
}
@Override
public DecodableStreamSinkBuilder<T> withSerializationSchema(
SerializationSchema<T> serializationSchema) {
this.serializationSchema = serializationSchema;
return this;
}
@Override
public DecodableStreamSink<T> build() {
Objects.requireNonNull(serializationSchema, "serializationSchema");
Map<String, String> environment =
EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();
StreamConfig streamConfig =
new StreamConfigMapping(environment).determineConfig(streamName, streamId);
KafkaSink<T> delegate =
KafkaSink.<T>builder()
.setBootstrapServers(streamConfig.bootstrapServers())
.setRecordSerializer(
KafkaRecordSerializationSchema.builder()
.setTopic(streamConfig.topic())
.setValueSerializationSchema(serializationSchema)
.build())
.setDeliveryGuarantee(
"exactly-once".equals(streamConfig.deliveryGuarantee())
? DeliveryGuarantee.EXACTLY_ONCE
: "at-least-once".equals(streamConfig.deliveryGuarantee())
? DeliveryGuarantee.AT_LEAST_ONCE
: DeliveryGuarantee.NONE)
.setTransactionalIdPrefix | (streamConfig.transactionalIdPrefix())
.setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties()))
.build(); |
return new DecodableStreamSinkImpl<T>(delegate);
}
private static Properties toProperties(Map<String, String> map) {
Properties p = new Properties();
p.putAll(map);
return p;
}
}
| sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java | decodableco-decodable-pipeline-sdk-af78b8a | [
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java",
"retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),",
"score": 50.98791201345016
},
{
"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": 32.07931971422242
},
{
"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": 24.87394611581828
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " streamConfig = configsByStreamName.get(streamName);\n if (streamConfig == null) {\n throw new IllegalStateException(\n String.format(\n \"No topic name could be determined for stream with name '%s'\", streamName));\n }\n }\n } else {\n if (streamId != null) {\n streamConfig = configsByStreamId.get(streamId);",
"score": 21.510121944819875
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java",
"retrieved_chunk": " + \" \\\"properties.compression.type\\\": \\\"zstd\\\",\\n\"\n + \" \\\"properties.enable.idempotence\\\": \\\"true\\\"\\n\"\n + \" },\\n\"\n + \" \\\"name\\\": \\\"shipments\\\"\\n\"\n + \"}\";\n StreamConfigMapping streamConfigMapping =\n new StreamConfigMapping(Map.of(\"DECODABLE_STREAM_CONFIG_078fc8b5\", config));\n StreamConfig streamConfig = streamConfigMapping.determineConfig(null, \"078fc8b5\");\n assertEquals(\"078fc8b5\", streamConfig.id());\n assertEquals(\"shipments\", streamConfig.name());",
"score": 20.943470397507518
}
] | 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/testing/TestEnvironment.java",
"retrieved_chunk": " streams.put(firstStream, new StreamConfiguration(firstStream));\n if (furtherStreams != null) {\n for (String stream : furtherStreams) {\n streams.put(stream, new StreamConfiguration(stream));\n }\n }\n return this;\n }\n /** Returns a new {@link TestEnvironment} for the given configuration. */\n public TestEnvironment build() {",
"score": 35.00632173040811
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java",
"retrieved_chunk": "import java.util.Map;\nimport java.util.stream.Collectors;\nimport org.apache.kafka.clients.consumer.ConsumerConfig;\npublic class StreamConfig {\n /** Used by Flink to prefix all pass-through options for the Kafka producer/consumer. */\n private static final String PROPERTIES_PREFIX = \"properties.\";\n private final String id;\n private final String name;\n private final String bootstrapServers;\n private final String topic;",
"score": 34.431542554021455
},
{
"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": 32.02645283522188
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java",
"retrieved_chunk": " return id;\n }\n public String name() {\n return name;\n }\n public String bootstrapServers() {\n return bootstrapServers;\n }\n public String topic() {\n return topic;",
"score": 30.528558344819054
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java",
"retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;",
"score": 29.793967650650302
}
] | 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": 72.46571769382523
},
{
"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": 34.44570365205622
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java",
"retrieved_chunk": " + \" \\\"properties.compression.type\\\": \\\"zstd\\\",\\n\"\n + \" \\\"properties.enable.idempotence\\\": \\\"true\\\"\\n\"\n + \" },\\n\"\n + \" \\\"name\\\": \\\"shipments\\\"\\n\"\n + \"}\";\n StreamConfigMapping streamConfigMapping =\n new StreamConfigMapping(Map.of(\"DECODABLE_STREAM_CONFIG_078fc8b5\", config));\n StreamConfig streamConfig = streamConfigMapping.determineConfig(null, \"078fc8b5\");\n assertEquals(\"078fc8b5\", streamConfig.id());\n assertEquals(\"shipments\", streamConfig.name());",
"score": 33.451017293468176
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " streamConfig = configsByStreamName.get(streamName);\n if (streamConfig == null) {\n throw new IllegalStateException(\n String.format(\n \"No topic name could be determined for stream with name '%s'\", streamName));\n }\n }\n } else {\n if (streamId != null) {\n streamConfig = configsByStreamId.get(streamId);",
"score": 32.878743870481586
},
{
"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": 32.625265440952916
}
] | java | setTopics(streamConfig.topic())
.setProperties(toProperties(streamConfig.kafkaProperties()))
.setValueOnlyDeserializer(deserializationSchema); |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Decodable, Inc.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package co.decodable.sdk.pipeline.internal;
import co.decodable.sdk.pipeline.DecodableSourceSplit;
import java.io.IOException;
import org.apache.flink.connector.kafka.source.split.KafkaPartitionSplit;
import org.apache.flink.core.io.SimpleVersionedSerializer;
public class DelegatingSplitSerializer implements SimpleVersionedSerializer<DecodableSourceSplit> {
private final SimpleVersionedSerializer<KafkaPartitionSplit> delegate;
public DelegatingSplitSerializer(SimpleVersionedSerializer<KafkaPartitionSplit> delegate) {
this.delegate = delegate;
}
@Override
public int getVersion() {
return delegate.getVersion();
}
@Override
public byte[] serialize(DecodableSourceSplit obj) throws IOException {
return delegate.serialize( | ((DecodableSourceSplitImpl) obj).getDelegate()); |
}
@Override
public DecodableSourceSplit deserialize(int version, byte[] serialized) throws IOException {
return new DecodableSourceSplitImpl(delegate.deserialize(version, serialized));
}
}
| sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingSplitSerializer.java | decodableco-decodable-pipeline-sdk-af78b8a | [
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingEnumeratorStateSerializer.java",
"retrieved_chunk": " public int getVersion() {\n return delegate.getVersion();\n }\n @Override\n public byte[] serialize(DecodableSourceEnumeratorState obj) throws IOException {\n return delegate.serialize(((DecodableSourceEnumeratorStateImpl) obj).getDelegate());\n }\n @Override\n public DecodableSourceEnumeratorState deserialize(int version, byte[] serialized)\n throws IOException {",
"score": 84.29580574462011
},
{
"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": 31.776234288089476
},
{
"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": 26.19525576667827
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingSplitEnumerator.java",
"retrieved_chunk": " }\n @Override\n public void addSplitsBack(List<DecodableSourceSplit> splits, int subtaskId) {\n List<KafkaPartitionSplit> delegateSplits =\n splits.stream()\n .map(s -> ((DecodableSourceSplitImpl) s).getDelegate())\n .collect(Collectors.toList());\n delegate.addSplitsBack(delegateSplits, subtaskId);\n }\n @Override",
"score": 25.187590774454616
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingSourceReader.java",
"retrieved_chunk": " public InputStatus pollNext(ReaderOutput<T> output) throws Exception {\n return delegate.pollNext(output);\n }\n @Override\n public List<DecodableSourceSplit> snapshotState(long checkpointId) {\n return delegate.snapshotState(checkpointId).stream()\n .map(DecodableSourceSplitImpl::new)\n .collect(Collectors.toList());\n }\n @Override",
"score": 24.749409835252145
}
] | java | ((DecodableSourceSplitImpl) obj).getDelegate()); |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Decodable, Inc.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package co.decodable.sdk.pipeline.testing;
import co.decodable.sdk.pipeline.EnvironmentAccess;
import co.decodable.sdk.pipeline.util.Incubating;
import java.lang.System.Logger.Level;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
/**
* Provides access to Decodable streams during testing as well as the ability to run custom Flink
* jobs.
*/
@Incubating
public class PipelineTestContext implements AutoCloseable {
private static final System.Logger LOGGER = System.getLogger(PipelineTestContext.class.getName());
private final TestEnvironment testEnvironment;
private final KafkaProducer<String, String> producer;
private final Map<String, DecodableStreamImpl> streams;
private final ExecutorService executorService;
/** Creates a new testing context, using the given {@link TestEnvironment}. */
public PipelineTestContext(TestEnvironment testEnvironment) {
EnvironmentAccess.setEnvironment(testEnvironment);
this.testEnvironment = testEnvironment;
this.producer =
new KafkaProducer<String, String>( | producerProperties(testEnvironment.bootstrapServers())); |
this.streams = new HashMap<>();
this.executorService = Executors.newCachedThreadPool();
}
private static Properties producerProperties(String bootstrapServers) {
var props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
return props;
}
private static Properties consumerProperties(String bootstrapServers) {
var consumerProps = new Properties();
consumerProps.put("bootstrap.servers", bootstrapServers);
consumerProps.put(
"key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumerProps.put(
"value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumerProps.put("auto.offset.reset", "earliest");
consumerProps.put("group.id", "my-group");
return consumerProps;
}
/** Returns a stream for the given name. */
public DecodableStream<String> stream(String name) {
KafkaConsumer<String, String> consumer =
new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers()));
consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name)));
return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer));
}
/** Asynchronously executes the given Flink job main method. */
public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args)
throws Exception {
executorService.submit(
() -> {
try {
jobMainMethod.accept(args);
} catch (InterruptedException e) {
LOGGER.log(Level.INFO, "Job aborted");
} catch (Exception e) {
LOGGER.log(Level.ERROR, "Job failed", e);
}
});
}
@Override
public void close() throws Exception {
try {
producer.close();
executorService.shutdownNow();
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
for (DecodableStreamImpl stream : streams.values()) {
stream.consumer.close();
}
} catch (Exception e) {
throw new RuntimeException("Couldn't close testing context", e);
} finally {
EnvironmentAccess.resetEnvironment();
}
}
/**
* A {@link Consumer} variant which allows for declared checked exception types.
*
* @param <T> The consumed data type.
*/
@FunctionalInterface
public interface ThrowingConsumer<T> {
void accept(T t) throws Exception;
}
private class DecodableStreamImpl implements DecodableStream<String> {
private final String streamName;
private final KafkaConsumer<String, String> consumer;
private final List<ConsumerRecord<String, String>> consumed;
public DecodableStreamImpl(String streamName, KafkaConsumer<String, String> consumer) {
this.streamName = streamName;
this.consumer = consumer;
this.consumed = new ArrayList<>();
}
@Override
public void add(StreamRecord<String> streamRecord) {
Future<RecordMetadata> sent =
producer.send(
new ProducerRecord<>(testEnvironment.topicFor(streamName), streamRecord.value()));
// wait for record to be ack-ed
try {
sent.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Couldn't send record", e);
}
}
@Override
public Future<StreamRecord<String>> takeOne() {
return ((CompletableFuture<List<StreamRecord<String>>>) take(1)).thenApply(l -> l.get(0));
}
@Override
public Future<List<StreamRecord<String>>> take(int n) {
return CompletableFuture.supplyAsync(
() -> {
while (consumed.size() < n) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(20));
for (ConsumerRecord<String, String> record : records) {
consumed.add(record);
}
}
List<StreamRecord<String>> result =
consumed.subList(0, n).stream()
.map(cr -> new StreamRecord<>(cr.value()))
.collect(Collectors.toList());
consumed.subList(0, n).clear();
return result;
},
executorService);
}
}
}
| sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java | decodableco-decodable-pipeline-sdk-af78b8a | [
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java",
"retrieved_chunk": " + \"}\";\n @Unmodifiable private final Map<String, StreamConfiguration> streams;\n private final String bootstrapServers;\n private TestEnvironment(String bootstrapServers, Map<String, StreamConfiguration> streams) {\n this.bootstrapServers = bootstrapServers;\n this.streams = Collections.unmodifiableMap(streams);\n }\n /** Returns a builder for creating a new {@link TestEnvironment}. */\n public static Builder builder() {\n return new Builder();",
"score": 53.567912214842295
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/DataStreamJobTest.java",
"retrieved_chunk": "@Testcontainers // @start region=\"testing-custom-pipeline\"\npublic class DataStreamJobTest {\n private static final String PURCHASE_ORDERS = \"purchase-orders\";\n private static final String PURCHASE_ORDERS_PROCESSED = \"purchase-orders-processed\";\n @Container\n public RedpandaContainer broker =\n new RedpandaContainer(\"docker.redpanda.com/redpandadata/redpanda:v23.1.2\");\n @Test\n public void shouldUpperCaseCustomerName() throws Exception {\n TestEnvironment testEnvironment =",
"score": 45.610780508726954
},
{
"filename": "examples/apache-maven/custom-pipelines-hello-world/src/test/java/co/decodable/examples/cpdemo/DataStreamJobTest.java",
"retrieved_chunk": "public class DataStreamJobTest {\n\tprivate static final String PURCHASE_ORDERS = \"purchase-orders\";\n\tprivate static final String PURCHASE_ORDERS_PROCESSED = \"purchase-orders-processed\";\n\t@Container\n\tpublic RedpandaContainer broker = new RedpandaContainer(\"docker.redpanda.com/redpandadata/redpanda:v23.1.2\");\n\t@Test\n\tpublic void shouldUpperCaseCustomerName() throws Exception {\n\t\tTestEnvironment testEnvironment = TestEnvironment.builder()\n\t\t\t\t.withBootstrapServers(broker.getBootstrapServers())\n\t\t\t\t.withStreams(PURCHASE_ORDERS, PURCHASE_ORDERS_PROCESSED)",
"score": 44.94229947436812
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/DataStreamJobTest.java",
"retrieved_chunk": " TestEnvironment.builder()\n .withBootstrapServers(broker.getBootstrapServers())\n .withStreams(PURCHASE_ORDERS, PURCHASE_ORDERS_PROCESSED)\n .build();\n try (PipelineTestContext ctx = new PipelineTestContext(testEnvironment)) {\n String value =\n \"{\\n\"\n + \" \\\"order_id\\\" : 19001,\\n\"\n + \" \\\"order_date\\\" : \\\"2023-06-09 10:18:38\\\",\\n\"\n + \" \\\"customer_name\\\" : \\\"Yolanda Hagenes\\\",\\n\"",
"score": 37.86989945499735
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java",
"retrieved_chunk": "import java.util.Map;\nimport java.util.stream.Collectors;\nimport org.apache.kafka.clients.consumer.ConsumerConfig;\npublic class StreamConfig {\n /** Used by Flink to prefix all pass-through options for the Kafka producer/consumer. */\n private static final String PROPERTIES_PREFIX = \"properties.\";\n private final String id;\n private final String name;\n private final String bootstrapServers;\n private final String topic;",
"score": 37.8589824085374
}
] | 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": 50.98791201345016
},
{
"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": 32.07931971422242
},
{
"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": 27.832380250913335
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " streamConfig = configsByStreamName.get(streamName);\n if (streamConfig == null) {\n throw new IllegalStateException(\n String.format(\n \"No topic name could be determined for stream with name '%s'\", streamName));\n }\n }\n } else {\n if (streamId != null) {\n streamConfig = configsByStreamId.get(streamId);",
"score": 21.510121944819875
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java",
"retrieved_chunk": " + \" \\\"properties.compression.type\\\": \\\"zstd\\\",\\n\"\n + \" \\\"properties.enable.idempotence\\\": \\\"true\\\"\\n\"\n + \" },\\n\"\n + \" \\\"name\\\": \\\"shipments\\\"\\n\"\n + \"}\";\n StreamConfigMapping streamConfigMapping =\n new StreamConfigMapping(Map.of(\"DECODABLE_STREAM_CONFIG_078fc8b5\", config));\n StreamConfig streamConfig = streamConfigMapping.determineConfig(null, \"078fc8b5\");\n assertEquals(\"078fc8b5\", streamConfig.id());\n assertEquals(\"shipments\", streamConfig.name());",
"score": 20.943470397507518
}
] | java | .setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties()))
.build(); |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Decodable, Inc.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package co.decodable.sdk.pipeline.testing;
import co.decodable.sdk.pipeline.EnvironmentAccess;
import co.decodable.sdk.pipeline.util.Incubating;
import java.lang.System.Logger.Level;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
/**
* Provides access to Decodable streams during testing as well as the ability to run custom Flink
* jobs.
*/
@Incubating
public class PipelineTestContext implements AutoCloseable {
private static final System.Logger LOGGER = System.getLogger(PipelineTestContext.class.getName());
private final TestEnvironment testEnvironment;
private final KafkaProducer<String, String> producer;
private final Map<String, DecodableStreamImpl> streams;
private final ExecutorService executorService;
/** Creates a new testing context, using the given {@link TestEnvironment}. */
public PipelineTestContext(TestEnvironment testEnvironment) {
EnvironmentAccess.setEnvironment(testEnvironment);
this.testEnvironment = testEnvironment;
this.producer =
new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers()));
this.streams = new HashMap<>();
this.executorService = Executors.newCachedThreadPool();
}
private static Properties producerProperties(String bootstrapServers) {
var props = new Properties();
props.put("bootstrap.servers", bootstrapServers);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
return props;
}
private static Properties consumerProperties(String bootstrapServers) {
var consumerProps = new Properties();
consumerProps.put("bootstrap.servers", bootstrapServers);
consumerProps.put(
"key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumerProps.put(
"value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
consumerProps.put("auto.offset.reset", "earliest");
consumerProps.put("group.id", "my-group");
return consumerProps;
}
/** Returns a stream for the given name. */
public DecodableStream<String> stream(String name) {
KafkaConsumer<String, String> consumer =
new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers()));
consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name)));
return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer));
}
/** Asynchronously executes the given Flink job main method. */
public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args)
throws Exception {
executorService.submit(
() -> {
try {
jobMainMethod.accept(args);
} catch (InterruptedException e) {
LOGGER.log(Level.INFO, "Job aborted");
} catch (Exception e) {
LOGGER.log(Level.ERROR, "Job failed", e);
}
});
}
@Override
public void close() throws Exception {
try {
producer.close();
executorService.shutdownNow();
executorService.awaitTermination(100, TimeUnit.MILLISECONDS);
for (DecodableStreamImpl stream : streams.values()) {
stream.consumer.close();
}
} catch (Exception e) {
throw new RuntimeException("Couldn't close testing context", e);
} finally {
EnvironmentAccess.resetEnvironment();
}
}
/**
* A {@link Consumer} variant which allows for declared checked exception types.
*
* @param <T> The consumed data type.
*/
@FunctionalInterface
public interface ThrowingConsumer<T> {
void accept(T t) throws Exception;
}
private class DecodableStreamImpl implements DecodableStream<String> {
private final String streamName;
private final KafkaConsumer<String, String> consumer;
private final List<ConsumerRecord<String, String>> consumed;
public DecodableStreamImpl(String streamName, KafkaConsumer<String, String> consumer) {
this.streamName = streamName;
this.consumer = consumer;
this.consumed = new ArrayList<>();
}
@Override
public void add(StreamRecord<String> streamRecord) {
Future<RecordMetadata> sent =
producer.send(
new ProducerRecord<> | (testEnvironment.topicFor(streamName), streamRecord.value())); |
// wait for record to be ack-ed
try {
sent.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException("Couldn't send record", e);
}
}
@Override
public Future<StreamRecord<String>> takeOne() {
return ((CompletableFuture<List<StreamRecord<String>>>) take(1)).thenApply(l -> l.get(0));
}
@Override
public Future<List<StreamRecord<String>>> take(int n) {
return CompletableFuture.supplyAsync(
() -> {
while (consumed.size() < n) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(20));
for (ConsumerRecord<String, String> record : records) {
consumed.add(record);
}
}
List<StreamRecord<String>> result =
consumed.subList(0, n).stream()
.map(cr -> new StreamRecord<>(cr.value()))
.collect(Collectors.toList());
consumed.subList(0, n).clear();
return result;
},
executorService);
}
}
}
| sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java | decodableco-decodable-pipeline-sdk-af78b8a | [
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/DecodableStream.java",
"retrieved_chunk": "import java.util.concurrent.Future;\n/**\n * Represents a data stream on the Decodable platform.\n *\n * @param <T> The element type of this stream\n */\n@Incubating\npublic interface DecodableStream<T> {\n /** Adds the given stream record to this stream. */\n void add(StreamRecord<T> streamRecord);",
"score": 29.06777489733414
},
{
"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": 25.99466758807488
},
{
"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": 23.49796320650876
},
{
"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": 21.084966942094052
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/DecodableStream.java",
"retrieved_chunk": " /** Retrieves one element from this stream. */\n Future<StreamRecord<T>> takeOne();\n /** Retrieves {@code n} elements from this stream. */\n Future<List<StreamRecord<T>>> take(int n);\n}",
"score": 19.5063556962672
}
] | 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": 72.46571769382523
},
{
"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": 34.44570365205622
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java",
"retrieved_chunk": " + \" \\\"properties.compression.type\\\": \\\"zstd\\\",\\n\"\n + \" \\\"properties.enable.idempotence\\\": \\\"true\\\"\\n\"\n + \" },\\n\"\n + \" \\\"name\\\": \\\"shipments\\\"\\n\"\n + \"}\";\n StreamConfigMapping streamConfigMapping =\n new StreamConfigMapping(Map.of(\"DECODABLE_STREAM_CONFIG_078fc8b5\", config));\n StreamConfig streamConfig = streamConfigMapping.determineConfig(null, \"078fc8b5\");\n assertEquals(\"078fc8b5\", streamConfig.id());\n assertEquals(\"shipments\", streamConfig.name());",
"score": 33.451017293468176
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " streamConfig = configsByStreamName.get(streamName);\n if (streamConfig == null) {\n throw new IllegalStateException(\n String.format(\n \"No topic name could be determined for stream with name '%s'\", streamName));\n }\n }\n } else {\n if (streamId != null) {\n streamConfig = configsByStreamId.get(streamId);",
"score": 32.878743870481586
},
{
"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": 32.625265440952916
}
] | java | toProperties(streamConfig.kafkaProperties()))
.setValueOnlyDeserializer(deserializationSchema); |
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright Decodable, Inc.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package co.decodable.sdk.pipeline.internal;
import co.decodable.sdk.pipeline.DecodableStreamSource;
import co.decodable.sdk.pipeline.DecodableStreamSourceBuilder;
import co.decodable.sdk.pipeline.EnvironmentAccess;
import co.decodable.sdk.pipeline.StartupMode;
import co.decodable.sdk.pipeline.internal.config.StreamConfig;
import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.KafkaSourceBuilder;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
public class DecodableStreamSourceBuilderImpl<T> implements DecodableStreamSourceBuilder<T> {
private String streamId;
private String streamName;
private StartupMode startupMode;
private DeserializationSchema<T> deserializationSchema;
@Override
public DecodableStreamSourceBuilder<T> withStreamName(String streamName) {
this.streamName = streamName;
return this;
}
@Override
public DecodableStreamSourceBuilder<T> withStreamId(String streamId) {
this.streamId = streamId;
return this;
}
@Override
public DecodableStreamSourceBuilder<T> withStartupMode(StartupMode startupMode) {
this.startupMode = startupMode;
return this;
}
@Override
public DecodableStreamSourceBuilder<T> withDeserializationSchema(
DeserializationSchema<T> deserializationSchema) {
this.deserializationSchema = deserializationSchema;
return this;
}
@Override
public DecodableStreamSource<T> build() {
Objects.requireNonNull(deserializationSchema, "deserializationSchema");
Map<String, String> environment =
EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();
StreamConfig streamConfig =
new StreamConfigMapping(environment).determineConfig(streamName, streamId);
KafkaSourceBuilder<T> builder =
KafkaSource.<T>builder()
.setBootstrapServers(streamConfig.bootstrapServers())
.setTopics(streamConfig.topic())
.setProperties(toProperties(streamConfig.kafkaProperties()))
.setValueOnlyDeserializer(deserializationSchema);
| if (streamConfig.startupMode() != null) { |
builder.setStartingOffsets(toOffsetsInitializer(streamConfig.startupMode()));
} else if (startupMode != null) {
builder.setStartingOffsets(toOffsetsInitializer(startupMode));
}
KafkaSource<T> delegate = builder.build();
return new DecodableStreamSourceImpl<T>(delegate);
}
private static Properties toProperties(Map<String, String> map) {
Properties p = new Properties();
p.putAll(map);
return p;
}
private OffsetsInitializer toOffsetsInitializer(StartupMode startupMode) {
switch (startupMode) {
case EARLIEST_OFFSET:
return OffsetsInitializer.earliest();
case LATEST_OFFSET:
return OffsetsInitializer.latest();
default:
throw new IllegalArgumentException("Unexpected startup mode: " + startupMode);
}
}
}
| sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java | decodableco-decodable-pipeline-sdk-af78b8a | [
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java",
"retrieved_chunk": " @Override\n public DecodableStreamSink<T> build() {\n Objects.requireNonNull(serializationSchema, \"serializationSchema\");\n Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSink<T> delegate =\n KafkaSink.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())",
"score": 76.90848924451915
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " streamConfig = configsByStreamName.get(streamName);\n if (streamConfig == null) {\n throw new IllegalStateException(\n String.format(\n \"No topic name could be determined for stream with name '%s'\", streamName));\n }\n }\n } else {\n if (streamId != null) {\n streamConfig = configsByStreamId.get(streamId);",
"score": 47.35594294420544
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " }\n }\n }\n }\n public StreamConfig determineConfig(String streamName, String streamId) {\n StreamConfig streamConfig = null;\n if (streamName != null) {\n if (streamId != null) {\n throw new IllegalStateException(\"Only one of stream name or stream id may be specified\");\n } else {",
"score": 44.976850635906466
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java",
"retrieved_chunk": " + \" \\\"properties.compression.type\\\": \\\"zstd\\\",\\n\"\n + \" \\\"properties.enable.idempotence\\\": \\\"true\\\"\\n\"\n + \" },\\n\"\n + \" \\\"name\\\": \\\"shipments\\\"\\n\"\n + \"}\";\n StreamConfigMapping streamConfigMapping =\n new StreamConfigMapping(Map.of(\"DECODABLE_STREAM_CONFIG_078fc8b5\", config));\n StreamConfig streamConfig = streamConfigMapping.determineConfig(null, \"078fc8b5\");\n assertEquals(\"078fc8b5\", streamConfig.id());\n assertEquals(\"shipments\", streamConfig.name());",
"score": 41.65619817075897
},
{
"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": 41.58866238475334
}
] | java | if (streamConfig.startupMode() != null) { |
package com.home.chat.services;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.home.chat.controllers.request.Message;
import com.home.chat.controllers.request.QueryUserBalanceRequest;
import com.home.chat.controllers.response.QueryBalanceResponse;
import com.home.chat.controllers.response.QueryUserBalanceResponse;
import com.home.chat.dao.TbApikeyDAO;
import com.home.chat.dao.TbUserKeyDAO;
import com.home.chat.domain.OpenAiConfig;
import com.home.chat.domain.ChatWebConfig;
import com.home.chat.pojo.entity.TbApikeyEntity;
import com.home.chat.pojo.entity.TbUserKeyEntity;
import com.home.chat.pojo.query.TbApikeyQuery;
import com.home.chat.pojo.query.TbUserKeyQuery;
import com.home.chat.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class ChatGPTService {
private final OpenAiConfig openAiConfig;
private final ChatWebConfig xinQiuConfig;
@Autowired
TbApikeyDAO tbApikeyDAO;
@Autowired
TbUserKeyDAO tbUserKeyDAO;
public QueryBalanceResponse creditQuery(String key) {
String apikey = openAiConfig.getApiKey();
if (StrUtil.isNotBlank(key)) {
apikey = key;
}
String result = HttpRequest.get(openAiConfig.getCreditApi())
.header(Header.CONTENT_TYPE, "application/json")
.header(Header.AUTHORIZATION, "Bearer " + apikey)
.execute().body();
if (result.contains("server_error")) {
throw new RuntimeException("请求ChatGPT官方服务器出错");
}
JSONObject jsonObject = JSONUtil.parseObj(result);
// 返回结果
return QueryBalanceResponse.builder()
.balances(jsonObject.getStr("total_available"))
.build();
}
private void genImage(Message message, String key, Consumer<String> send) {
// 请求参数
Map<String, String> userMessage = MapUtil.of(
"size", "512x512"
);
userMessage.put("prompt", message.getMessage().get(0));
// 调用接口
String result = HttpRequest.post(openAiConfig.getImageApi())
.header(Header.CONTENT_TYPE, "application/json")
.header(Header.AUTHORIZATION, "Bearer " + key)
.body(JSONUtil.toJsonStr(userMessage))
.execute().body();
// 正则匹配出结果
Pattern p = Pattern.compile("\"url\": \"(.*?)\"");
Matcher m = p.matcher(result);
if (m.find()) {
send.accept(m.group(1));
//扣除次数
tbUserKeyDAO.useOnece(3,message.getApiKey());
} else {
send.accept("图片生成失败!");
}
}
public void sendResponse(Message message, Consumer<String> send) throws IOException {
TbUserKeyQuery userKeyQuery = new TbUserKeyQuery();
userKeyQuery.setUserKey(message.getApiKey());
TbUserKeyEntity tbUserKeyEntity = tbUserKeyDAO.queryForObject(userKeyQuery);
if(StringUtils.isBlank(message.getApiKey()) || tbUserKeyEntity == null || !tbUserKeyEntity.getValidStatus().equals("1")){
send.accept("user key无效,请在页面左下角设置正确的key!");
return;
}
if(tbUserKeyEntity.getRemainingCount() <= 0){
send.accept("user key次数已耗尽!");
return;
}
TbApikeyQuery apikeyQuery = new TbApikeyQuery();
apikeyQuery.setValidStatus("1");
apikeyQuery.setEndDate(DateUtil.getCurrDate());
apikeyQuery.setOrder("balance desc,use_times asc");
TbApikeyEntity tbApikeyEntity = tbApikeyDAO.queryForObject(apikeyQuery);
String key = tbApikeyEntity.getApiKey();
| tbApikeyDAO.useOnece(key); |
if (Objects.equals(message.getType(), Message.MessageType.IMAGE)) {
genImage(message, key, send);
return;
}
// 构建对话参数
List<Map<String, String>> messages = message.getMessage().stream().map(msg -> {
Map<String, String> userMessage = MapUtil.of(
"role", "user"
);
userMessage.put("content", msg);
return userMessage;
}).collect(Collectors.toList());
// 构建请求参数
HashMap<Object, Object> params = new HashMap<>();
params.put("stream", true);
params.put("model", openAiConfig.getModel());
params.put("messages", messages);
// 调用接口
HttpResponse result;
try {
result = HttpRequest.post(openAiConfig.getOpenaiApi())
.header(Header.CONTENT_TYPE, "application/json")
.header(Header.AUTHORIZATION, "Bearer " + key)
.body(JSONUtil.toJsonStr(params))
.executeAsync();
} catch (Exception e) {
send.accept(String.join("", "出错了", e.getMessage()));
send.accept("END");
return;
}
// 处理数据
String line;
assert result != null;
BufferedReader reader = new BufferedReader(new InputStreamReader(result.bodyStream()));
boolean printErrorMsg = false;
StringBuilder errMsg = new StringBuilder();
Boolean userflag = false;
while ((line = reader.readLine()) != null) {
String msgResult = UnicodeUtil.toString(line);
// 正则匹配错误信息
if (msgResult.contains("\"error\":")) {
printErrorMsg = true;
}
// 如果出错,打印错误信息
if (printErrorMsg) {
errMsg.append(msgResult);
} else if (msgResult.contains("content")) {
String data = JSONUtil.parseObj(line.substring(5)).getByPath("choices[0].delta.content").toString();
send.accept(data);
//扣除次数
userflag = true;
}
}
if(userflag){
//这里可以调整消耗次数
tbUserKeyDAO.useOnece(message.getMessage().size() > 1 ? message.getMessage().size()/2 : 1,message.getApiKey());
}
// 关闭流
reader.close();
// 如果出错,抛出异常
if (printErrorMsg) {
send.accept(errMsg.toString());
send.accept("END");
}
send.accept("END");
}
public QueryUserBalanceResponse queryUserBalance(QueryUserBalanceRequest request){
QueryUserBalanceResponse response = new QueryUserBalanceResponse();
TbUserKeyQuery query = new TbUserKeyQuery();
query.setUserKey(request.getKey());
TbUserKeyEntity tbUserKeyEntity = tbUserKeyDAO.queryForObject(query);
if(tbUserKeyEntity == null){
return response;
}
response.setExpireDate(tbUserKeyEntity.getExpireDate());
response.setRemainingCount(tbUserKeyEntity.getRemainingCount());
return response;
}
}
| src/main/java/com/home/chat/services/ChatGPTService.java | dd8023dd-chatgpt-web-server-7bd2f76 | [
{
"filename": "src/main/java/com/home/chat/dao/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": 26.106379522258806
},
{
"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": 20.419234937672428
},
{
"filename": "src/main/java/com/home/chat/pojo/query/QueryPage.java",
"retrieved_chunk": "\t/**\n\t * 查询第几页\n\t */\n\tprotected int pageNo = 1;\n\t/**\n\t * 排序字段,如: row_id desc, create_date asc\n\t */\n\tprivate String order;\n\t/**\n\t * 分页查询返回的结果List",
"score": 14.900046270501464
},
{
"filename": "src/main/java/com/home/chat/dao/TbApikeyDAO.java",
"retrieved_chunk": " /**\n * 通过查询条件查询所有记录,不分页\n * @param query 查询条件对象\n * @return 表记录实体类对象集合list\n */\n List<TbApikeyEntity> queryForList(TbApikeyQuery query);\n /**\n * 批量删除,通过主键list删除一批表记录\n * @param idList 主键ID列表list \n * @return 影响行数",
"score": 12.321184981841954
},
{
"filename": "src/main/java/com/home/chat/redis/RedisDataHelper.java",
"retrieved_chunk": "\t * @version 1.0\n\t * @since JDK 1.8\n\t **/\n\tpublic void setKey(String key, Map<String, Object> map) {\n\t\tthis.redisTemplate.opsForHash().putAll(key, map);\n\t}\n\t/**\n\t *\n\t * @param key\n\t * @return [key]",
"score": 11.915185553023056
}
] | 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/method/MethodActionRegister.java",
"retrieved_chunk": " }\n if (actionInfo.isHasParameterType()) {\n actionInfo.setParameterType((int[]) args[actionInfo.getParameterTypeIndex()]);\n }\n }\n return actionInfo;\n } else {\n return new MethodActionInfo();\n }\n }",
"score": 48.93647719693158
},
{
"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": 48.35371992650245
},
{
"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": 45.52729360966964
},
{
"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": 41.99524192331761
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/AbstractDialect.java",
"retrieved_chunk": "public abstract class AbstractDialect implements Dialect {\n @Override\n public String getCountSql(String sql) {\n return \"SELECT COUNT(*) AS PG_COUNT FROM ( \" + sql + \" ) PG_TB \";\n }\n}",
"score": 38.14284193621878
}
] | 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-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": 88.18396797508056
},
{
"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": 87.67361239008973
},
{
"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": 75.6238197239539
},
{
"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": 58.568947187022815
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/spring/boot/autoconfigure/JdbcPlusAutoConfiguration.java",
"retrieved_chunk": " private JdbcPlusProperties jdbcPlusProperties;\n @Bean\n public Advisor jdbcTemplateMethodAdvisor(List<IInterceptor> interceptors) {\n JdbcTemplateMethodInterceptor interceptor = new JdbcTemplateMethodInterceptor(interceptors);\n return new JdbcTemplateMethodAdvisor(interceptor);\n }\n}",
"score": 57.96952850060853
}
] | 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-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java",
"retrieved_chunk": " }\n if (actionInfo.isHasParameterType()) {\n actionInfo.setParameterType((int[]) args[actionInfo.getParameterTypeIndex()]);\n }\n }\n return actionInfo;\n } else {\n return new MethodActionInfo();\n }\n }",
"score": 39.66959700116337
},
{
"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": 32.45392802077551
},
{
"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": 31.42433354792518
},
{
"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": 30.28368134425501
},
{
"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": 26.64205107140299
}
] | 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/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": 48.35371992650245
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java",
"retrieved_chunk": " }\n if (actionInfo.isHasParameterType()) {\n actionInfo.setParameterType((int[]) args[actionInfo.getParameterTypeIndex()]);\n }\n }\n return actionInfo;\n } else {\n return new MethodActionInfo();\n }\n }",
"score": 45.83584298336183
},
{
"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": 44.2790289743044
},
{
"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": 40.713791987829666
},
{
"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": 37.324775643360034
}
] | 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": 40.73004682729299
},
{
"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": 29.990552673080963
},
{
"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": 29.63799138397707
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java",
"retrieved_chunk": " String sql = actionInfo.getSql();\n //查询汇总\n if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) {\n if (actionInfo.isHasParameter()) {\n if (actionInfo.isParameterIsPss()) {\n Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() {\n @Override\n public Map extractData(ResultSet rs) throws SQLException, DataAccessException {\n while (rs.next()) {\n Map<String, Object> map = new HashMap<>();",
"score": 28.35889940999552
},
{
"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": 23.180726439553716
}
] | java | .debug("finish sql==>{ |
/*
* 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/K8sTestLocation.java",
"retrieved_chunk": "import java.net.URI;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\npublic class K8sTestLocation implements Location {\n\tprivate final String location;\n\tprivate final String fileContent;\n\tpublic K8sTestLocation(Path location) throws IOException {\n\t\tthis.location = location.toString();\n\t\tfileContent = Files.readString(location);\n\t}",
"score": 34.102825535199976
},
{
"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": 28.35609474747877
},
{
"filename": "src/main/java/dev/cru/context/k8s/K8sRecommendation.java",
"retrieved_chunk": " *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage dev.cru.context.k8s;\npublic record K8sRecommendation(String container, String cluster, String value, K8sResourceType resourceType) {}",
"score": 25.930868034720824
},
{
"filename": "src/main/java/dev/cru/conf/RepoConfig.java",
"retrieved_chunk": "public record RepoConfig(K8s k8s, Aws aws) {\n\tpublic record K8s(List<K8sLocation> location) {}\n\tpublic record Aws(String account, List<AwsLocation> location) {}\n\tpublic record K8sLocation(\n\t\tString path,\n\t\tString cluster,\n\t\tString namespace,\n\t\tString cpuDifference,\n\t\tString memDifference\n\t) {}",
"score": 23.52260665010605
},
{
"filename": "src/main/java/dev/cru/context/k8s/K8sResourceUpdater.java",
"retrieved_chunk": "public class K8sResourceUpdater {\n\tprivate final K8sNeedleExtractor needleExtractor = new K8sNeedleExtractor();\n\tprivate final Environment environment = new Environment();\n}",
"score": 21.896001666183388
}
] | java | cpuPattern.matcher(location.fileContent()); |
/*
* 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/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": 51.61581782789476
},
{
"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": 51.26204279349776
},
{
"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": 49.97060887779741
},
{
"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": 45.68733264285694
},
{
"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": 40.65003485149239
}
] | 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": 131.76903536401332
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java",
"retrieved_chunk": " }\n if (actionInfo.isHasParameterType()) {\n actionInfo.setParameterType((int[]) args[actionInfo.getParameterTypeIndex()]);\n }\n }\n return actionInfo;\n } else {\n return new MethodActionInfo();\n }\n }",
"score": 80.99942410908527
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java",
"retrieved_chunk": " String sql = actionInfo.getSql();\n //查询汇总\n if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) {\n if (actionInfo.isHasParameter()) {\n if (actionInfo.isParameterIsPss()) {\n Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() {\n @Override\n public Map extractData(ResultSet rs) throws SQLException, DataAccessException {\n while (rs.next()) {\n Map<String, Object> map = new HashMap<>();",
"score": 78.97483738781251
},
{
"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": 74.02458069540029
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java",
"retrieved_chunk": " map.put(\"PG_COUNT\", rs.getLong(\"PG_COUNT\"));\n return map;\n }\n return new HashMap<>();\n }\n }).get(\"PG_COUNT\");\n localPage.setTotal(Long.parseLong(cnt.toString()));\n } else {\n if (actionInfo.isHasParameterType()) {\n Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get(\"PG_COUNT\");",
"score": 65.63095366635629
}
] | java | ] = this.actionInfo.getParameter(); |
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": 44.2487451281752
},
{
"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": 44.06009573620228
},
{
"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": 38.59159002306532
},
{
"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": 36.6069517725784
},
{
"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": 29.53773449883717
}
] | java | MethodActionInfo actionInfo = methodInfo.getActionInfo(); |
/*
* Copyright © 2018 organization baomidou
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.deeround.jdbc.plus.aop;
import com.github.deeround.jdbc.plus.Interceptor.IInterceptor;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class JdbcTemplateMethodInterceptor implements MethodInterceptor {
private final List<IInterceptor> interceptors;
public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) {
this.interceptors = interceptors;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;
Object[] args = methodInvocation.getArguments();
Method method = methodInvocation.getMethod();
JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();
final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);
log | .debug("method==>name:{ | },actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType());
log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
//逻辑处理(核心方法:主要处理SQL和SQL参数)
if (this.interceptors != null && this.interceptors.size() > 0) {
for (IInterceptor interceptor : this.interceptors) {
if (interceptor.supportMethod(methodInfo)) {
interceptor.beforePrepare(methodInfo, jdbcTemplate);
//插件允许修改原始SQL以及入参
if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {
//回写参数
methodInvocation.setArguments(methodInfo.getArgs());
}
}
}
}
log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
Object result = methodInvocation.proceed();
log.debug("origin result==>{}", result);
//逻辑处理
if (this.interceptors != null && this.interceptors.size() > 0) {
for (int i = this.interceptors.size() - 1; i >= 0; i--) {
IInterceptor interceptor = this.interceptors.get(i);
if (interceptor.supportMethod(methodInfo)) {
result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);
}
}
}
log.debug("finish result==>{}", result);
return result;
}
private String toStr(Object[] objs) {
if (objs == null) {
return null;
}
return Arrays.toString(objs);
}
private String toStr(List<Object[]> list) {
if (list == null) {
return null;
}
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < list.size(); i++) {
str.append(Arrays.toString(list.get(i)));
if (i < list.size() - 1) {
str.append(",");
}
}
return str.append("]").toString();
}
}
| jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java | deeround-jdbc-plus-a0dcdfd | [
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": "public class MethodInvocationInfo extends MethodInfo {\n private boolean isSupport;\n private final Object[] args;\n private MethodType type;\n private MethodActionInfo actionInfo;\n private final Map<String, Object> userAttributes = new HashMap<>(0);\n public MethodInvocationInfo(final Object[] args, Method method) {\n super(method);\n this.args = args;\n this.type = MethodType.UNKNOWN;",
"score": 38.47369464159399
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java",
"retrieved_chunk": " public static void register(Class<JdbcTemplate> clazz, MethodActionInfo actionInfo, String name, Class<?>... parameterTypes) {\n try {\n Method method = clazz.getMethod(name, parameterTypes);\n Method_MAP.put(method, actionInfo);\n } catch (NoSuchMethodException e) {\n log.error(\"未找到方法:name={},parameterTypes={}\", name, parameterTypes, e);\n }\n }\n}",
"score": 36.739012943977194
},
{
"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": 34.20532487528282
},
{
"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": 32.45878403819062
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java",
"retrieved_chunk": " @Override\n public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL结束时间:{}\", LocalDateTime.now());\n LocalDateTime startTime = (LocalDateTime) methodInfo.getUserAttribute(\"startTime\");\n log.info(\"执行SQL耗时:{}毫秒\", Duration.between(startTime, LocalDateTime.now()).toMillis());\n return result;\n }\n}",
"score": 30.47874263557034
}
] | java | .debug("method==>name:{ |
package com.github.deeround.jdbc.plus.Interceptor;
import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect;
import com.github.deeround.jdbc.plus.Interceptor.pagination.Page;
import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper;
import com.github.deeround.jdbc.plus.method.MethodActionInfo;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import com.github.deeround.jdbc.plus.method.MethodType;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author wanghao [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": " }\n if (actionInfo.isHasParameterType()) {\n actionInfo.setParameterType((int[]) args[actionInfo.getParameterTypeIndex()]);\n }\n }\n return actionInfo;\n } else {\n return new MethodActionInfo();\n }\n }",
"score": 39.66959700116337
},
{
"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": 32.45392802077551
},
{
"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": 31.42433354792518
},
{
"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": 30.28368134425501
},
{
"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": 26.64205107140299
}
] | java | queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); |
/*
* 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": 67.14956632453436
},
{
"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": 34.189700272893255
},
{
"filename": "src/test/java/dev/cru/context/PrintDemoConfigTest.java",
"retrieved_chunk": "import com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.dataformat.yaml.YAMLFactory;\nimport dev.cru.conf.RepoConfig;\nimport java.util.List;\nimport org.junit.jupiter.api.Test;\npublic class PrintDemoConfigTest {\n\t@Test\n\tvoid name() throws JsonProcessingException {\n\t\tRepoConfig config = new RepoConfig(\n\t\t\tnew RepoConfig.K8s(",
"score": 28.477368941559067
},
{
"filename": "src/main/java/dev/cru/context/k8s/K8sNeedleExtractor.java",
"retrieved_chunk": "import java.util.HashSet;\nimport java.util.Set;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class K8sNeedleExtractor {\n\tprivate final Pattern cpuPattern = Pattern.compile(\n\t\t\"cru: container=(?<container>.*) cluster=(?<cluster>.*)\\\\n\\\\s*cpu: (?<cpu>\\\\S*)\"\n\t);\n\tprivate final Pattern memoryPattern = Pattern.compile(\n\t\t\"cru: container=(?<container>.*) cluster=(?<cluster>.*)\\\\n\\\\s*memory: (?<memory>\\\\S*)\"",
"score": 27.053864962257027
},
{
"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": 24.260888005710928
}
] | 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": 42.82781568293869
},
{
"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": 42.626802876720376
},
{
"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": 40.0412494395699
},
{
"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": 39.02844348053142
},
{
"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": 31.557416741634754
}
] | 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": 36.885066291656656
},
{
"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": 36.58029241038167
},
{
"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": 32.340094867181215
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageHelper.java",
"retrieved_chunk": " try {\n Class dialectClass = null;\n Dialect dialect = null;\n try {\n dialectClass = DIALECT_MAP.get(dialectName);\n if (Dialect.class.isAssignableFrom(dialectClass)) {\n dialect = (Dialect) dialectClass.newInstance();\n DIALECT_INSTANCE_MAP.put(dialectName, dialect);\n return dialect;\n } else {",
"score": 27.840009817101485
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " return this.isSupport;\n }\n public MethodActionInfo getActionInfo() {\n return this.actionInfo;\n }\n public Map<String, Object> getUserAttributes() {\n return this.userAttributes;\n }\n public void putUserAttribute(String key, Object value) {\n if (this.userAttributes != null) {",
"score": 27.351308059168787
}
] | java | () && methodInfo.getActionInfo().isReturnIsList()) { |
package com.github.deeround.jdbc.plus.Interceptor;
import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect;
import com.github.deeround.jdbc.plus.Interceptor.pagination.Page;
import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper;
import com.github.deeround.jdbc.plus.method.MethodActionInfo;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import com.github.deeround.jdbc.plus.method.MethodType;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author wanghao [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": 65.95151143201845
},
{
"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": 54.71604607360335
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java",
"retrieved_chunk": " }\n if (actionInfo.isHasParameterType()) {\n actionInfo.setParameterType((int[]) args[actionInfo.getParameterTypeIndex()]);\n }\n }\n return actionInfo;\n } else {\n return new MethodActionInfo();\n }\n }",
"score": 48.40936655128414
},
{
"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": 48.409131825372924
},
{
"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": 46.72955649894829
}
] | java | sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { |
/*
* Copyright © 2018 organization baomidou
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.deeround.jdbc.plus.aop;
import com.github.deeround.jdbc.plus.Interceptor.IInterceptor;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class JdbcTemplateMethodInterceptor implements MethodInterceptor {
private final List<IInterceptor> interceptors;
public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) {
this.interceptors = interceptors;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;
Object[] args = methodInvocation.getArguments();
Method method = methodInvocation.getMethod();
JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();
final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);
log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType());
log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("origin parameters==>{}", this.toStr | (methodInfo.getActionInfo().getBatchParameter())); |
//逻辑处理(核心方法:主要处理SQL和SQL参数)
if (this.interceptors != null && this.interceptors.size() > 0) {
for (IInterceptor interceptor : this.interceptors) {
if (interceptor.supportMethod(methodInfo)) {
interceptor.beforePrepare(methodInfo, jdbcTemplate);
//插件允许修改原始SQL以及入参
if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {
//回写参数
methodInvocation.setArguments(methodInfo.getArgs());
}
}
}
}
log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
Object result = methodInvocation.proceed();
log.debug("origin result==>{}", result);
//逻辑处理
if (this.interceptors != null && this.interceptors.size() > 0) {
for (int i = this.interceptors.size() - 1; i >= 0; i--) {
IInterceptor interceptor = this.interceptors.get(i);
if (interceptor.supportMethod(methodInfo)) {
result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);
}
}
}
log.debug("finish result==>{}", result);
return result;
}
private String toStr(Object[] objs) {
if (objs == null) {
return null;
}
return Arrays.toString(objs);
}
private String toStr(List<Object[]> list) {
if (list == null) {
return null;
}
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < list.size(); i++) {
str.append(Arrays.toString(list.get(i)));
if (i < list.size() - 1) {
str.append(",");
}
}
return str.append("]").toString();
}
}
| jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java | deeround-jdbc-plus-a0dcdfd | [
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java",
"retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));",
"score": 81.66832328292134
},
{
"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": 76.43101906680312
},
{
"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": 76.01622065776772
},
{
"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": 61.503578783470545
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java",
"retrieved_chunk": " public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n Page<Object> localPage = PageHelper.getLocalPage();\n if (localPage == null) {\n return result;\n }\n try {\n if (methodInfo.getActionInfo().isReturnIsList()) {\n if (result != null) {\n localPage.addAll((Collection<?>) result);\n }",
"score": 58.99907417204343
}
] | 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": 47.82570546440891
},
{
"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": 40.57255884336723
},
{
"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": 33.80992536571193
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " if (this.interceptors != null && this.interceptors.size() > 0) {\n for (int i = this.interceptors.size() - 1; i >= 0; i--) {\n IInterceptor interceptor = this.interceptors.get(i);\n if (interceptor.supportMethod(methodInfo)) {\n result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);\n }\n }\n }\n log.debug(\"finish result==>{}\", result);\n return result;",
"score": 33.06883675603713
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java",
"retrieved_chunk": " public long getStartRow() {\n return this.startRow;\n }\n public Page<E> setStartRow(long startRow) {\n this.startRow = startRow;\n return this;\n }\n public long getTotal() {\n return this.total;\n }",
"score": 31.952881102245648
}
] | java | page.getStartRow() + 1; |
/*
* Copyright © 2018 organization baomidou
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.deeround.jdbc.plus.aop;
import com.github.deeround.jdbc.plus.Interceptor.IInterceptor;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class JdbcTemplateMethodInterceptor implements MethodInterceptor {
private final List<IInterceptor> interceptors;
public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) {
this.interceptors = interceptors;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;
Object[] args = methodInvocation.getArguments();
Method method = methodInvocation.getMethod();
JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();
final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);
log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType());
log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
//逻辑处理(核心方法:主要处理SQL和SQL参数)
if (this.interceptors != null && this.interceptors.size() > 0) {
for (IInterceptor interceptor : this.interceptors) {
if (interceptor.supportMethod(methodInfo)) {
interceptor.beforePrepare(methodInfo, jdbcTemplate);
//插件允许修改原始SQL以及入参
| if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { |
//回写参数
methodInvocation.setArguments(methodInfo.getArgs());
}
}
}
}
log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
Object result = methodInvocation.proceed();
log.debug("origin result==>{}", result);
//逻辑处理
if (this.interceptors != null && this.interceptors.size() > 0) {
for (int i = this.interceptors.size() - 1; i >= 0; i--) {
IInterceptor interceptor = this.interceptors.get(i);
if (interceptor.supportMethod(methodInfo)) {
result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);
}
}
}
log.debug("finish result==>{}", result);
return result;
}
private String toStr(Object[] objs) {
if (objs == null) {
return null;
}
return Arrays.toString(objs);
}
private String toStr(List<Object[]> list) {
if (list == null) {
return null;
}
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < list.size(); i++) {
str.append(Arrays.toString(list.get(i)));
if (i < list.size() - 1) {
str.append(",");
}
}
return str.append("]").toString();
}
}
| jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java | deeround-jdbc-plus-a0dcdfd | [
{
"filename": "jdbc-plus-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": 108.81163420721728
},
{
"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": 108.38173048697534
},
{
"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": 96.65282453138111
},
{
"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": 80.29185293540802
},
{
"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": 72.96986453128152
}
] | java | if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { |
/*
* Copyright © 2018 organization baomidou
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.deeround.jdbc.plus.aop;
import com.github.deeround.jdbc.plus.Interceptor.IInterceptor;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.framework.ReflectiveMethodInvocation;
import org.springframework.jdbc.core.JdbcTemplate;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class JdbcTemplateMethodInterceptor implements MethodInterceptor {
private final List<IInterceptor> interceptors;
public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) {
this.interceptors = interceptors;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;
Object[] args = methodInvocation.getArguments();
Method method = methodInvocation.getMethod();
JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();
final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);
log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType());
log.debug("origin sql==>{}", this. | toStr(methodInfo.getActionInfo().getBatchSql())); |
log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
//逻辑处理(核心方法:主要处理SQL和SQL参数)
if (this.interceptors != null && this.interceptors.size() > 0) {
for (IInterceptor interceptor : this.interceptors) {
if (interceptor.supportMethod(methodInfo)) {
interceptor.beforePrepare(methodInfo, jdbcTemplate);
//插件允许修改原始SQL以及入参
if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {
//回写参数
methodInvocation.setArguments(methodInfo.getArgs());
}
}
}
}
log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter()));
Object result = methodInvocation.proceed();
log.debug("origin result==>{}", result);
//逻辑处理
if (this.interceptors != null && this.interceptors.size() > 0) {
for (int i = this.interceptors.size() - 1; i >= 0; i--) {
IInterceptor interceptor = this.interceptors.get(i);
if (interceptor.supportMethod(methodInfo)) {
result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);
}
}
}
log.debug("finish result==>{}", result);
return result;
}
private String toStr(Object[] objs) {
if (objs == null) {
return null;
}
return Arrays.toString(objs);
}
private String toStr(List<Object[]> list) {
if (list == null) {
return null;
}
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < list.size(); i++) {
str.append(Arrays.toString(list.get(i)));
if (i < list.size() - 1) {
str.append(",");
}
}
return str.append("]").toString();
}
}
| jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java | deeround-jdbc-plus-a0dcdfd | [
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java",
"retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));",
"score": 68.38476248177342
},
{
"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": 63.49852415483013
},
{
"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": 63.13308994002742
},
{
"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": 53.257147237553454
},
{
"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": 51.521309964781246
}
] | java | toStr(methodInfo.getActionInfo().getBatchSql())); |
package com.github.deeround.jdbc.plus.Interceptor;
import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect;
import com.github.deeround.jdbc.plus.Interceptor.pagination.Page;
import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper;
import com.github.deeround.jdbc.plus.method.MethodActionInfo;
import com.github.deeround.jdbc.plus.method.MethodInvocationInfo;
import com.github.deeround.jdbc.plus.method.MethodType;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.ResultSetExtractor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* @author wanghao [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/pagination/PageHelper.java",
"retrieved_chunk": " try {\n Class dialectClass = null;\n Dialect dialect = null;\n try {\n dialectClass = DIALECT_MAP.get(dialectName);\n if (Dialect.class.isAssignableFrom(dialectClass)) {\n dialect = (Dialect) dialectClass.newInstance();\n DIALECT_INSTANCE_MAP.put(dialectName, dialect);\n return dialect;\n } else {",
"score": 20.321367596144626
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/AbstractDialect.java",
"retrieved_chunk": "public abstract class AbstractDialect implements Dialect {\n @Override\n public String getCountSql(String sql) {\n return \"SELECT COUNT(*) AS PG_COUNT FROM ( \" + sql + \" ) PG_TB \";\n }\n}",
"score": 18.941951538352644
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionType.java",
"retrieved_chunk": " * Map<String, Object> queryForMap(String sql)\n */\n QUERYFORMAP_SQL,\n /**\n * Map<String, Object> queryForMap(String sql, @Nullable Object... args)\n */\n QUERYFORMAP_SQL_ARGS,\n /**\n * Map<String, Object> queryForMap(String sql, Object[] args, int[] argTypes)\n */",
"score": 16.253125875453925
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageHelper.java",
"retrieved_chunk": " }\n }\n private static String getDialectName(String url) {\n url = url.toLowerCase();\n for (String dialect : DIALECT_MAP.keySet()) {\n if (url.contains(\":\" + dialect + \":\")) {\n return dialect;\n }\n }\n return null;",
"score": 13.942333436487312
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/SqlServerDialect.java",
"retrieved_chunk": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.github.deeround.jdbc.plus.Interceptor.pagination.dialect;\n/**\n * @author liuzh\n */\npublic class SqlServerDialect extends AbstractDialect {\n @Override\n public String getPageSql(String sql, int pageNum, int pageSize) {",
"score": 13.853263970647234
}
] | java | methodInfo.resolveSql(sql); |
/*
* 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": 96.74724306664974
},
{
"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": 93.01955144841261
},
{
"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": 62.101005668699685
},
{
"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": 61.873627738809404
},
{
"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": 58.92278568939722
}
] | java | String.format("%s-- key: %s\n", prefix, keyType.getTypeName())); |
/*
* 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/handler/TenantLineHandler.java",
"retrieved_chunk": " */\n default boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {\n return columns.stream().map(Column::getColumnName).anyMatch(i -> i.equalsIgnoreCase(tenantIdColumn));\n }\n}",
"score": 37.47965589515289
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " this.processSelectBody(((SubSelect) expression).getSelectBody(), whereSegment);\n } else if (expression instanceof Function) {\n this.processFunction((Function) expression, whereSegment);\n }\n }\n }\n /**\n * 处理函数\n * <p>支持: 1. select fun(args..) 2. select fun1(fun2(args..),args..)<p>\n * <p> fixed gitee pulls/141</p>",
"score": 24.184110639729628
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/handler/TenantLineHandler.java",
"retrieved_chunk": " */\n default boolean ignoreTable(String tableName) {\n return false;\n }\n /**\n * 忽略插入租户字段逻辑\n *\n * @param columns 插入字段\n * @param tenantIdColumn 租户 ID 字段\n * @return",
"score": 21.875859653454267
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/JdbcPlusConfig.java",
"retrieved_chunk": " public Expression getTenantId() {\n String currentTenantId = \"test_tenant_4\";//可以从请求上下文中获取(cookie、session、header等)\n return new StringValue(currentTenantId);\n }\n /**\n * 租户字段名\n */\n @Override\n public String getTenantIdColumn() {\n return \"tenant_id\";",
"score": 21.503983690226676
},
{
"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": 17.849120221277676
}
] | java | equalsTo.setRightExpression(this.tenantLineHandler.getTenantId()); |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file contains code from the Apache Spark project (original license above).
* It contains modifications, which are licensed as follows:
*/
/*
* Copyright (2020-present) The Delta Lake Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.delta.store.internal.types;
import java.util.Objects;
/*
* The data type for 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": 106.71622130124004
},
{
"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": 85.45052311239895
},
{
"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": 79.51181103308717
},
{
"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": 73.90968161898024
},
{
"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": 70.47675742826476
}
] | java | DataType.buildFormattedString(elementType, nextPrefix, builder); |
/*
* 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": 78.73009251271412
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " public abstract Expression buildTableExpression(final Table table, final Expression where, final String whereSegment);\n}",
"score": 77.98069382451573
},
{
"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": 48.66771837442279
},
{
"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": 30.831726997654904
},
{
"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": 30.732331164705315
}
] | java | new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId()); |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file contains code from the Apache Spark project (original license above).
* It contains modifications, which are licensed as follows:
*/
/*
* Copyright (2020-present) The Delta Lake Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.delta.store.internal.types;
import java.util.Objects;
/*
* A field inside a {@link StructType}.
*/
public final class StructField {
private final String name;
private final DataType dataType;
private final boolean nullable;
private final FieldMetadata metadata;
/*
* Constructor with default {@code nullable = true}.
*
* @param name the name of this field
*
* @param dataType the data type of this field
*/
public StructField(String name, DataType dataType) {
this(name, dataType, true);
}
/*
* @param name the name of this field
*
* @param dataType the data type of this field
*
* @param nullable indicates if values of this field can be {@code null} values
*/
public StructField(String name, DataType dataType, boolean nullable) {
this(name, dataType, nullable, FieldMetadata.builder().build());
}
/*
* @param name the name of this field
*
* @param dataType the data type of this field
*
* @param nullable indicates if values of this field can be {@code null} values
*
* @param metadata metadata for this field
*/
public StructField(String name, DataType dataType, boolean nullable, FieldMetadata metadata) {
this.name = name;
this.dataType = dataType;
this.nullable = nullable;
this.metadata = metadata;
}
/*
* @return the name of this field
*/
public String getName() {
return name;
}
/*
* @return the data type of this field
*/
public DataType getDataType() {
return dataType;
}
/*
* @return whether this field allows to have a {@code null} value.
*/
public boolean isNullable() {
return nullable;
}
/*
* @return the metadata for this field
*/
public FieldMetadata getMetadata() {
return metadata;
}
/*
* Builds a readable {@code String} representation of this {@code StructField}.
*/
protected void buildFormattedString(String prefix, StringBuilder builder) {
final String nextPrefix = prefix + " |";
builder.append(String.format("%s-- %s: %s (nullable = %b) (metadata =%s)\n", prefix, name,
dataType.getTypeName(), nullable, metadata.toString()));
| DataType.buildFormattedString(dataType, nextPrefix, builder); |
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
StructField that = (StructField) o;
return name.equals(that.name) && dataType.equals(that.dataType) && nullable == that.nullable
&& metadata.equals(that.metadata);
}
@Override
public int hashCode() {
return Objects.hash(name, dataType, nullable, metadata);
}
}
| server/src/main/java/io/delta/store/internal/types/StructField.java | dataplatform-lab-deltastore-017c850 | [
{
"filename": "server/src/main/java/io/delta/store/internal/types/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": 119.22883793919605
},
{
"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": 98.4362426976057
},
{
"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": 82.68862980039223
},
{
"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": 74.85735347464886
},
{
"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": 73.61448670457719
}
] | java | DataType.buildFormattedString(dataType, nextPrefix, builder); |
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": 46.24854035589221
},
{
"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": 45.42147633817528
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java",
"retrieved_chunk": " @Override\n public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL结束时间:{}\", LocalDateTime.now());\n LocalDateTime startTime = (LocalDateTime) methodInfo.getUserAttribute(\"startTime\");\n log.info(\"执行SQL耗时:{}毫秒\", Duration.between(startTime, LocalDateTime.now()).toMillis());\n return result;\n }\n}",
"score": 44.372516504611966
},
{
"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": 38.253180663666136
},
{
"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": 37.99929490506271
}
] | java | (methodInfo.getActionInfo().isReturnIsList()) { |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file contains code from the Apache Spark project (original license above).
* It contains modifications, which are licensed as follows:
*/
/*
* Copyright (2020-present) The Delta Lake Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.delta.store.internal.types;
import java.util.Objects;
/*
* 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": 146.3744101179537
},
{
"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": 143.59718836417463
},
{
"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": 84.80519715558853
},
{
"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": 81.7332468624212
},
{
"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": 81.29534638278163
}
] | java | prefix, valueType.getTypeName(),
valueContainsNull)); |
/*
* 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 * 处理 PlainSelect\n */\n protected void processPlainSelect(final PlainSelect plainSelect, final String whereSegment) {\n //#3087 github\n List<SelectItem> selectItems = plainSelect.getSelectItems();\n if (CollectionUtils.isNotEmpty(selectItems)) {\n selectItems.forEach(selectItem -> this.processSelectItem(selectItem, whereSegment));\n }",
"score": 39.13141206538229
},
{
"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": 29.85034978829844
},
{
"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": 28.121977034402533
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageInfo.java",
"retrieved_chunk": " this.startRow = 0;\n this.endRow = list.size() > 0 ? list.size() - 1 : 0;\n }\n if (list instanceof Collection) {\n this.calcByNavigatePages(navigatePages);\n }\n }\n public static <T> PageInfo<T> of(List<T> list) {\n return new PageInfo<T>(list);\n }",
"score": 23.482513529934078
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " injectExpression = new AndExpression(injectExpression, expressions.get(i));\n }\n }\n if (currentExpression == null) {\n return injectExpression;\n }\n if (currentExpression instanceof OrExpression) {\n return new AndExpression(new Parenthesis(currentExpression), injectExpression);\n } else {\n return new AndExpression(currentExpression, injectExpression);",
"score": 21.56230003733492
}
] | 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 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": 95.8373718346014
},
{
"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": 73.16759717447361
},
{
"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": 69.40228523969893
},
{
"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": 63.930700643208894
},
{
"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": 61.39655681785287
}
] | java | .format("%s-- element: %s (containsNull = %b)\n", prefix, elementType.getTypeName(),
containsNull)); |
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/model/Hero.java",
"retrieved_chunk": " public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {",
"score": 19.585756489609004
},
{
"filename": "src/main/java/me/dio/model/Hero.java",
"retrieved_chunk": " this.name = name;\n }\n public int getXp() {\n return xp;\n }\n public void setXp(int xp) {\n this.xp = xp;\n }\n public int getVersion() {\n return version;",
"score": 16.137724968351492
},
{
"filename": "src/main/java/me/dio/service/CrudService.java",
"retrieved_chunk": "package me.dio.service;\nimport java.util.List;\npublic interface CrudService<ID, T> {\n List<T> findAll();\n T findById(ID id);\n T create(T entity);\n T update(ID id, T entity);\n void delete(ID id);\n}",
"score": 12.738084313229365
},
{
"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": 10.566665397283751
},
{
"filename": "src/main/java/me/dio/model/Hero.java",
"retrieved_chunk": " }\n public void setVersion(int version) {\n this.version = version;\n }\n}",
"score": 10.13094577041461
}
] | java | (!dbHero.getId().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;
/*
* 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": 108.27092384729045
},
{
"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": 86.05192987802016
},
{
"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": 66.87356578236658
},
{
"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": 65.67775655052333
},
{
"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": 63.68630275795597
}
] | 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/model/Hero.java",
"retrieved_chunk": " this.name = name;\n }\n public int getXp() {\n return xp;\n }\n public void setXp(int xp) {\n this.xp = xp;\n }\n public int getVersion() {\n return version;",
"score": 23.83765265474436
},
{
"filename": "src/main/java/me/dio/model/Hero.java",
"retrieved_chunk": " public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {",
"score": 20.48272064084893
},
{
"filename": "src/main/java/me/dio/model/Hero.java",
"retrieved_chunk": " }\n public void setVersion(int version) {\n this.version = version;\n }\n}",
"score": 15.545916676661346
},
{
"filename": "src/main/java/me/dio/service/CrudService.java",
"retrieved_chunk": "package me.dio.service;\nimport java.util.List;\npublic interface CrudService<ID, T> {\n List<T> findAll();\n T findById(ID id);\n T create(T entity);\n T update(ID id, T entity);\n void delete(ID id);\n}",
"score": 15.32103920143514
},
{
"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": 11.252720194160336
}
] | java | dbHero.getXp() + 2); |
/*
* 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": 107.69631559421812
},
{
"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": 103.86993280562568
},
{
"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": 71.99585952334154
},
{
"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": 71.15682821325376
},
{
"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": 66.57286989912485
}
] | java | DataType.buildFormattedString(keyType, nextPrefix, builder); |
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/model/Hero.java",
"retrieved_chunk": " public Long getId() {\n return id;\n }\n public void setId(Long id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {",
"score": 19.585756489609004
},
{
"filename": "src/main/java/me/dio/model/Hero.java",
"retrieved_chunk": " this.name = name;\n }\n public int getXp() {\n return xp;\n }\n public void setXp(int xp) {\n this.xp = xp;\n }\n public int getVersion() {\n return version;",
"score": 16.137724968351492
},
{
"filename": "src/main/java/me/dio/service/CrudService.java",
"retrieved_chunk": "package me.dio.service;\nimport java.util.List;\npublic interface CrudService<ID, T> {\n List<T> findAll();\n T findById(ID id);\n T create(T entity);\n T update(ID id, T entity);\n void delete(ID id);\n}",
"score": 12.738084313229365
},
{
"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": 10.566665397283751
},
{
"filename": "src/main/java/me/dio/model/Hero.java",
"retrieved_chunk": " }\n public void setVersion(int version) {\n this.version = version;\n }\n}",
"score": 10.13094577041461
}
] | java | ).equals(heroToUpdate.getId())) { |
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": " * Toast.maximumWidth int -1 (default) -1 as not set\n * <p>\n * Toast.shadowColor Color\n * Toast.shadowOpacity float 0.1f (default)\n * Toast.shadowInsets Insets 0,0,6,6 (default)\n * <p>\n * Toast.useEffect boolean true (default)\n * Toast.effectWidth float 0.5f (default) 0.5f as 50%\n * Toast.effectOpacity float 0.2f (default) 0 to 1\n * Toast.effectAlignment String left (default) left, right",
"score": 39.023460155504225
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " * Toast.error.foreground Color\n * Toast.error.background Color\n * <p>\n * Toast.frameInsets Insets 10,10,10,10 (default)\n * Toast.margin Insets 8,8,8,8 (default)\n * <p>\n * Toast.showCloseButton boolean true (default)\n * Toast.closeIconColor Color\n *\n * <p>",
"score": 30.38941597945115
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " }\n public DropShadowBorder(Color shadowColor, Insets shadowInsets, float shadowOpacity) {\n super(nonNegativeInsets(shadowInsets));\n this.shadowColor = shadowColor;\n this.shadowInsets = shadowInsets;\n this.shadowOpacity = shadowOpacity;\n this.shadowSize = maxInset(shadowInsets);\n }\n private static Insets nonNegativeInsets(Insets shadowInsets) {\n return new Insets(Math.max(shadowInsets.top, 0), Math.max(shadowInsets.left, 0), Math.max(shadowInsets.bottom, 0), Math.max(shadowInsets.right, 0));",
"score": 28.585544962815582
},
{
"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": 27.841848862704367
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": "/**\n * @author Raven\n */\npublic class DropShadowBorder extends EmptyBorder {\n @Styleable\n protected Color shadowColor;\n @Styleable\n protected Insets shadowInsets;\n @Styleable\n protected float shadowOpacity;",
"score": 27.36831929269332
}
] | 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": " * Toast.error.foreground Color\n * Toast.error.background Color\n * <p>\n * Toast.frameInsets Insets 10,10,10,10 (default)\n * Toast.margin Insets 8,8,8,8 (default)\n * <p>\n * Toast.showCloseButton boolean true (default)\n * Toast.closeIconColor Color\n *\n * <p>",
"score": 69.01248325983045
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " * Toast.maximumWidth int -1 (default) -1 as not set\n * <p>\n * Toast.shadowColor Color\n * Toast.shadowOpacity float 0.1f (default)\n * Toast.shadowInsets Insets 0,0,6,6 (default)\n * <p>\n * Toast.useEffect boolean true (default)\n * Toast.effectWidth float 0.5f (default) 0.5f as 50%\n * Toast.effectOpacity float 0.2f (default) 0 to 1\n * Toast.effectAlignment String left (default) left, right",
"score": 41.387388541277595
},
{
"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": 39.72672821182122
},
{
"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": 36.93309504289067
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": "package raven.toast;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.Animator;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.ui.ToastNotificationPanel;\nimport raven.toast.util.NotificationHolder;\nimport raven.toast.util.UIUtils;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ComponentAdapter;",
"score": 28.668129291354592
}
] | 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": 63.29585518785167
},
{
"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": 22.107427039955194
},
{
"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": 18.865803706903073
},
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }",
"score": 7.809932116164812
},
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": " if (n.getLocation() == location) {\n lists.remove(n);\n i--;\n }\n }\n }\n }\n}",
"score": 6.502858342157919
}
] | 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": " 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": 54.2735326566127
},
{
"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": 40.73634497569955
},
{
"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": 20.73077251040068
},
{
"filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java",
"retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport com.formdev.flatlaf.extras.FlatSVGIcon;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport javax.swing.*;\nimport java.awt.*;\npublic class ToastNotificationPanel extends JPanel {\n protected JWindow window;\n protected JLabel labelIcon;",
"score": 18.710694093445742
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " private Image shadowImage;\n private int shadowSize;\n private Color lastShadowColor;\n private float lastShadowOpacity;\n private int lastShadowSize;\n private int lastArc;\n private int lastWidth;\n private int lastHeight;\n public DropShadowBorder() {\n this(new Color(0, 0, 0), new Insets(0, 0, 6, 6), 0.1f);",
"score": 16.346712182391713
}
] | java | UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); |
package raven.toast;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.Animator;
import com.formdev.flatlaf.util.UIScale;
import raven.toast.ui.ToastNotificationPanel;
import raven.toast.util.NotificationHolder;
import raven.toast.util.UIUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
/**
* <!-- FlatLaf Property -->
* <p>
* Toast.outlineWidth int 0 (default)
* Toast.iconTextGap int 5 (default)
* Toast.closeButtonGap int 5 (default)
* Toast.arc int 20 (default)
* Toast.horizontalGap int 10 (default)
* <p>
* Toast.limit int -1 (default) -1 as unlimited
* Toast.duration long 2500 (default)
* Toast.animation int 200 (default)
* Toast.animationResolution int 5 (default)
* Toast.animationMove int 10 (default)
* Toast.minimumWidth int 50 (default)
* Toast.maximumWidth int -1 (default) -1 as not set
* <p>
* Toast.shadowColor Color
* Toast.shadowOpacity float 0.1f (default)
* Toast.shadowInsets Insets 0,0,6,6 (default)
* <p>
* Toast.useEffect boolean true (default)
* Toast.effectWidth float 0.5f (default) 0.5f as 50%
* Toast.effectOpacity float 0.2f (default) 0 to 1
* Toast.effectAlignment String left (default) left, right
* Toast.effectColor Color
* Toast.success.effectColor Color
* Toast.info.effectColor Color
* Toast.warning.effectColor Color
* Toast.error.effectColor Color
* <p>
* Toast.outlineColor Color
* Toast.foreground Color
* Toast.background Color
* <p>
* Toast.success.outlineColor Color
* Toast.success.foreground Color
* Toast.success.background Color
* Toast.info.outlineColor Color
* Toast.info.foreground Color
* Toast.info.background Color
* Toast.warning.outlineColor Color
* Toast.warning.foreground Color
* Toast.warning.background Color
* Toast.error.outlineColor Color
* Toast.error.foreground Color
* Toast.error.background Color
* <p>
* Toast.frameInsets Insets 10,10,10,10 (default)
* Toast.margin Insets 8,8,8,8 (default)
* <p>
* Toast.showCloseButton boolean true (default)
* Toast.closeIconColor Color
*
* <p>
* <!-- UIManager -->
* <p>
* Toast.success.icon Icon
* Toast.info.icon Icon
* Toast.warning.icon Icon
* Toast.error.icon Icon
* Toast.closeIcon Icon
*/
/**
* @author Raven
*/
public class Notifications {
private static Notifications instance;
private JFrame frame;
private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>();
private final NotificationHolder notificationHolder = new NotificationHolder();
private ComponentListener windowEvent;
private void installEvent(JFrame frame) {
if (windowEvent == null && frame != null) {
windowEvent = new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
move(frame.getBounds());
}
@Override
public void componentResized(ComponentEvent e) {
move(frame.getBounds());
}
};
}
if (this.frame != null) {
this.frame.removeComponentListener(windowEvent);
}
if (frame != null) {
frame.addComponentListener(windowEvent);
}
this.frame = frame;
}
public static Notifications getInstance() {
if (instance == null) {
instance = new Notifications();
}
return instance;
}
private int getCurrentShowCount(Location location) {
List list = lists.get(location);
return list == null ? 0 : list.size();
}
private synchronized void move(Rectangle rectangle) {
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) {
for (int i = 0; i < set.getValue().size(); i++) {
NotificationAnimation an = set.getValue().get(i);
if (an != null) {
an.move(rectangle);
}
}
}
}
public void setJFrame(JFrame frame) {
installEvent(frame);
}
public void show(Type type, String message) {
show(type, Location.TOP_CENTER, message);
}
public void show(Type type, long duration, String message) {
show(type, Location.TOP_CENTER, duration, message);
}
public void show(Type type, Location location, String message) {
long duration = FlatUIUtils.getUIInt("Toast.duration", 2500);
show(type, location, duration, message);
}
public void show(Type type, Location location, long duration, String message) {
initStart(new NotificationAnimation(type, location, duration, message), duration);
}
public void show(JComponent component) {
show(Location.TOP_CENTER, component);
}
public void show(Location location, JComponent component) {
long duration = FlatUIUtils.getUIInt("Toast.duration", 2500);
show(location, duration, component);
}
public void show(Location location, long duration, JComponent component) {
initStart(new NotificationAnimation(location, duration, component), duration);
}
private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) {
int limit = FlatUIUtils.getUIInt("Toast.limit", -1);
if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) {
notificationAnimation.start();
return true;
} else {
notificationHolder.hold(notificationAnimation);
return false;
}
}
private synchronized void notificationClose(NotificationAnimation notificationAnimation) {
NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation());
if (hold != null) {
if (initStart(hold, hold.getDuration())) {
| notificationHolder.removeHold(hold); |
}
}
}
public void clearAll() {
notificationHolder.clearHold();
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) {
for (int i = 0; i < set.getValue().size(); i++) {
NotificationAnimation an = set.getValue().get(i);
if (an != null) {
an.close();
}
}
}
}
public void clear(Location location) {
notificationHolder.clearHold(location);
List<NotificationAnimation> list = lists.get(location);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
NotificationAnimation an = list.get(i);
if (an != null) {
an.close();
}
}
}
}
public void clearHold() {
notificationHolder.clearHold();
}
public void clearHold(Location location) {
notificationHolder.clearHold(location);
}
protected ToastNotificationPanel createNotification(Type type, String message) {
ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel();
toastNotificationPanel.set(type, message);
return toastNotificationPanel;
}
private synchronized void updateList(Location key, NotificationAnimation values, boolean add) {
if (add) {
if (lists.containsKey(key)) {
lists.get(key).add(values);
} else {
List<NotificationAnimation> list = new ArrayList<>();
list.add(values);
lists.put(key, list);
}
} else {
if (lists.containsKey(key)) {
lists.get(key).remove(values);
if (lists.get(key).isEmpty()) {
lists.remove(key);
}
}
}
}
public enum Type {
SUCCESS, INFO, WARNING, ERROR
}
public enum Location {
TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT
}
public class NotificationAnimation {
private JWindow window;
private Animator animator;
private boolean show = true;
private float animate;
private int x;
private int y;
private Location location;
private long duration;
private Insets frameInsets;
private int horizontalSpace;
private int animationMove;
private boolean top;
private boolean close = false;
public NotificationAnimation(Type type, Location location, long duration, String message) {
installDefault();
this.location = location;
this.duration = duration;
window = new JWindow(frame);
ToastNotificationPanel toastNotificationPanel = createNotification(type, message);
toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close());
window.setContentPane(toastNotificationPanel);
window.setFocusableWindowState(false);
window.pack();
toastNotificationPanel.setDialog(window);
}
public NotificationAnimation(Location location, long duration, JComponent component) {
installDefault();
this.location = location;
this.duration = duration;
window = new JWindow(frame);
window.setBackground(new Color(0, 0, 0, 0));
window.setContentPane(component);
window.setFocusableWindowState(false);
window.setSize(component.getPreferredSize());
}
private void installDefault() {
frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10));
horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10);
animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10);
}
public void start() {
int animation = FlatUIUtils.getUIInt("Toast.animation", 200);
int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5);
animator = new Animator(animation, new Animator.TimingTarget() {
@Override
public void begin() {
if (show) {
updateList(location, NotificationAnimation.this, true);
installLocation();
}
}
@Override
public void timingEvent(float f) {
animate = show ? f : 1f - f;
updateLocation(true);
}
@Override
public void end() {
if (show && close == false) {
SwingUtilities.invokeLater(() -> {
new Thread(() -> {
sleep(duration);
if (close == false) {
show = false;
animator.start();
}
}).start();
});
} else {
updateList(location, NotificationAnimation.this, false);
window.dispose();
notificationClose(NotificationAnimation.this);
}
}
});
animator.setResolution(resolution);
animator.start();
}
private void installLocation() {
Insets insets;
Rectangle rec;
if (frame == null) {
insets = UIScale.scale(frameInsets);
rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize());
} else {
insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets()));
rec = frame.getBounds();
}
setupLocation(rec, insets);
window.setOpacity(0f);
window.setVisible(true);
}
private void move(Rectangle rec) {
Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets()));
setupLocation(rec, insets);
}
private void setupLocation(Rectangle rec, Insets insets) {
if (location == Location.TOP_LEFT) {
x = rec.x + insets.left;
y = rec.y + insets.top;
top = true;
} else if (location == Location.TOP_CENTER) {
x = rec.x + (rec.width - window.getWidth()) / 2;
y = rec.y + insets.top;
top = true;
} else if (location == Location.TOP_RIGHT) {
x = rec.x + rec.width - (window.getWidth() + insets.right);
y = rec.y + insets.top;
top = true;
} else if (location == Location.BOTTOM_LEFT) {
x = rec.x + insets.left;
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
} else if (location == Location.BOTTOM_CENTER) {
x = rec.x + (rec.width - window.getWidth()) / 2;
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
} else if (location == Location.BOTTOM_RIGHT) {
x = rec.x + rec.width - (window.getWidth() + insets.right);
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
}
int am = UIScale.scale(top ? animationMove : -animationMove);
int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am);
window.setLocation(x, ly);
}
private void updateLocation(boolean loop) {
int am = UIScale.scale(top ? animationMove : -animationMove);
int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am);
window.setLocation(x, ly);
window.setOpacity(animate);
if (loop) {
update(this);
}
}
private int getLocation(NotificationAnimation notification) {
int height = 0;
List<NotificationAnimation> list = lists.get(location);
for (int i = 0; i < list.size(); i++) {
NotificationAnimation n = list.get(i);
if (notification == n) {
return height;
}
double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace));
height += top ? v : -v;
}
return height;
}
private void update(NotificationAnimation except) {
List<NotificationAnimation> list = lists.get(location);
for (int i = 0; i < list.size(); i++) {
NotificationAnimation n = list.get(i);
if (n != except) {
n.updateLocation(false);
}
}
}
public void close() {
close = true;
show = false;
if (animator.isRunning()) {
animator.stop();
}
animator.start();
}
private void sleep(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
System.err.println(e);
}
}
public Location getLocation() {
return location;
}
public long getDuration() {
return duration;
}
}
}
| src/main/java/raven/toast/Notifications.java | DJ-Raven-swing-toast-notifications-4c7978a | [
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }",
"score": 74.519130969483
},
{
"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": 22.618041566354258
},
{
"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": 11.614713727274301
},
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }",
"score": 7.8312445378642135
},
{
"filename": "src/test/java/raven/demo/Test.java",
"retrieved_chunk": " @Override\n public void actionPerformed(ActionEvent e) {\n if (cmdMode.getText().equals(\"Mode Light\")) {\n changeMode(true);\n cmdMode.setText(\"Mode Dark\");\n } else {\n changeMode(false);\n cmdMode.setText(\"Mode Light\");\n }\n }",
"score": 6.7444174109635275
}
] | 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/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": 54.62213600486558
},
{
"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": 34.92177726382715
},
{
"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": 33.85402273099968
},
{
"filename": "src/test/java/raven/demo/CustomNotification.java",
"retrieved_chunk": "package raven.demo;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport raven.toast.ui.ToastNotificationPanel;\nimport javax.swing.*;\npublic class CustomNotification extends Notifications {\n @Override\n protected ToastNotificationPanel createNotification(Type type, String message) {\n ToastNotificationPanel toastNotificationPanel = super.createNotification(type, message);",
"score": 33.00172259077562
},
{
"filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java",
"retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport com.formdev.flatlaf.extras.FlatSVGIcon;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport javax.swing.*;\nimport java.awt.*;\npublic class ToastNotificationPanel extends JPanel {\n protected JWindow window;\n protected JLabel labelIcon;",
"score": 23.794245136853363
}
] | java | toastNotificationPanel.setDialog(window); |
package raven.toast.ui;
import static com.formdev.flatlaf.FlatClientProperties.*;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.ui.FlatStylingSupport;
import com.formdev.flatlaf.ui.FlatStylingSupport.StyleableUI;
import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.LoggingFacade;
import com.formdev.flatlaf.util.UIScale;
import static raven.toast.ToastClientProperties.*;
import raven.toast.util.UIUtils;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicPanelUI;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;
import java.util.function.Consumer;
public class ToastPanelUI extends BasicPanelUI implements StyleableUI, PropertyChangeListener {
protected JComponent iconComponent;
protected JComponent component;
protected JComponent closeButton;
@Styleable
protected int iconTextGap;
@Styleable
protected int closeButtonGap;
@Styleable
protected int minimumWidth;
@Styleable
protected int maximumWidth;
@Styleable
protected int arc;
@Styleable
protected int outlineWidth;
@Styleable
protected Color outlineColor;
@Styleable
protected boolean showCloseButton;
@Styleable
protected Color closeIconColor;
@Styleable
protected Insets margin;
@Styleable
protected Icon closeButtonIcon;
@Styleable
protected boolean useEffect;
@Styleable
protected Color effectColor;
@Styleable
protected float effectWidth;
@Styleable
protected float effectOpacity;
@Styleable
protected String effectAlignment;
private PanelNotificationLayout layout;
private Map<String, Object> oldStyleValues;
@Override
public void installUI(JComponent c) {
super.installUI(c);
c.addPropertyChangeListener(this);
installIconComponent(c);
installComponent(c);
installCloseButton(c);
installStyle((JPanel) c);
}
@Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removePropertyChangeListener(this);
uninstallIconComponent(c);
uninstallComponent(c);
uninstallCloseButton(c);
}
@Override
protected void installDefaults(JPanel p) {
super.installDefaults(p);
String prefix = getPropertyPrefix();
iconTextGap = FlatUIUtils.getUIInt(prefix + ".iconTextGap", 5);
closeButtonGap = FlatUIUtils.getUIInt(prefix + ".closeButtonGap", 5);
minimumWidth = FlatUIUtils.getUIInt(prefix + ".minimumWidth", 50);
maximumWidth = FlatUIUtils.getUIInt(prefix + ".maximumWidth", -1);
arc = FlatUIUtils.getUIInt(prefix + ".arc", 20);
outlineWidth = FlatUIUtils.getUIInt(prefix + ".outlineWidth", 0);
outlineColor = FlatUIUtils.getUIColor(prefix + ".outlineColor", "Component.focusColor");
margin = UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8));
showCloseButton = FlatUIUtils.getUIBoolean(prefix + ".showCloseButton", true);
closeIconColor = FlatUIUtils.getUIColor(prefix + ".closeIconColor", new Color(150, 150, 150));
closeButtonIcon = UIUtils.getIcon(prefix | + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f)); |
useEffect = FlatUIUtils.getUIBoolean(prefix + ".useEffect", true);
effectColor = FlatUIUtils.getUIColor(prefix + ".effectColor", "Component.focusColor");
effectWidth = FlatUIUtils.getUIFloat(prefix + ".effectWidth", 0.5f);
effectOpacity = FlatUIUtils.getUIFloat(prefix + ".effectOpacity", 0.2f);
effectAlignment = UIUtils.getString(prefix + ".effectAlignment", "left");
p.setBackground(FlatUIUtils.getUIColor(prefix + ".background", "Panel.background"));
p.setBorder(createDefaultBorder());
LookAndFeel.installProperty(p, "opaque", false);
}
@Override
protected void uninstallDefaults(JPanel p) {
super.uninstallDefaults(p);
oldStyleValues = null;
}
protected Border createDefaultBorder() {
Color color = FlatUIUtils.getUIColor("Toast.shadowColor", new Color(0, 0, 0));
Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6));
float shadowOpacity = FlatUIUtils.getUIFloat("Toast.shadowOpacity", 0.1f);
return new DropShadowBorder(color, insets, shadowOpacity);
}
protected String getPropertyPrefix() {
return "Toast";
}
@Override
public void propertyChange(PropertyChangeEvent e) {
switch (e.getPropertyName()) {
case TOAST_ICON: {
JPanel c = (JPanel) e.getSource();
uninstallIconComponent(c);
installIconComponent(c);
c.revalidate();
c.repaint();
break;
}
case TOAST_COMPONENT: {
JPanel c = (JPanel) e.getSource();
uninstallComponent(c);
installComponent(c);
c.revalidate();
c.repaint();
break;
}
case TOAST_SHOW_CLOSE_BUTTON: {
JPanel c = (JPanel) e.getSource();
uninstallCloseButton(c);
installCloseButton(c);
c.revalidate();
c.repaint();
break;
}
case STYLE:
case STYLE_CLASS: {
JPanel c = (JPanel) e.getSource();
installStyle(c);
c.revalidate();
c.repaint();
break;
}
}
}
private void installIconComponent(JComponent c) {
iconComponent = clientProperty(c, TOAST_ICON, null, JComponent.class);
if (iconComponent != null) {
installLayout(c);
c.add(iconComponent);
}
}
private void uninstallIconComponent(JComponent c) {
if (iconComponent != null) {
c.remove(iconComponent);
iconComponent = null;
}
}
private void installComponent(JComponent c) {
component = FlatClientProperties.clientProperty(c, TOAST_COMPONENT, null, JComponent.class);
if (component != null) {
installLayout(c);
c.add(component);
}
}
private void uninstallComponent(JComponent c) {
if (component != null) {
c.remove(component);
component = null;
}
}
private void installCloseButton(JComponent c) {
if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) {
closeButton = createCloseButton(c);
installLayout(c);
c.add(closeButton);
}
}
private void uninstallCloseButton(JComponent c) {
if (closeButton != null) {
c.remove(closeButton);
closeButton = null;
}
}
protected JComponent createCloseButton(JComponent c) {
JButton button = new JButton();
button.setFocusable(false);
button.setName("Toast.closeButton");
button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON);
button.putClientProperty(STYLE, "" +
"arc:999");
button.setIcon(closeButtonIcon);
button.addActionListener(e -> closeButtonClicked(c));
return button;
}
protected void closeButtonClicked(JComponent c) {
Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK);
if (callback instanceof Runnable) {
((Runnable) callback).run();
} else if (callback instanceof Consumer) {
((Consumer) callback).accept(c);
}
}
public void installLayout(JComponent c) {
if (layout == null) {
layout = new PanelNotificationLayout();
}
c.setLayout(layout);
}
protected void installStyle(JPanel c) {
try {
applyStyle(c, FlatStylingSupport.getResolvedStyle(c, "ToastPanel"));
} catch (RuntimeException ex) {
LoggingFacade.INSTANCE.logSevere(null, ex);
}
}
protected void applyStyle(JPanel c, Object style) {
boolean oldShowCloseButton = showCloseButton;
oldStyleValues = FlatStylingSupport.parseAndApply(oldStyleValues, style, (key, value) -> applyStyleProperty(c, key, value));
if (oldShowCloseButton != showCloseButton) {
uninstallCloseButton(c);
installCloseButton(c);
}
}
protected Object applyStyleProperty(JPanel c, String key, Object value) {
return FlatStylingSupport.applyToAnnotatedObjectOrComponent(this, c, key, value);
}
@Override
public Map<String, Class<?>> getStyleableInfos(JComponent c) {
return FlatStylingSupport.getAnnotatedStyleableInfos(this);
}
@Override
public Object getStyleableValue(JComponent c, String key) {
return FlatStylingSupport.getAnnotatedStyleableValue(this, key);
}
protected class PanelNotificationLayout implements LayoutManager {
@Override
public void addLayoutComponent(String name, Component comp) {
}
@Override
public void removeLayoutComponent(Component comp) {
}
@Override
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin));
int width = insets.left + insets.right;
int height = 0;
int gap = 0;
int closeGap = 0;
if (iconComponent != null) {
width += iconComponent.getPreferredSize().width;
height = Math.max(height, iconComponent.getPreferredSize().height);
gap = UIScale.scale(iconTextGap);
}
if (component != null) {
width += gap;
width += component.getPreferredSize().width;
height = Math.max(height, component.getPreferredSize().height);
closeGap = UIScale.scale(closeButtonGap);
}
if (closeButton != null) {
width += closeGap;
width += closeButton.getPreferredSize().width;
height = Math.max(height, closeButton.getPreferredSize().height);
}
height += (insets.top + insets.bottom);
width = Math.max(minimumWidth, maximumWidth == -1 ? width : Math.min(maximumWidth, width));
return new Dimension(width, height);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
return new Dimension(0, 0);
}
}
private int getMaxWidth(int insets) {
int width = Math.max(maximumWidth, minimumWidth) - insets;
if (iconComponent != null) {
width -= (iconComponent.getPreferredSize().width + UIScale.scale(iconTextGap));
}
if (closeButton != null) {
width -= (UIScale.scale(closeButtonGap) + closeButton.getPreferredSize().width);
}
return width;
}
@Override
public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin));
int x = insets.left;
int y = insets.top;
int height = 0;
if (iconComponent != null) {
int iconW = iconComponent.getPreferredSize().width;
int iconH = iconComponent.getPreferredSize().height;
iconComponent.setBounds(x, y, iconW, iconH);
x += iconW;
height = iconH;
}
if (component != null) {
int cW = maximumWidth == -1 ? component.getPreferredSize().width : Math.min(component.getPreferredSize().width, getMaxWidth(insets.left + insets.right));
int cH = component.getPreferredSize().height;
x += UIScale.scale(iconTextGap);
component.setBounds(x, y, cW, cH);
height = Math.max(height, cH);
}
if (closeButton != null) {
int cW = closeButton.getPreferredSize().width;
int cH = closeButton.getPreferredSize().height;
int cX = parent.getWidth() - insets.right - cW;
int cy = y + ((height - cH) / 2);
closeButton.setBounds(cX, cy, cW, cH);
}
}
}
}
}
| src/main/java/raven/toast/ui/ToastPanelUI.java | DJ-Raven-swing-toast-notifications-4c7978a | [
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " * Toast.error.foreground Color\n * Toast.error.background Color\n * <p>\n * Toast.frameInsets Insets 10,10,10,10 (default)\n * Toast.margin Insets 8,8,8,8 (default)\n * <p>\n * Toast.showCloseButton boolean true (default)\n * Toast.closeIconColor Color\n *\n * <p>",
"score": 66.90733549172501
},
{
"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": 50.27924378503038
},
{
"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": 39.967530193456405
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " }\n public void start() {\n int animation = FlatUIUtils.getUIInt(\"Toast.animation\", 200);\n int resolution = FlatUIUtils.getUIInt(\"Toast.animationResolution\", 5);\n animator = new Animator(animation, new Animator.TimingTarget() {\n @Override\n public void begin() {\n if (show) {\n updateList(location, NotificationAnimation.this, true);\n installLocation();",
"score": 39.35899035682263
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " }\n public void show(Location location, long duration, JComponent component) {\n initStart(new NotificationAnimation(location, duration, component), duration);\n }\n private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) {\n int limit = FlatUIUtils.getUIInt(\"Toast.limit\", -1);\n if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) {\n notificationAnimation.start();\n return true;\n } else {",
"score": 29.161942318220856
}
] | java | + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f)); |
package raven.toast;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.Animator;
import com.formdev.flatlaf.util.UIScale;
import raven.toast.ui.ToastNotificationPanel;
import raven.toast.util.NotificationHolder;
import raven.toast.util.UIUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
/**
* <!-- FlatLaf Property -->
* <p>
* Toast.outlineWidth int 0 (default)
* Toast.iconTextGap int 5 (default)
* Toast.closeButtonGap int 5 (default)
* Toast.arc int 20 (default)
* Toast.horizontalGap int 10 (default)
* <p>
* Toast.limit int -1 (default) -1 as unlimited
* Toast.duration long 2500 (default)
* Toast.animation int 200 (default)
* Toast.animationResolution int 5 (default)
* Toast.animationMove int 10 (default)
* Toast.minimumWidth int 50 (default)
* Toast.maximumWidth int -1 (default) -1 as not set
* <p>
* Toast.shadowColor Color
* Toast.shadowOpacity float 0.1f (default)
* Toast.shadowInsets Insets 0,0,6,6 (default)
* <p>
* Toast.useEffect boolean true (default)
* Toast.effectWidth float 0.5f (default) 0.5f as 50%
* Toast.effectOpacity float 0.2f (default) 0 to 1
* Toast.effectAlignment String left (default) left, right
* Toast.effectColor Color
* Toast.success.effectColor Color
* Toast.info.effectColor Color
* Toast.warning.effectColor Color
* Toast.error.effectColor Color
* <p>
* Toast.outlineColor Color
* Toast.foreground Color
* Toast.background Color
* <p>
* Toast.success.outlineColor Color
* Toast.success.foreground Color
* Toast.success.background Color
* Toast.info.outlineColor Color
* Toast.info.foreground Color
* Toast.info.background Color
* Toast.warning.outlineColor Color
* Toast.warning.foreground Color
* Toast.warning.background Color
* Toast.error.outlineColor Color
* Toast.error.foreground Color
* Toast.error.background Color
* <p>
* Toast.frameInsets Insets 10,10,10,10 (default)
* Toast.margin Insets 8,8,8,8 (default)
* <p>
* Toast.showCloseButton boolean true (default)
* Toast.closeIconColor Color
*
* <p>
* <!-- UIManager -->
* <p>
* Toast.success.icon Icon
* Toast.info.icon Icon
* Toast.warning.icon Icon
* Toast.error.icon Icon
* Toast.closeIcon Icon
*/
/**
* @author Raven
*/
public class Notifications {
private static Notifications instance;
private JFrame frame;
private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>();
private final NotificationHolder notificationHolder = new NotificationHolder();
private ComponentListener windowEvent;
private void installEvent(JFrame frame) {
if (windowEvent == null && frame != null) {
windowEvent = new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
move(frame.getBounds());
}
@Override
public void componentResized(ComponentEvent e) {
move(frame.getBounds());
}
};
}
if (this.frame != null) {
this.frame.removeComponentListener(windowEvent);
}
if (frame != null) {
frame.addComponentListener(windowEvent);
}
this.frame = frame;
}
public static Notifications getInstance() {
if (instance == null) {
instance = new Notifications();
}
return instance;
}
private int getCurrentShowCount(Location location) {
List list = lists.get(location);
return list == null ? 0 : list.size();
}
private synchronized void move(Rectangle rectangle) {
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) {
for (int i = 0; i < set.getValue().size(); i++) {
NotificationAnimation an = set.getValue().get(i);
if (an != null) {
an.move(rectangle);
}
}
}
}
public void setJFrame(JFrame frame) {
installEvent(frame);
}
public void show(Type type, String message) {
show(type, Location.TOP_CENTER, message);
}
public void show(Type type, long duration, String message) {
show(type, Location.TOP_CENTER, duration, message);
}
public void show(Type type, Location location, String message) {
long duration = FlatUIUtils.getUIInt("Toast.duration", 2500);
show(type, location, duration, message);
}
public void show(Type type, Location location, long duration, String message) {
initStart(new NotificationAnimation(type, location, duration, message), duration);
}
public void show(JComponent component) {
show(Location.TOP_CENTER, component);
}
public void show(Location location, JComponent component) {
long duration = FlatUIUtils.getUIInt("Toast.duration", 2500);
show(location, duration, component);
}
public void show(Location location, long duration, JComponent component) {
initStart(new NotificationAnimation(location, duration, component), duration);
}
private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) {
int limit = FlatUIUtils.getUIInt("Toast.limit", -1);
if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) {
notificationAnimation.start();
return true;
} else {
notificationHolder.hold(notificationAnimation);
return false;
}
}
private synchronized void notificationClose(NotificationAnimation notificationAnimation) {
NotificationAnimation | hold = notificationHolder.getHold(notificationAnimation.getLocation()); |
if (hold != null) {
if (initStart(hold, hold.getDuration())) {
notificationHolder.removeHold(hold);
}
}
}
public void clearAll() {
notificationHolder.clearHold();
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) {
for (int i = 0; i < set.getValue().size(); i++) {
NotificationAnimation an = set.getValue().get(i);
if (an != null) {
an.close();
}
}
}
}
public void clear(Location location) {
notificationHolder.clearHold(location);
List<NotificationAnimation> list = lists.get(location);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
NotificationAnimation an = list.get(i);
if (an != null) {
an.close();
}
}
}
}
public void clearHold() {
notificationHolder.clearHold();
}
public void clearHold(Location location) {
notificationHolder.clearHold(location);
}
protected ToastNotificationPanel createNotification(Type type, String message) {
ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel();
toastNotificationPanel.set(type, message);
return toastNotificationPanel;
}
private synchronized void updateList(Location key, NotificationAnimation values, boolean add) {
if (add) {
if (lists.containsKey(key)) {
lists.get(key).add(values);
} else {
List<NotificationAnimation> list = new ArrayList<>();
list.add(values);
lists.put(key, list);
}
} else {
if (lists.containsKey(key)) {
lists.get(key).remove(values);
if (lists.get(key).isEmpty()) {
lists.remove(key);
}
}
}
}
public enum Type {
SUCCESS, INFO, WARNING, ERROR
}
public enum Location {
TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT
}
public class NotificationAnimation {
private JWindow window;
private Animator animator;
private boolean show = true;
private float animate;
private int x;
private int y;
private Location location;
private long duration;
private Insets frameInsets;
private int horizontalSpace;
private int animationMove;
private boolean top;
private boolean close = false;
public NotificationAnimation(Type type, Location location, long duration, String message) {
installDefault();
this.location = location;
this.duration = duration;
window = new JWindow(frame);
ToastNotificationPanel toastNotificationPanel = createNotification(type, message);
toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close());
window.setContentPane(toastNotificationPanel);
window.setFocusableWindowState(false);
window.pack();
toastNotificationPanel.setDialog(window);
}
public NotificationAnimation(Location location, long duration, JComponent component) {
installDefault();
this.location = location;
this.duration = duration;
window = new JWindow(frame);
window.setBackground(new Color(0, 0, 0, 0));
window.setContentPane(component);
window.setFocusableWindowState(false);
window.setSize(component.getPreferredSize());
}
private void installDefault() {
frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10));
horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10);
animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10);
}
public void start() {
int animation = FlatUIUtils.getUIInt("Toast.animation", 200);
int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5);
animator = new Animator(animation, new Animator.TimingTarget() {
@Override
public void begin() {
if (show) {
updateList(location, NotificationAnimation.this, true);
installLocation();
}
}
@Override
public void timingEvent(float f) {
animate = show ? f : 1f - f;
updateLocation(true);
}
@Override
public void end() {
if (show && close == false) {
SwingUtilities.invokeLater(() -> {
new Thread(() -> {
sleep(duration);
if (close == false) {
show = false;
animator.start();
}
}).start();
});
} else {
updateList(location, NotificationAnimation.this, false);
window.dispose();
notificationClose(NotificationAnimation.this);
}
}
});
animator.setResolution(resolution);
animator.start();
}
private void installLocation() {
Insets insets;
Rectangle rec;
if (frame == null) {
insets = UIScale.scale(frameInsets);
rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize());
} else {
insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets()));
rec = frame.getBounds();
}
setupLocation(rec, insets);
window.setOpacity(0f);
window.setVisible(true);
}
private void move(Rectangle rec) {
Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets()));
setupLocation(rec, insets);
}
private void setupLocation(Rectangle rec, Insets insets) {
if (location == Location.TOP_LEFT) {
x = rec.x + insets.left;
y = rec.y + insets.top;
top = true;
} else if (location == Location.TOP_CENTER) {
x = rec.x + (rec.width - window.getWidth()) / 2;
y = rec.y + insets.top;
top = true;
} else if (location == Location.TOP_RIGHT) {
x = rec.x + rec.width - (window.getWidth() + insets.right);
y = rec.y + insets.top;
top = true;
} else if (location == Location.BOTTOM_LEFT) {
x = rec.x + insets.left;
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
} else if (location == Location.BOTTOM_CENTER) {
x = rec.x + (rec.width - window.getWidth()) / 2;
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
} else if (location == Location.BOTTOM_RIGHT) {
x = rec.x + rec.width - (window.getWidth() + insets.right);
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
}
int am = UIScale.scale(top ? animationMove : -animationMove);
int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am);
window.setLocation(x, ly);
}
private void updateLocation(boolean loop) {
int am = UIScale.scale(top ? animationMove : -animationMove);
int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am);
window.setLocation(x, ly);
window.setOpacity(animate);
if (loop) {
update(this);
}
}
private int getLocation(NotificationAnimation notification) {
int height = 0;
List<NotificationAnimation> list = lists.get(location);
for (int i = 0; i < list.size(); i++) {
NotificationAnimation n = list.get(i);
if (notification == n) {
return height;
}
double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace));
height += top ? v : -v;
}
return height;
}
private void update(NotificationAnimation except) {
List<NotificationAnimation> list = lists.get(location);
for (int i = 0; i < list.size(); i++) {
NotificationAnimation n = list.get(i);
if (n != except) {
n.updateLocation(false);
}
}
}
public void close() {
close = true;
show = false;
if (animator.isRunning()) {
animator.stop();
}
animator.start();
}
private void sleep(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
System.err.println(e);
}
}
public Location getLocation() {
return location;
}
public long getDuration() {
return duration;
}
}
}
| src/main/java/raven/toast/Notifications.java | DJ-Raven-swing-toast-notifications-4c7978a | [
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }",
"score": 57.8719117549952
},
{
"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": 21.79102673906861
},
{
"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": 11.614713727274301
},
{
"filename": "src/test/java/raven/demo/Test.java",
"retrieved_chunk": " @Override\n public void actionPerformed(ActionEvent e) {\n if (cmdMode.getText().equals(\"Mode Light\")) {\n changeMode(true);\n cmdMode.setText(\"Mode Dark\");\n } else {\n changeMode(false);\n cmdMode.setText(\"Mode Light\");\n }\n }",
"score": 9.794011827348589
},
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }",
"score": 8.447947950175164
}
] | java | hold = notificationHolder.getHold(notificationAnimation.getLocation()); |
package raven.toast.ui;
import static com.formdev.flatlaf.FlatClientProperties.*;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.ui.FlatStylingSupport;
import com.formdev.flatlaf.ui.FlatStylingSupport.StyleableUI;
import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.LoggingFacade;
import com.formdev.flatlaf.util.UIScale;
import static raven.toast.ToastClientProperties.*;
import raven.toast.util.UIUtils;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicPanelUI;
import java.awt.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Map;
import java.util.function.Consumer;
public class ToastPanelUI extends BasicPanelUI implements StyleableUI, PropertyChangeListener {
protected JComponent iconComponent;
protected JComponent component;
protected JComponent closeButton;
@Styleable
protected int iconTextGap;
@Styleable
protected int closeButtonGap;
@Styleable
protected int minimumWidth;
@Styleable
protected int maximumWidth;
@Styleable
protected int arc;
@Styleable
protected int outlineWidth;
@Styleable
protected Color outlineColor;
@Styleable
protected boolean showCloseButton;
@Styleable
protected Color closeIconColor;
@Styleable
protected Insets margin;
@Styleable
protected Icon closeButtonIcon;
@Styleable
protected boolean useEffect;
@Styleable
protected Color effectColor;
@Styleable
protected float effectWidth;
@Styleable
protected float effectOpacity;
@Styleable
protected String effectAlignment;
private PanelNotificationLayout layout;
private Map<String, Object> oldStyleValues;
@Override
public void installUI(JComponent c) {
super.installUI(c);
c.addPropertyChangeListener(this);
installIconComponent(c);
installComponent(c);
installCloseButton(c);
installStyle((JPanel) c);
}
@Override
public void uninstallUI(JComponent c) {
super.uninstallUI(c);
c.removePropertyChangeListener(this);
uninstallIconComponent(c);
uninstallComponent(c);
uninstallCloseButton(c);
}
@Override
protected void installDefaults(JPanel p) {
super.installDefaults(p);
String prefix = getPropertyPrefix();
iconTextGap = FlatUIUtils.getUIInt(prefix + ".iconTextGap", 5);
closeButtonGap = FlatUIUtils.getUIInt(prefix + ".closeButtonGap", 5);
minimumWidth = FlatUIUtils.getUIInt(prefix + ".minimumWidth", 50);
maximumWidth = FlatUIUtils.getUIInt(prefix + ".maximumWidth", -1);
arc = FlatUIUtils.getUIInt(prefix + ".arc", 20);
outlineWidth = FlatUIUtils.getUIInt(prefix + ".outlineWidth", 0);
outlineColor = FlatUIUtils.getUIColor(prefix + ".outlineColor", "Component.focusColor");
margin = | UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8)); |
showCloseButton = FlatUIUtils.getUIBoolean(prefix + ".showCloseButton", true);
closeIconColor = FlatUIUtils.getUIColor(prefix + ".closeIconColor", new Color(150, 150, 150));
closeButtonIcon = UIUtils.getIcon(prefix + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f));
useEffect = FlatUIUtils.getUIBoolean(prefix + ".useEffect", true);
effectColor = FlatUIUtils.getUIColor(prefix + ".effectColor", "Component.focusColor");
effectWidth = FlatUIUtils.getUIFloat(prefix + ".effectWidth", 0.5f);
effectOpacity = FlatUIUtils.getUIFloat(prefix + ".effectOpacity", 0.2f);
effectAlignment = UIUtils.getString(prefix + ".effectAlignment", "left");
p.setBackground(FlatUIUtils.getUIColor(prefix + ".background", "Panel.background"));
p.setBorder(createDefaultBorder());
LookAndFeel.installProperty(p, "opaque", false);
}
@Override
protected void uninstallDefaults(JPanel p) {
super.uninstallDefaults(p);
oldStyleValues = null;
}
protected Border createDefaultBorder() {
Color color = FlatUIUtils.getUIColor("Toast.shadowColor", new Color(0, 0, 0));
Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6));
float shadowOpacity = FlatUIUtils.getUIFloat("Toast.shadowOpacity", 0.1f);
return new DropShadowBorder(color, insets, shadowOpacity);
}
protected String getPropertyPrefix() {
return "Toast";
}
@Override
public void propertyChange(PropertyChangeEvent e) {
switch (e.getPropertyName()) {
case TOAST_ICON: {
JPanel c = (JPanel) e.getSource();
uninstallIconComponent(c);
installIconComponent(c);
c.revalidate();
c.repaint();
break;
}
case TOAST_COMPONENT: {
JPanel c = (JPanel) e.getSource();
uninstallComponent(c);
installComponent(c);
c.revalidate();
c.repaint();
break;
}
case TOAST_SHOW_CLOSE_BUTTON: {
JPanel c = (JPanel) e.getSource();
uninstallCloseButton(c);
installCloseButton(c);
c.revalidate();
c.repaint();
break;
}
case STYLE:
case STYLE_CLASS: {
JPanel c = (JPanel) e.getSource();
installStyle(c);
c.revalidate();
c.repaint();
break;
}
}
}
private void installIconComponent(JComponent c) {
iconComponent = clientProperty(c, TOAST_ICON, null, JComponent.class);
if (iconComponent != null) {
installLayout(c);
c.add(iconComponent);
}
}
private void uninstallIconComponent(JComponent c) {
if (iconComponent != null) {
c.remove(iconComponent);
iconComponent = null;
}
}
private void installComponent(JComponent c) {
component = FlatClientProperties.clientProperty(c, TOAST_COMPONENT, null, JComponent.class);
if (component != null) {
installLayout(c);
c.add(component);
}
}
private void uninstallComponent(JComponent c) {
if (component != null) {
c.remove(component);
component = null;
}
}
private void installCloseButton(JComponent c) {
if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) {
closeButton = createCloseButton(c);
installLayout(c);
c.add(closeButton);
}
}
private void uninstallCloseButton(JComponent c) {
if (closeButton != null) {
c.remove(closeButton);
closeButton = null;
}
}
protected JComponent createCloseButton(JComponent c) {
JButton button = new JButton();
button.setFocusable(false);
button.setName("Toast.closeButton");
button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON);
button.putClientProperty(STYLE, "" +
"arc:999");
button.setIcon(closeButtonIcon);
button.addActionListener(e -> closeButtonClicked(c));
return button;
}
protected void closeButtonClicked(JComponent c) {
Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK);
if (callback instanceof Runnable) {
((Runnable) callback).run();
} else if (callback instanceof Consumer) {
((Consumer) callback).accept(c);
}
}
public void installLayout(JComponent c) {
if (layout == null) {
layout = new PanelNotificationLayout();
}
c.setLayout(layout);
}
protected void installStyle(JPanel c) {
try {
applyStyle(c, FlatStylingSupport.getResolvedStyle(c, "ToastPanel"));
} catch (RuntimeException ex) {
LoggingFacade.INSTANCE.logSevere(null, ex);
}
}
protected void applyStyle(JPanel c, Object style) {
boolean oldShowCloseButton = showCloseButton;
oldStyleValues = FlatStylingSupport.parseAndApply(oldStyleValues, style, (key, value) -> applyStyleProperty(c, key, value));
if (oldShowCloseButton != showCloseButton) {
uninstallCloseButton(c);
installCloseButton(c);
}
}
protected Object applyStyleProperty(JPanel c, String key, Object value) {
return FlatStylingSupport.applyToAnnotatedObjectOrComponent(this, c, key, value);
}
@Override
public Map<String, Class<?>> getStyleableInfos(JComponent c) {
return FlatStylingSupport.getAnnotatedStyleableInfos(this);
}
@Override
public Object getStyleableValue(JComponent c, String key) {
return FlatStylingSupport.getAnnotatedStyleableValue(this, key);
}
protected class PanelNotificationLayout implements LayoutManager {
@Override
public void addLayoutComponent(String name, Component comp) {
}
@Override
public void removeLayoutComponent(Component comp) {
}
@Override
public Dimension preferredLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin));
int width = insets.left + insets.right;
int height = 0;
int gap = 0;
int closeGap = 0;
if (iconComponent != null) {
width += iconComponent.getPreferredSize().width;
height = Math.max(height, iconComponent.getPreferredSize().height);
gap = UIScale.scale(iconTextGap);
}
if (component != null) {
width += gap;
width += component.getPreferredSize().width;
height = Math.max(height, component.getPreferredSize().height);
closeGap = UIScale.scale(closeButtonGap);
}
if (closeButton != null) {
width += closeGap;
width += closeButton.getPreferredSize().width;
height = Math.max(height, closeButton.getPreferredSize().height);
}
height += (insets.top + insets.bottom);
width = Math.max(minimumWidth, maximumWidth == -1 ? width : Math.min(maximumWidth, width));
return new Dimension(width, height);
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
synchronized (parent.getTreeLock()) {
return new Dimension(0, 0);
}
}
private int getMaxWidth(int insets) {
int width = Math.max(maximumWidth, minimumWidth) - insets;
if (iconComponent != null) {
width -= (iconComponent.getPreferredSize().width + UIScale.scale(iconTextGap));
}
if (closeButton != null) {
width -= (UIScale.scale(closeButtonGap) + closeButton.getPreferredSize().width);
}
return width;
}
@Override
public void layoutContainer(Container parent) {
synchronized (parent.getTreeLock()) {
Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin));
int x = insets.left;
int y = insets.top;
int height = 0;
if (iconComponent != null) {
int iconW = iconComponent.getPreferredSize().width;
int iconH = iconComponent.getPreferredSize().height;
iconComponent.setBounds(x, y, iconW, iconH);
x += iconW;
height = iconH;
}
if (component != null) {
int cW = maximumWidth == -1 ? component.getPreferredSize().width : Math.min(component.getPreferredSize().width, getMaxWidth(insets.left + insets.right));
int cH = component.getPreferredSize().height;
x += UIScale.scale(iconTextGap);
component.setBounds(x, y, cW, cH);
height = Math.max(height, cH);
}
if (closeButton != null) {
int cW = closeButton.getPreferredSize().width;
int cH = closeButton.getPreferredSize().height;
int cX = parent.getWidth() - insets.right - cW;
int cy = y + ((height - cH) / 2);
closeButton.setBounds(cX, cy, cW, cH);
}
}
}
}
}
| src/main/java/raven/toast/ui/ToastPanelUI.java | DJ-Raven-swing-toast-notifications-4c7978a | [
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " }\n public void start() {\n int animation = FlatUIUtils.getUIInt(\"Toast.animation\", 200);\n int resolution = FlatUIUtils.getUIInt(\"Toast.animationResolution\", 5);\n animator = new Animator(animation, new Animator.TimingTarget() {\n @Override\n public void begin() {\n if (show) {\n updateList(location, NotificationAnimation.this, true);\n installLocation();",
"score": 49.70783928977656
},
{
"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": 48.66384463826309
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " * Toast.error.foreground Color\n * Toast.error.background Color\n * <p>\n * Toast.frameInsets Insets 10,10,10,10 (default)\n * Toast.margin Insets 8,8,8,8 (default)\n * <p>\n * Toast.showCloseButton boolean true (default)\n * Toast.closeIconColor Color\n *\n * <p>",
"score": 42.193410492961284
},
{
"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": 37.69666667488599
},
{
"filename": "src/main/java/raven/toast/Notifications.java",
"retrieved_chunk": " * Toast.closeButtonGap int 5 (default)\n * Toast.arc int 20 (default)\n * Toast.horizontalGap int 10 (default)\n * <p>\n * Toast.limit int -1 (default) -1 as unlimited\n * Toast.duration long 2500 (default)\n * Toast.animation int 200 (default)\n * Toast.animationResolution int 5 (default)\n * Toast.animationMove int 10 (default)\n * Toast.minimumWidth int 50 (default)",
"score": 35.1705672258002
}
] | 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": 54.05012463725539
},
{
"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": 47.29613441416487
},
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": " if (n.getLocation() == location) {\n lists.remove(n);\n i--;\n }\n }\n }\n }\n}",
"score": 25.881286626410418
},
{
"filename": "src/main/java/raven/toast/util/ShadowRenderer.java",
"retrieved_chunk": " }\n int[] vSumLookup = new int[256 * shadowSize];\n for (int i = 0; i < vSumLookup.length; i++) {\n vSumLookup[i] = (int) (i * vSumDivider);\n }\n int srcOffset;\n for (int srcY = 0, dstOffset = left * dstWidth; srcY < srcHeight; srcY++) {\n for (historyIdx = 0; historyIdx < shadowSize; ) {\n aHistory[historyIdx++] = 0;\n }",
"score": 25.64226285365455
},
{
"filename": "src/main/java/raven/toast/util/ShadowRenderer.java",
"retrieved_chunk": " if (++historyIdx >= shadowSize) {\n historyIdx -= shadowSize;\n }\n }\n for (int i = 0; i < shadowSize; i++) {\n int a = hSumLookup[aSum];\n dstBuffer[dstOffset++] = a << 24;\n aSum -= aHistory[historyIdx];\n if (++historyIdx >= shadowSize) {\n historyIdx -= shadowSize;",
"score": 22.87935242704884
}
] | 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/test/java/raven/demo/CustomNotification.java",
"retrieved_chunk": "package raven.demo;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport raven.toast.ui.ToastNotificationPanel;\nimport javax.swing.*;\npublic class CustomNotification extends Notifications {\n @Override\n protected ToastNotificationPanel createNotification(Type type, String message) {\n ToastNotificationPanel toastNotificationPanel = super.createNotification(type, message);",
"score": 46.042584059899355
},
{
"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": 34.8090238867756
},
{
"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": 23.513265902898876
},
{
"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": 21.50825906898657
},
{
"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": 20.754965372182287
}
] | java | toastNotificationPanel.set(type, message); |
package sprites;
import domain.CompositeShape;
import domain.GenericShape;
import domain.Point;
import domain.Shape;
import primitives.Line;
import primitives.Rectangle;
import primitives.Square;
import transformations.MoveBy;
import java.util.ArrayList;
import java.util.List;
public class House extends CompositeShape {
private final Point lowerLeft;
public House(Point lowerLeft) {
this.lowerLeft = lowerLeft;
}
@Override
protected List<Shape> getShapes() {
List<Shape> allShapes = new ArrayList<>();
allShapes.add(new Rectangle(new Point(0, 0), new Point(26, 20))); //wall
allShapes.add(new Rectangle(new Point(17, 0), new Point(22, 12))); //door
allShapes.add(new Square(new Point(5, 10), 5)); //window
allShapes.add(new Line(new Point(0, 20), new Point(12, 25)));
allShapes.add(new Line(new Point(12, 25), new Point(26, 20)));
return allShapes;
}
@Override
public List<Point> getPoints() {
List<Point> originalPoints = super.getPoints();
return new MoveBy(lowerLeft.getX(), | lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints(); |
}
}
| src/main/java/sprites/House.java | dmitriyvolk-redrover-draw-b9b5e7d | [
{
"filename": "src/main/java/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": 28.41019311578586
},
{
"filename": "src/main/java/primitives/Rectangle.java",
"retrieved_chunk": "package primitives;\nimport domain.Point;\npublic class Rectangle extends Quadrilateral {\n public Rectangle(Point vertex1, Point vertex2) {\n super(\n vertex1, //0, 0\n new Point(vertex1.getX(), vertex2.getY()), //0, 10\n vertex2, //20, 10\n new Point(vertex2.getX(), vertex1.getY())// 20, 0\n );",
"score": 27.740021345194307
},
{
"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": 26.92246675588597
},
{
"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": 26.086342044199295
},
{
"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": 21.38350339835546
}
] | java | lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints(); |
package raven.toast;
import com.formdev.flatlaf.ui.FlatUIUtils;
import com.formdev.flatlaf.util.Animator;
import com.formdev.flatlaf.util.UIScale;
import raven.toast.ui.ToastNotificationPanel;
import raven.toast.util.NotificationHolder;
import raven.toast.util.UIUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.*;
import java.util.List;
import java.util.function.Consumer;
/**
* <!-- FlatLaf Property -->
* <p>
* Toast.outlineWidth int 0 (default)
* Toast.iconTextGap int 5 (default)
* Toast.closeButtonGap int 5 (default)
* Toast.arc int 20 (default)
* Toast.horizontalGap int 10 (default)
* <p>
* Toast.limit int -1 (default) -1 as unlimited
* Toast.duration long 2500 (default)
* Toast.animation int 200 (default)
* Toast.animationResolution int 5 (default)
* Toast.animationMove int 10 (default)
* Toast.minimumWidth int 50 (default)
* Toast.maximumWidth int -1 (default) -1 as not set
* <p>
* Toast.shadowColor Color
* Toast.shadowOpacity float 0.1f (default)
* Toast.shadowInsets Insets 0,0,6,6 (default)
* <p>
* Toast.useEffect boolean true (default)
* Toast.effectWidth float 0.5f (default) 0.5f as 50%
* Toast.effectOpacity float 0.2f (default) 0 to 1
* Toast.effectAlignment String left (default) left, right
* Toast.effectColor Color
* Toast.success.effectColor Color
* Toast.info.effectColor Color
* Toast.warning.effectColor Color
* Toast.error.effectColor Color
* <p>
* Toast.outlineColor Color
* Toast.foreground Color
* Toast.background Color
* <p>
* Toast.success.outlineColor Color
* Toast.success.foreground Color
* Toast.success.background Color
* Toast.info.outlineColor Color
* Toast.info.foreground Color
* Toast.info.background Color
* Toast.warning.outlineColor Color
* Toast.warning.foreground Color
* Toast.warning.background Color
* Toast.error.outlineColor Color
* Toast.error.foreground Color
* Toast.error.background Color
* <p>
* Toast.frameInsets Insets 10,10,10,10 (default)
* Toast.margin Insets 8,8,8,8 (default)
* <p>
* Toast.showCloseButton boolean true (default)
* Toast.closeIconColor Color
*
* <p>
* <!-- UIManager -->
* <p>
* Toast.success.icon Icon
* Toast.info.icon Icon
* Toast.warning.icon Icon
* Toast.error.icon Icon
* Toast.closeIcon Icon
*/
/**
* @author Raven
*/
public class Notifications {
private static Notifications instance;
private JFrame frame;
private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>();
private final NotificationHolder notificationHolder = new NotificationHolder();
private ComponentListener windowEvent;
private void installEvent(JFrame frame) {
if (windowEvent == null && frame != null) {
windowEvent = new ComponentAdapter() {
@Override
public void componentMoved(ComponentEvent e) {
move(frame.getBounds());
}
@Override
public void componentResized(ComponentEvent e) {
move(frame.getBounds());
}
};
}
if (this.frame != null) {
this.frame.removeComponentListener(windowEvent);
}
if (frame != null) {
frame.addComponentListener(windowEvent);
}
this.frame = frame;
}
public static Notifications getInstance() {
if (instance == null) {
instance = new Notifications();
}
return instance;
}
private int getCurrentShowCount(Location location) {
List list = lists.get(location);
return list == null ? 0 : list.size();
}
private synchronized void move(Rectangle rectangle) {
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) {
for (int i = 0; i < set.getValue().size(); i++) {
NotificationAnimation an = set.getValue().get(i);
if (an != null) {
an.move(rectangle);
}
}
}
}
public void setJFrame(JFrame frame) {
installEvent(frame);
}
public void show(Type type, String message) {
show(type, Location.TOP_CENTER, message);
}
public void show(Type type, long duration, String message) {
show(type, Location.TOP_CENTER, duration, message);
}
public void show(Type type, Location location, String message) {
long duration = FlatUIUtils.getUIInt("Toast.duration", 2500);
show(type, location, duration, message);
}
public void show(Type type, Location location, long duration, String message) {
initStart(new NotificationAnimation(type, location, duration, message), duration);
}
public void show(JComponent component) {
show(Location.TOP_CENTER, component);
}
public void show(Location location, JComponent component) {
long duration = FlatUIUtils.getUIInt("Toast.duration", 2500);
show(location, duration, component);
}
public void show(Location location, long duration, JComponent component) {
initStart(new NotificationAnimation(location, duration, component), duration);
}
private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) {
int limit = FlatUIUtils.getUIInt("Toast.limit", -1);
if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) {
notificationAnimation.start();
return true;
} else {
| notificationHolder.hold(notificationAnimation); |
return false;
}
}
private synchronized void notificationClose(NotificationAnimation notificationAnimation) {
NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation());
if (hold != null) {
if (initStart(hold, hold.getDuration())) {
notificationHolder.removeHold(hold);
}
}
}
public void clearAll() {
notificationHolder.clearHold();
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) {
for (int i = 0; i < set.getValue().size(); i++) {
NotificationAnimation an = set.getValue().get(i);
if (an != null) {
an.close();
}
}
}
}
public void clear(Location location) {
notificationHolder.clearHold(location);
List<NotificationAnimation> list = lists.get(location);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
NotificationAnimation an = list.get(i);
if (an != null) {
an.close();
}
}
}
}
public void clearHold() {
notificationHolder.clearHold();
}
public void clearHold(Location location) {
notificationHolder.clearHold(location);
}
protected ToastNotificationPanel createNotification(Type type, String message) {
ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel();
toastNotificationPanel.set(type, message);
return toastNotificationPanel;
}
private synchronized void updateList(Location key, NotificationAnimation values, boolean add) {
if (add) {
if (lists.containsKey(key)) {
lists.get(key).add(values);
} else {
List<NotificationAnimation> list = new ArrayList<>();
list.add(values);
lists.put(key, list);
}
} else {
if (lists.containsKey(key)) {
lists.get(key).remove(values);
if (lists.get(key).isEmpty()) {
lists.remove(key);
}
}
}
}
public enum Type {
SUCCESS, INFO, WARNING, ERROR
}
public enum Location {
TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT
}
public class NotificationAnimation {
private JWindow window;
private Animator animator;
private boolean show = true;
private float animate;
private int x;
private int y;
private Location location;
private long duration;
private Insets frameInsets;
private int horizontalSpace;
private int animationMove;
private boolean top;
private boolean close = false;
public NotificationAnimation(Type type, Location location, long duration, String message) {
installDefault();
this.location = location;
this.duration = duration;
window = new JWindow(frame);
ToastNotificationPanel toastNotificationPanel = createNotification(type, message);
toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close());
window.setContentPane(toastNotificationPanel);
window.setFocusableWindowState(false);
window.pack();
toastNotificationPanel.setDialog(window);
}
public NotificationAnimation(Location location, long duration, JComponent component) {
installDefault();
this.location = location;
this.duration = duration;
window = new JWindow(frame);
window.setBackground(new Color(0, 0, 0, 0));
window.setContentPane(component);
window.setFocusableWindowState(false);
window.setSize(component.getPreferredSize());
}
private void installDefault() {
frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10));
horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10);
animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10);
}
public void start() {
int animation = FlatUIUtils.getUIInt("Toast.animation", 200);
int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5);
animator = new Animator(animation, new Animator.TimingTarget() {
@Override
public void begin() {
if (show) {
updateList(location, NotificationAnimation.this, true);
installLocation();
}
}
@Override
public void timingEvent(float f) {
animate = show ? f : 1f - f;
updateLocation(true);
}
@Override
public void end() {
if (show && close == false) {
SwingUtilities.invokeLater(() -> {
new Thread(() -> {
sleep(duration);
if (close == false) {
show = false;
animator.start();
}
}).start();
});
} else {
updateList(location, NotificationAnimation.this, false);
window.dispose();
notificationClose(NotificationAnimation.this);
}
}
});
animator.setResolution(resolution);
animator.start();
}
private void installLocation() {
Insets insets;
Rectangle rec;
if (frame == null) {
insets = UIScale.scale(frameInsets);
rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize());
} else {
insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets()));
rec = frame.getBounds();
}
setupLocation(rec, insets);
window.setOpacity(0f);
window.setVisible(true);
}
private void move(Rectangle rec) {
Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets()));
setupLocation(rec, insets);
}
private void setupLocation(Rectangle rec, Insets insets) {
if (location == Location.TOP_LEFT) {
x = rec.x + insets.left;
y = rec.y + insets.top;
top = true;
} else if (location == Location.TOP_CENTER) {
x = rec.x + (rec.width - window.getWidth()) / 2;
y = rec.y + insets.top;
top = true;
} else if (location == Location.TOP_RIGHT) {
x = rec.x + rec.width - (window.getWidth() + insets.right);
y = rec.y + insets.top;
top = true;
} else if (location == Location.BOTTOM_LEFT) {
x = rec.x + insets.left;
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
} else if (location == Location.BOTTOM_CENTER) {
x = rec.x + (rec.width - window.getWidth()) / 2;
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
} else if (location == Location.BOTTOM_RIGHT) {
x = rec.x + rec.width - (window.getWidth() + insets.right);
y = rec.y + rec.height - (window.getHeight() + insets.bottom);
top = false;
}
int am = UIScale.scale(top ? animationMove : -animationMove);
int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am);
window.setLocation(x, ly);
}
private void updateLocation(boolean loop) {
int am = UIScale.scale(top ? animationMove : -animationMove);
int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am);
window.setLocation(x, ly);
window.setOpacity(animate);
if (loop) {
update(this);
}
}
private int getLocation(NotificationAnimation notification) {
int height = 0;
List<NotificationAnimation> list = lists.get(location);
for (int i = 0; i < list.size(); i++) {
NotificationAnimation n = list.get(i);
if (notification == n) {
return height;
}
double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace));
height += top ? v : -v;
}
return height;
}
private void update(NotificationAnimation except) {
List<NotificationAnimation> list = lists.get(location);
for (int i = 0; i < list.size(); i++) {
NotificationAnimation n = list.get(i);
if (n != except) {
n.updateLocation(false);
}
}
}
public void close() {
close = true;
show = false;
if (animator.isRunning()) {
animator.stop();
}
animator.start();
}
private void sleep(long l) {
try {
Thread.sleep(l);
} catch (InterruptedException e) {
System.err.println(e);
}
}
public Location getLocation() {
return location;
}
public long getDuration() {
return duration;
}
}
}
| src/main/java/raven/toast/Notifications.java | DJ-Raven-swing-toast-notifications-4c7978a | [
{
"filename": "src/main/java/raven/toast/util/NotificationHolder.java",
"retrieved_chunk": " }\n public void 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": 53.611384615269195
},
{
"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": 29.501878104078916
},
{
"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": 22.18794931554541
},
{
"filename": "src/main/java/raven/toast/ui/ToastPanelUI.java",
"retrieved_chunk": " minimumWidth = FlatUIUtils.getUIInt(prefix + \".minimumWidth\", 50);\n maximumWidth = FlatUIUtils.getUIInt(prefix + \".maximumWidth\", -1);\n arc = FlatUIUtils.getUIInt(prefix + \".arc\", 20);\n outlineWidth = FlatUIUtils.getUIInt(prefix + \".outlineWidth\", 0);\n outlineColor = FlatUIUtils.getUIColor(prefix + \".outlineColor\", \"Component.focusColor\");\n margin = UIUtils.getInsets(prefix + \".margin\", new Insets(8, 8, 8, 8));\n showCloseButton = FlatUIUtils.getUIBoolean(prefix + \".showCloseButton\", true);\n closeIconColor = FlatUIUtils.getUIColor(prefix + \".closeIconColor\", new Color(150, 150, 150));\n closeButtonIcon = UIUtils.getIcon(prefix + \".closeIcon\", UIUtils.createIcon(\"raven/toast/svg/close.svg\", closeIconColor, 0.75f));\n useEffect = FlatUIUtils.getUIBoolean(prefix + \".useEffect\", true);",
"score": 15.937888756103627
},
{
"filename": "src/test/java/raven/demo/Test.java",
"retrieved_chunk": " } else {\n return Notifications.Location.BOTTOM_RIGHT;\n }\n }\n private String getRandomText() {\n Random ran = new Random();\n int a = ran.nextInt(5);\n if (a == 0) {\n return \"Toast Notifications notify the user of a system occurrence\";\n } else if (a == 1) {",
"score": 15.719763623051389
}
] | 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/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": 28.41019311578586
},
{
"filename": "src/main/java/primitives/Rectangle.java",
"retrieved_chunk": "package primitives;\nimport domain.Point;\npublic class Rectangle extends Quadrilateral {\n public Rectangle(Point vertex1, Point vertex2) {\n super(\n vertex1, //0, 0\n new Point(vertex1.getX(), vertex2.getY()), //0, 10\n vertex2, //20, 10\n new Point(vertex2.getX(), vertex1.getY())// 20, 0\n );",
"score": 27.740021345194307
},
{
"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": 26.92246675588597
},
{
"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": 26.086342044199295
},
{
"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": 21.38350339835546
}
] | java | lowerLeft.getX(), lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints(); |
package canvas;
import domain.Point;
import domain.Shape;
import org.apache.commons.lang3.StringUtils;
import java.util.Arrays;
public class TextCanvas implements Canvas {
private final Pixel[][] pixels;
private final int height;
private final int width;
private String SET = " 0 ";
private String UNSET = " · ";
public TextCanvas(int width, int height) {
this.width = width;
this.height = height;
this.pixels = new Pixel[height][width];
clean();
}
public void clean() {
for (Pixel[] row : pixels) {
Arrays.fill(row, new Pixel(false));
}
}
public void draw(Shape shape) {
for (Point point : shape.getPoints()) {
set(point.getX(), point.getY());
}
}
private void set(int x, int y) {
if (x >= 0 && y >= 0 && x < width && y < height) {
pixels[y][x] = new Pixel(true);
}
}
@Override
public void show() {
for (int y = height - 1; y >= 0; y--) {
if (y % 5 == 0) {
System.out.print(String.format("%1$3s", y));
} else {
System.out.print(" ");
}
for (int x = 0; x < width; x++) {
if (pixels[ | y][x].isSet()) { |
System.out.print(SET);
} else {
System.out.print(UNSET);
}
}
System.out.println();
}
System.out.print(" ");
for (int x = 0; x < width; x++) {
if (x % 5 == 0) {
System.out.print(StringUtils.rightPad(String.valueOf(x), 3));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
| src/main/java/canvas/TextCanvas.java | dmitriyvolk-redrover-draw-b9b5e7d | [
{
"filename": "src/main/java/canvas/SwingCanvas.java",
"retrieved_chunk": " int y = point.getY();\n if (x >= 0 && y >= 0 && x < width && y < height) {\n allPoints.add(new Point(x, height - 1 - y));\n }\n }\n }\n public void show() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {",
"score": 56.39350936908731
},
{
"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": 36.55244452117714
},
{
"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": 34.69443353952953
},
{
"filename": "src/main/java/transformations/MoveBy.java",
"retrieved_chunk": "package transformations;\nimport domain.Point;\npublic class MoveBy extends PerPointTransformation {\n private final int x;\n private final int y;\n public MoveBy(int x, int y) {\n this.x = x;\n this.y = y;\n }\n @Override",
"score": 33.53299118165981
},
{
"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": 19.890812997273372
}
] | 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": 24.23032304360118
},
{
"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": 20.526056480238413
},
{
"filename": "src/main/java/canvas/Canvas.java",
"retrieved_chunk": "package canvas;\nimport domain.Shape;\npublic interface Canvas {\n void draw(Shape shape);\n void show();\n}",
"score": 17.355155611871417
},
{
"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": 13.921275332386976
},
{
"filename": "src/main/java/domain/CompositeShape.java",
"retrieved_chunk": "package domain;\nimport java.util.ArrayList;\nimport java.util.List;\npublic abstract class CompositeShape implements Shape {\n protected abstract List<Shape> getShapes();\n @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n for (Shape shape: getShapes()) {\n result.addAll(shape.getPoints());",
"score": 13.171207649603813
}
] | 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": 20.042554065878495
},
{
"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": 12.296025055333494
},
{
"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": 10.507937732597386
},
{
"filename": "src/main/java/primitives/Line.java",
"retrieved_chunk": " result.add(point);\n }\n result.add(to);\n return result;\n }\n}",
"score": 9.210814174360562
},
{
"filename": "src/main/java/primitives/Line.java",
"retrieved_chunk": " int rise = this.to.getY() - this.from.getY();\n int run = this.to.getX() - this.from.getX();\n int iterations = Math.max(Math.abs(rise), Math.abs(run));\n float stepX = run * 1.0f / iterations;\n float stepY = rise * 1f / iterations;\n for (int i = 0; i < iterations; i++) {\n Point point = new Point(\n this.from.getX() + Math.round(i * stepX),\n this.from.getY() + Math.round(i * stepY)\n );",
"score": 8.846053327218682
}
] | java | getX() * factor, point.getY() * factor + 50, factor, factor); |
package canvas;
import domain.Point;
import domain.Shape;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class SwingCanvas implements Canvas {
private final int width;
private final int height;
private final int factor;
public SwingCanvas(int width, int height, int factor) {
this.width = width;
this.height = height;
this.factor = factor;
}
private List<Point> allPoints = new ArrayList<>();
public void draw(Shape shape) {
for (Point point: shape.getPoints()) {
int x = point.getX();
int y = point.getY();
if (x >= 0 && y >= 0 && x < width && y < height) {
allPoints.add(new Point(x, height - 1 - y));
}
}
}
public void show() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Frame().setVisible(true);
}
});
}
class Frame extends JFrame {
Frame() {
super("Graphic Canvas");
setSize(factor * width + 2*factor, factor * height + 50);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
@Override
public void paint(Graphics g) {
super.paint(g);
for (Point point : allPoints) {
g | .drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor); |
}
}
}
}
| src/main/java/canvas/SwingCanvas.java | dmitriyvolk-redrover-draw-b9b5e7d | [
{
"filename": "src/main/java/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": 20.042554065878495
},
{
"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": 12.296025055333494
},
{
"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": 10.507937732597386
},
{
"filename": "src/main/java/primitives/Line.java",
"retrieved_chunk": " result.add(point);\n }\n result.add(to);\n return result;\n }\n}",
"score": 9.210814174360562
},
{
"filename": "src/main/java/primitives/Line.java",
"retrieved_chunk": " int rise = this.to.getY() - this.from.getY();\n int run = this.to.getX() - this.from.getX();\n int iterations = Math.max(Math.abs(rise), Math.abs(run));\n float stepX = run * 1.0f / iterations;\n float stepY = rise * 1f / iterations;\n for (int i = 0; i < iterations; i++) {\n Point point = new Point(\n this.from.getX() + Math.round(i * stepX),\n this.from.getY() + Math.round(i * stepY)\n );",
"score": 8.846053327218682
}
] | java | .drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor); |
package com.easyhome.common.feign;
import com.easyhome.common.utils.GrayscaleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* 打印请求头灰度参数拦截器
* @author wangshufeng
*/
@Slf4j
public class TransmitHeaderPrintLogHanlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String printLogFlg = request.getHeader(GrayscaleConstant.PRINT_HEADER_LOG_KEY);
if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) {
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.getHeader(name);
log.info("接收到的请求头信息:{}={}", name, value);
}
}
}
Map<String,String> param=new HashMap<>(8);
//获取所有灰度参数值设置到ThreadLocal,以便传值
for (GrayHeaderParam item:GrayHeaderParam.values()) {
String hParam = request.getHeader(item.getValue());
if(!StringUtils.isEmpty(hParam)){
| param.put(item.getValue(), hParam); |
}
}
GrayParamHolder.putValues(param);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
//清除灰度ThreadLocal
GrayParamHolder.clearValue();
}
}
| src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java | EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a | [
{
"filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java",
"retrieved_chunk": " 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": 29.573184714522892
},
{
"filename": "src/main/java/com/easyhome/common/feign/GrayHeaderParam.java",
"retrieved_chunk": " DW_LANG(GrayscaleConstant.DW_LANG),\n DEVICE_OS(GrayscaleConstant.DEVICE_OS);\n private String value;\n GrayHeaderParam(String value) {\n this.value = value;\n }\n public String getValue() {\n return value;\n }\n}",
"score": 21.729744413718
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " this.key = key;\n this.value = value;\n }\n public static String getValue(Integer key) {\n for (ListenerStateEnum value : values()) {\n if (value.getKey().equals(key)) {\n return value.getValue();\n }\n }\n return null;",
"score": 20.861948752792618
},
{
"filename": "src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java",
"retrieved_chunk": " for(Instance item:instances){\n Map<String, String> metadata = item.getMetadata();\n if (metadata.isEmpty() || !GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) {\n prodInstance.add(item);\n }\n if (isGrayRequest) {\n if (!metadata.isEmpty() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) {\n if(Objects.equals(grayGroup,metadata.get(GrayscaleConstant.GRAY_GROUP))){\n grayInstance.add(item);\n }",
"score": 20.055469166713316
},
{
"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": 19.26115883753402
}
] | java | param.put(item.getValue(), hParam); |
/*
* 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": 157.25174429097123
},
{
"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": 90.71097875868038
},
{
"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": 86.50011169480736
},
{
"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": 77.93917833590233
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " if (this.interceptors != null && this.interceptors.size() > 0) {\n for (int i = this.interceptors.size() - 1; i >= 0; i--) {\n IInterceptor interceptor = this.interceptors.get(i);\n if (interceptor.supportMethod(methodInfo)) {\n result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);\n }\n }\n }\n log.debug(\"finish result==>{}\", result);\n return result;",
"score": 74.06773597149828
}
] | 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/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": 31.37148707290006
},
{
"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": 21.316370507671284
},
{
"filename": "src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java",
"retrieved_chunk": " for(Instance item:instances){\n Map<String, String> metadata = item.getMetadata();\n if (metadata.isEmpty() || !GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) {\n prodInstance.add(item);\n }\n if (isGrayRequest) {\n if (!metadata.isEmpty() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) {\n if(Objects.equals(grayGroup,metadata.get(GrayscaleConstant.GRAY_GROUP))){\n grayInstance.add(item);\n }",
"score": 20.055469166713316
},
{
"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": 18.213395712482246
},
{
"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": 17.680886959765918
}
] | java | GrayParamHolder.putValues(param); |
/*
* 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 * @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": 33.120492019709474
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/JsqlParserSupport.java",
"retrieved_chunk": " if (i > 0) {\n sb.append(StringPool.SEMICOLON);\n }\n sb.append(this.processParser(statement, i, sql, obj));\n i++;\n }\n return sb.toString();\n } catch (JSQLParserException e) {\n throw ExceptionUtils.mpe(\"Failed to process, Error SQL: %s\", e.getCause(), sql);\n }",
"score": 27.87269589453936
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/JsqlParserSupport.java",
"retrieved_chunk": " throw ExceptionUtils.mpe(\"Failed to process, Error SQL: %s\", e.getCause(), sql);\n }\n }\n public String parserMulti(String sql, Object obj) {\n try {\n // fixed github pull/295\n StringBuilder sb = new StringBuilder();\n Statements statements = CCJSqlParserUtil.parseStatements(sql);\n int i = 0;\n for (Statement statement : statements.getStatements()) {",
"score": 23.850536144961282
},
{
"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": 20.51409093046112
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/domain/TestUser.java",
"retrieved_chunk": " private String name;\n /**\n *\n */\n private String tenantId;\n @TableField(exist = false)\n private static final long serialVersionUID = 1L;\n}",
"score": 19.731707809980556
}
] | java | ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId"); |
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": " return topicGrayName(topicName);\n } else {\n return topicName;\n }\n }\n /**\n * 是否为灰度请求\n * @return Boolean\n */\n public static Boolean isGrayRequest(){",
"score": 21.235348254389038
},
{
"filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java",
"retrieved_chunk": " }\n return topicName.concat(GrayscaleConstant.GRAY_TOPIC_SUFFIX);\n }\n /**\n * 自动主题名称拼接灰度后缀\n * @param topicName\n * @return String\n */\n public static String autoTopicGrayName(String topicName) {\n if (isGrayRequest()) {",
"score": 21.03129625845888
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " this.key = key;\n this.value = value;\n }\n public static String getValue(Integer key) {\n for (ListenerStateEnum value : values()) {\n if (value.getKey().equals(key)) {\n return value.getValue();\n }\n }\n return null;",
"score": 17.1781267029911
},
{
"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": 16.46998726008025
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " TOGETHER(2, \"同时监听生产和灰度环境队列\");\n /**\n * key\n */\n private Integer key;\n /**\n * value\n */\n private String value;\n ListenerStateEnum(Integer key, String value) {",
"score": 15.483083511617757
}
] | 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": 23.127693773061907
},
{
"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": 18.5227730686422
},
{
"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": 18.50963532752847
},
{
"filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java",
"retrieved_chunk": " * feign传递请求头信息拦截器\n *\n * @author wangshufeng\n */\n@Slf4j\n@Configuration\npublic class FeignTransmitHeadersRequestInterceptor implements RequestInterceptor {\n @Override\n public void apply(RequestTemplate requestTemplate) {\n Map<String,String> attributes=GrayParamHolder.getGrayMap();",
"score": 15.053846296543082
},
{
"filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java",
"retrieved_chunk": "public class GrayUtil {\n /**\n * 主题名称拼接灰度后缀\n *\n * @param topicName\n * @return String\n */\n public static String topicGrayName(String topicName) {\n if (StringUtils.isEmpty(topicName)) {\n throw new NullPointerException(\"topicName为null\");",
"score": 11.789830586030018
}
] | java | if(GrayUtil.isGrayPod()){ |
package com.easyhome.common.nacos;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.easyhome.common.event.GrayEventChangeEvent;
import com.easyhome.common.rocketmq.ListenerStateEnum;
import com.easyhome.common.utils.GrayUtil;
import com.easyhome.common.utils.GrayscaleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
/**
* nacos自定义监听实现
*
* @author wangshufeng
*/
@Slf4j
@Component
public class NacosEventListener implements EventListener {
@Resource
private ApplicationEventPublisher publisher;
@Override
public void onEvent(Event event) {
if (event instanceof NamingEvent) {
this.mqInit(((NamingEvent) event).getInstances());
}
}
/**
* 当前的mq监听状态
*/
private static ListenerStateEnum listenerMqState;
public synchronized void mqInit(List<Instance> instances) {
ListenerStateEnum newState;
//当前实例是灰度实例
if (GrayUtil.isGrayPod()) {
newState = ListenerStateEnum.GRAYSCALE;
} else {
//判断当前服务有灰度实例
if (this.isHaveGray(instances)) {
newState = ListenerStateEnum.PRODUCTION;
} else {
newState = ListenerStateEnum.TOGETHER;
}
}
log.info("当前实例是否为灰度环境:{}", GrayUtil.isGrayPod());
log. | info("当前实例监听mq队列的状态:{ | }", newState.getValue());
//防止重复初始化监听mq队列信息
if (!newState.equals(listenerMqState)) {
listenerMqState = newState;
publisher.publishEvent(new GrayEventChangeEvent(listenerMqState));
}
}
/**
* 是否有灰度实例
*
* @return
*/
private boolean isHaveGray(List<Instance> instances) {
if (!CollectionUtils.isEmpty(instances)) {
for (Instance instance : instances) {
if (GrayscaleConstant.STR_BOOLEAN_TRUE.equals(instance.getMetadata().get(GrayscaleConstant.POD_GRAY))) {
return true;
}
}
}
return false;
}
}
| src/main/java/com/easyhome/common/nacos/NacosEventListener.java | EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a | [
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " }\n }\n @Override\n public void onApplicationEvent(GrayEventChangeEvent event) {\n ListenerStateEnum listenerStateEnum = (ListenerStateEnum) event.getSource();\n log.info(this.getClass().getName() + \"灰度环境变更:\" + listenerStateEnum.getValue());\n currentState = listenerStateEnum;\n if (ListenerStateEnum.PRODUCTION.equals(listenerStateEnum)) {\n initConsumerProduction();\n for (SubscriptionData item : subscribes) {",
"score": 21.168613667752872
},
{
"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": 14.334550712157897
},
{
"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": 13.974833475062795
},
{
"filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java",
"retrieved_chunk": " }**/\n String printLogFlg = attributes.get(GrayscaleConstant.PRINT_HEADER_LOG_KEY);\n if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) {\n requestTemplate.header(GrayscaleConstant.PRINT_HEADER_LOG_KEY, printLogFlg);\n log.info(\"feign传递请求头信息:{}={}\", GrayscaleConstant.HEADER_KEY, version);\n }\n }\n }\n}",
"score": 12.041953242146548
},
{
"filename": "src/main/java/com/easyhome/common/nacos/NacosListenerConfig.java",
"retrieved_chunk": " @PostConstruct\n public void subscribe() {\n try {\n NamingService namingService = NamingFactory.createNamingService(nacosDiscoveryProperties.getServerAddr());\n namingService.subscribe(nacosDiscoveryProperties.getService(),nacosDiscoveryProperties.getGroup(), nacosEventListener);\n log.info(\"配置nacos自定义监听完成\");\n } catch (NacosException e) {\n log.error(\"配置nacos自定义监听错误\", e);\n }\n }",
"score": 11.014636417442892
}
] | java | info("当前实例监听mq队列的状态:{ |
package com.easyhome.common.nacos.ribbon;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.ExtendBalancer;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.easyhome.common.utils.GrayUtil;
import com.easyhome.common.utils.GrayscaleConstant;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* nacos自定义负载策略
*
* @author wangshufeng
*/
@Slf4j
public class NacosRule extends AbstractLoadBalancerRule {
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Override
public Server choose(Object key) {
try {
String clusterName = this.nacosDiscoveryProperties.getClusterName();
DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
String name = loadBalancer.getName();
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
List<Instance> instances = namingService.selectInstances(name, true);
instances = this.getGrayFilterInstances(instances, key);
if (CollectionUtils.isEmpty(instances)) {
log.warn("no instance in service {}", name);
return null;
}
List<Instance> instancesToChoose = instances;
if (StringUtils.isNotBlank(clusterName)) {
List<Instance> sameClusterInstances = instances.stream()
.filter(instance -> Objects.equals(clusterName, instance.getClusterName()))
.collect(Collectors.toList());
if (!CollectionUtils.isEmpty(sameClusterInstances)) {
instancesToChoose = sameClusterInstances;
} else {
log.warn(
"A cross-cluster call occurs,name = {}, clusterName = {}, instance = {}",
name, clusterName, instances);
}
}
Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToChoose);
return new NacosServer(instance);
} catch (Exception e) {
log.warn("NacosRule error", e);
return null;
}
}
/**
* 根据当前请求是否为灰度过滤服务实例列表
*
* @param instances
* @return List<Instance>
*/
private List<Instance> getGrayFilterInstances(List<Instance> instances, Object key) {
if (CollectionUtils.isEmpty(instances)) {
return instances;
} else {
//是否灰度请求
Boolean isGrayRequest;
String grayGroup=GrayscaleConstant.HEADER_VALUE;
//兼容gateway传值方式,gateway是nio是通过key来做负载实例识别的
if (Objects.nonNull(key) && !GrayscaleConstant.DEFAULT.equals(key)) {
isGrayRequest = true;
if(isGrayRequest){
grayGroup=(String)key;
}
} else {
isGrayRequest = GrayUtil.isGrayRequest();
if(isGrayRequest){
grayGroup | =GrayUtil.requestGroup(); |
}
}
List<Instance> prodInstance=new ArrayList<>();
List<Instance> grayInstance=new ArrayList<>();
for(Instance item:instances){
Map<String, String> metadata = item.getMetadata();
if (metadata.isEmpty() || !GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) {
prodInstance.add(item);
}
if (isGrayRequest) {
if (!metadata.isEmpty() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) {
if(Objects.equals(grayGroup,metadata.get(GrayscaleConstant.GRAY_GROUP))){
grayInstance.add(item);
}
}
}
}
if(!isGrayRequest||CollectionUtils.isEmpty(grayInstance)){
return prodInstance;
}
return grayInstance;
}
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}
| src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java | EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a | [
{
"filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java",
"retrieved_chunk": " return topicGrayName(topicName);\n } else {\n return topicName;\n }\n }\n /**\n * 是否为灰度请求\n * @return Boolean\n */\n public static Boolean isGrayRequest(){",
"score": 25.852251404965912
},
{
"filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java",
"retrieved_chunk": " }\n return topicName.concat(GrayscaleConstant.GRAY_TOPIC_SUFFIX);\n }\n /**\n * 自动主题名称拼接灰度后缀\n * @param topicName\n * @return String\n */\n public static String autoTopicGrayName(String topicName) {\n if (isGrayRequest()) {",
"score": 23.75007405363081
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " this.key = key;\n this.value = value;\n }\n public static String getValue(Integer key) {\n for (ListenerStateEnum value : values()) {\n if (value.getKey().equals(key)) {\n return value.getValue();\n }\n }\n return null;",
"score": 17.083819558226114
},
{
"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": 16.041217191581737
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " TOGETHER(2, \"同时监听生产和灰度环境队列\");\n /**\n * key\n */\n private Integer key;\n /**\n * value\n */\n private String value;\n ListenerStateEnum(Integer key, String value) {",
"score": 14.809490041130744
}
] | java | =GrayUtil.requestGroup(); |
package com.easyhome.common.utils;
import com.easyhome.common.feign.GrayParamHolder;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.Objects;
/**
* 灰度发布工具类
*
* @author wangshufeng
*/
public class GrayUtil {
/**
* 主题名称拼接灰度后缀
*
* @param topicName
* @return String
*/
public static String topicGrayName(String topicName) {
if (StringUtils.isEmpty(topicName)) {
throw new NullPointerException("topicName为null");
}
return topicName.concat(GrayscaleConstant.GRAY_TOPIC_SUFFIX);
}
/**
* 自动主题名称拼接灰度后缀
* @param topicName
* @return String
*/
public static String autoTopicGrayName(String topicName) {
if (isGrayRequest()) {
return topicGrayName(topicName);
} else {
return topicName;
}
}
/**
* 是否为灰度请求
* @return Boolean
*/
public static Boolean isGrayRequest(){
Map<String, | String> attributes= GrayParamHolder.getGrayMap(); |
String releaseVersion=attributes.get(GrayscaleConstant.HEADER_KEY);
if (Objects.nonNull(releaseVersion)&&!"".equals(releaseVersion)) {
return true;
}
return false;
}
/**
* 当前环境是否为灰度环境
*
* @return boolean
*/
public static Boolean isGrayPod() {
String grayFlg = System.getProperty(GrayscaleConstant.POD_GRAY);
if (GrayscaleConstant.STR_BOOLEAN_TRUE.equals(grayFlg)) {
return true;
} else {
return false;
}
}
/**
* 获取运行实例的灰度分组
* @return
*/
public static String podGroup() {
String groupFlag = System.getProperty(GrayscaleConstant.GRAY_GROUP);
if (groupFlag!=null&&!"".equals(groupFlag)) {
return groupFlag;
} else {
return GrayscaleConstant.HEADER_VALUE;
}
}
/**
* 获取当前请求分组
* @return
*/
public static String requestGroup(){
Map<String,String> attributes= GrayParamHolder.getGrayMap();
String groupFlag =attributes.get(GrayscaleConstant.HEADER_KEY);
if (groupFlag!=null&&!"".equals(groupFlag)) {
return groupFlag;
} else {
return GrayscaleConstant.HEADER_VALUE;
}
}
}
| src/main/java/com/easyhome/common/utils/GrayUtil.java | EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a | [
{
"filename": "src/main/java/com/easyhome/common/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": 16.199888809744664
},
{
"filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java",
"retrieved_chunk": " * feign传递请求头信息拦截器\n *\n * @author wangshufeng\n */\n@Slf4j\n@Configuration\npublic class FeignTransmitHeadersRequestInterceptor implements RequestInterceptor {\n @Override\n public void apply(RequestTemplate requestTemplate) {\n Map<String,String> attributes=GrayParamHolder.getGrayMap();",
"score": 14.40165298855521
},
{
"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": 12.94033667808197
},
{
"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": 11.05519244015456
},
{
"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": 8.587764735146528
}
] | 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": 17.97398012088531
},
{
"filename": "src/main/java/com/easyhome/common/nacos/NacosEventListener.java",
"retrieved_chunk": "@Slf4j\n@Component\npublic class NacosEventListener implements EventListener {\n @Resource\n private ApplicationEventPublisher publisher;\n @Override\n public void onEvent(Event event) {\n if (event instanceof NamingEvent) {\n this.mqInit(((NamingEvent) event).getInstances());\n }",
"score": 16.798745837147077
},
{
"filename": "src/main/java/com/easyhome/common/event/GrayEventChangeEvent.java",
"retrieved_chunk": " *\n * @param source the object on which the event initially occurred or with\n * which the event is associated (never {@code null})\n */\n public GrayEventChangeEvent(ListenerStateEnum source) {\n super(source);\n }\n}",
"score": 16.404976236810953
},
{
"filename": "src/main/java/com/easyhome/common/event/GrayEventChangeEvent.java",
"retrieved_chunk": "package com.easyhome.common.event;\nimport com.easyhome.common.rocketmq.ListenerStateEnum;\nimport org.springframework.context.ApplicationEvent;\n/**\n * 灰度环境变更事件\n * @author wangshufeng\n */\npublic class GrayEventChangeEvent extends ApplicationEvent {\n /**\n * Create a new {@code ApplicationEvent}.",
"score": 13.336444421697276
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " this.key = key;\n this.value = value;\n }\n public static String getValue(Integer key) {\n for (ListenerStateEnum value : values()) {\n if (value.getKey().equals(key)) {\n return value.getValue();\n }\n }\n return null;",
"score": 12.104580071631085
}
] | java | getName() + "灰度环境变更:" + listenerStateEnum.getValue()); |
package com.easyhome.common.feign;
import com.easyhome.common.utils.GrayscaleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/**
* 打印请求头灰度参数拦截器
* @author wangshufeng
*/
@Slf4j
public class TransmitHeaderPrintLogHanlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String printLogFlg = request.getHeader(GrayscaleConstant.PRINT_HEADER_LOG_KEY);
if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) {
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = request.getHeader(name);
log.info("接收到的请求头信息:{}={}", name, value);
}
}
}
Map<String,String> param=new HashMap<>(8);
//获取所有灰度参数值设置到ThreadLocal,以便传值
for (GrayHeaderParam item:GrayHeaderParam.values()) {
String hParam = request. | getHeader(item.getValue()); |
if(!StringUtils.isEmpty(hParam)){
param.put(item.getValue(), hParam);
}
}
GrayParamHolder.putValues(param);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
//清除灰度ThreadLocal
GrayParamHolder.clearValue();
}
}
| src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java | EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a | [
{
"filename": "src/main/java/com/easyhome/common/feign/GrayHeaderParam.java",
"retrieved_chunk": " DW_LANG(GrayscaleConstant.DW_LANG),\n DEVICE_OS(GrayscaleConstant.DEVICE_OS);\n private String value;\n GrayHeaderParam(String value) {\n this.value = value;\n }\n public String getValue() {\n return value;\n }\n}",
"score": 24.600724803923303
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " this.key = key;\n this.value = value;\n }\n public static String getValue(Integer key) {\n for (ListenerStateEnum value : values()) {\n if (value.getKey().equals(key)) {\n return value.getValue();\n }\n }\n return null;",
"score": 22.066810388539952
},
{
"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": 19.580583867033468
},
{
"filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java",
"retrieved_chunk": " public static void putValue(String key, String value) {\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 paramMap.put(key, value);\n }\n /**\n * 设置单多个参数",
"score": 15.361312410774381
},
{
"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": 14.084710930226432
}
] | java | getHeader(item.getValue()); |
package com.easyhome.common.nacos;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.easyhome.common.event.GrayEventChangeEvent;
import com.easyhome.common.rocketmq.ListenerStateEnum;
import com.easyhome.common.utils.GrayUtil;
import com.easyhome.common.utils.GrayscaleConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.List;
/**
* nacos自定义监听实现
*
* @author wangshufeng
*/
@Slf4j
@Component
public class NacosEventListener implements EventListener {
@Resource
private ApplicationEventPublisher publisher;
@Override
public void onEvent(Event event) {
if (event instanceof NamingEvent) {
this.mqInit(((NamingEvent) event).getInstances());
}
}
/**
* 当前的mq监听状态
*/
private static ListenerStateEnum listenerMqState;
public synchronized void mqInit(List<Instance> instances) {
ListenerStateEnum newState;
//当前实例是灰度实例
if (GrayUtil.isGrayPod()) {
newState = ListenerStateEnum.GRAYSCALE;
} else {
//判断当前服务有灰度实例
if (this.isHaveGray(instances)) {
newState = ListenerStateEnum.PRODUCTION;
} else {
newState = ListenerStateEnum.TOGETHER;
}
}
log.info | ("当前实例是否为灰度环境:{ | }", GrayUtil.isGrayPod());
log.info("当前实例监听mq队列的状态:{}", newState.getValue());
//防止重复初始化监听mq队列信息
if (!newState.equals(listenerMqState)) {
listenerMqState = newState;
publisher.publishEvent(new GrayEventChangeEvent(listenerMqState));
}
}
/**
* 是否有灰度实例
*
* @return
*/
private boolean isHaveGray(List<Instance> instances) {
if (!CollectionUtils.isEmpty(instances)) {
for (Instance instance : instances) {
if (GrayscaleConstant.STR_BOOLEAN_TRUE.equals(instance.getMetadata().get(GrayscaleConstant.POD_GRAY))) {
return true;
}
}
}
return false;
}
}
| src/main/java/com/easyhome/common/nacos/NacosEventListener.java | EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a | [
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " }\n }\n @Override\n public void onApplicationEvent(GrayEventChangeEvent event) {\n ListenerStateEnum listenerStateEnum = (ListenerStateEnum) event.getSource();\n log.info(this.getClass().getName() + \"灰度环境变更:\" + listenerStateEnum.getValue());\n currentState = listenerStateEnum;\n if (ListenerStateEnum.PRODUCTION.equals(listenerStateEnum)) {\n initConsumerProduction();\n for (SubscriptionData item : subscribes) {",
"score": 16.810651089525678
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java",
"retrieved_chunk": " TOGETHER(2, \"同时监听生产和灰度环境队列\");\n /**\n * key\n */\n private Integer key;\n /**\n * value\n */\n private String value;\n ListenerStateEnum(Integer key, String value) {",
"score": 9.785617965644509
},
{
"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": 9.17346719554148
},
{
"filename": "src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java",
"retrieved_chunk": " } else {\n log.warn(\n \"A cross-cluster call occurs,name = {}, clusterName = {}, instance = {}\",\n name, clusterName, instances);\n }\n }\n Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToChoose);\n return new NacosServer(instance);\n } catch (Exception e) {\n log.warn(\"NacosRule error\", e);",
"score": 9.143994686663678
},
{
"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 }\n shutdownConsumerGray();\n }\n if (ListenerStateEnum.TOGETHER.equals(listenerStateEnum)) {\n initConsumerProduction();\n initConsumerGray();\n for (SubscriptionData item : subscribes) {",
"score": 8.961588103112256
}
] | 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/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": 56.078717680672966
},
{
"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": 53.66743629374863
},
{
"filename": "src/main/java/pro/edgematrix/crypto/type/RtcMsg.java",
"retrieved_chunk": " String to;\n public RtcMsg(String subject, String application, String content, String to) {\n this.subject = subject;\n this.application = application;\n this.content = content;\n this.to = to;\n this.type = RtcMsgType.SubscribeMsg;\n }\n @Override\n public List<RlpType> asRlpValues(Sign.SignatureData signatureData) {",
"score": 50.71129031300048
},
{
"filename": "src/main/java/pro/edgematrix/crypto/type/RtcMsg.java",
"retrieved_chunk": "/**\n * RtcMsg class used for signing RtcMsg locally.<br>\n * For the specification, refer to <a href=\"http://www.edgematrix.pro/api/paper.pdf\">yellow\n * paper</a>.\n */\npublic class RtcMsg implements IRtcMsg {\n private RtcMsgType type;\n String subject;\n String application;\n String content;",
"score": 45.16385711605384
},
{
"filename": "src/main/java/pro/edgematrix/crypto/RawTelegram.java",
"retrieved_chunk": " * Transaction class used for signing transactions locally.<br>\n * For the specification, refer to p4 of the <a href=\"http://gavwood.com/paper.pdf\">yellow\n * paper</a>.\n */\npublic class RawTelegram {\n private final ITransaction transaction;\n protected RawTelegram(final ITransaction transaction) {\n this.transaction = transaction;\n }\n protected RawTelegram(",
"score": 43.39513698160899
}
] | 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/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": 85.10459430315161
},
{
"filename": "src/main/java/pro/edgematrix/crypto/type/Telegram.java",
"retrieved_chunk": " public static LegacyTransaction createTransaction(\n BigInteger nonce,\n BigInteger gasPrice,\n BigInteger gasLimit,\n String to,\n BigInteger value,\n String data) {\n return new LegacyTransaction(nonce, gasPrice, gasLimit, to, value, data);\n }\n @Override",
"score": 83.12094090716928
},
{
"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": 81.34106322271522
},
{
"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": 80.59375857053259
},
{
"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": 72.1729870331225
}
] | java | rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, contractAddress, value, data); |
package ru.dzen.kafka.connect.ytsaurus.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kafka.connect.header.Header;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.sink.SinkRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.dzen.kafka.connect.ytsaurus.common.BaseTableWriterConfig.AuthType;
import ru.dzen.kafka.connect.ytsaurus.common.BaseTableWriterConfig.OutputTableSchemaType;
import tech.ytsaurus.client.ApiServiceTransaction;
import tech.ytsaurus.client.YTsaurusClient;
import tech.ytsaurus.client.YTsaurusClientConfig;
import tech.ytsaurus.client.request.StartTransaction;
import tech.ytsaurus.ysontree.YTree;
import tech.ytsaurus.ysontree.YTreeNode;
public abstract class BaseTableWriter {
protected static final ObjectMapper objectMapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(BaseTableWriter.class);
private static final JsonConverter JSON_CONVERTER;
static {
JSON_CONVERTER = new JsonConverter();
JSON_CONVERTER.configure(Collections.singletonMap("schemas.enable", "false"), false);
}
protected final YTsaurusClient client;
protected final BaseOffsetsManager offsetsManager;
protected final BaseTableWriterConfig config;
protected BaseTableWriter(BaseTableWriterConfig config, BaseOffsetsManager offsetsManager) {
this.config = config;
this.client = YTsaurusClient.builder()
.setConfig(YTsaurusClientConfig.builder()
.setTvmOnly(config.getAuthType().equals(AuthType.SERVICE_TICKET)).build())
.setCluster(config.getYtCluster()).setAuth(config.getYtClientAuth()).build();
this.offsetsManager = offsetsManager;
}
protected ApiServiceTransaction createTransaction() throws Exception {
return client.startTransaction(StartTransaction.master()).get();
}
public Map<TopicPartition, OffsetAndMetadata> getSafeToCommitOffsets(
Map<TopicPartition, OffsetAndMetadata> unsafeOffsets) throws Exception {
return offsetsManager.getPrevOffsets(createTransaction(), unsafeOffsets.keySet()).entrySet()
.stream()
.filter(entry -> unsafeOffsets.containsKey(entry.getKey()))
.map(entry -> {
var topicPartition = entry.getKey();
var prevOffset = entry.getValue();
var unsafeOffset = unsafeOffsets.get(topicPartition);
return unsafeOffset.offset() >= prevOffset.offset() ?
Map.entry(topicPartition, prevOffset) :
Map.entry(topicPartition, unsafeOffset);
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
protected Object convertRecordKey(SinkRecord record) throws Exception {
if (record.key() == null) {
return JsonNodeFactory.instance.nullNode();
}
if (record.key() instanceof String) {
return record.key();
}
byte[] jsonBytes = JSON_CONVERTER.fromConnectData(record.topic(), record.keySchema(),
record.key());
var jsonString = new String(jsonBytes, StandardCharsets.UTF_8);
JsonNode jsonNode = objectMapper.readTree(jsonString);
return jsonNode;
}
protected YTreeNode convertRecordKeyToNode(SinkRecord record) throws Exception {
var recordKey = convertRecordKey(record);
if (config.getKeyOutputFormat() == BaseTableWriterConfig.OutputFormat.STRING
&& !(recordKey instanceof String)) {
recordKey = objectMapper.writeValueAsString(recordKey);
} else if (!(recordKey instanceof String)) {
recordKey = Util.convertJsonNodeToYTree((JsonNode) recordKey);
}
return YTree.node(recordKey);
}
protected Object convertRecordValue(SinkRecord record) throws Exception {
if (record.value() == null) {
return JsonNodeFactory.instance.nullNode();
}
if (record.value() instanceof String) {
return record.value();
}
byte[] jsonBytes = JSON_CONVERTER.fromConnectData(record.topic(), record.valueSchema(),
record.value());
var jsonString = new String(jsonBytes, StandardCharsets.UTF_8);
JsonNode jsonNode = objectMapper.readTree(jsonString);
return jsonNode;
}
protected YTreeNode convertRecordValueToNode(SinkRecord record) throws Exception {
var recordValue = convertRecordValue(record);
if | (config.getValueOutputFormat() == BaseTableWriterConfig.OutputFormat.STRING
&& !(recordValue instanceof String)) { |
recordValue = objectMapper.writeValueAsString(recordValue);
} else if (!(recordValue instanceof String)) {
recordValue = Util.convertJsonNodeToYTree((JsonNode) recordValue);
}
return YTree.node(recordValue);
}
protected List<Map<String, YTreeNode>> recordsToRows(Collection<SinkRecord> records) {
var mapNodesToWrite = new ArrayList<Map<String, YTreeNode>>();
for (SinkRecord record : records) {
var headersBuilder = YTree.builder().beginList();
for (Header header : record.headers()) {
headersBuilder.value(
YTree.builder().beginList().value(header.key()).value(header.value().toString())
.buildList());
}
YTreeNode recordKeyNode;
try {
recordKeyNode = convertRecordKeyToNode(record);
} catch (Exception e) {
log.error("Exception in convertRecordKeyToNode:", e);
throw new DataException(e);
}
YTreeNode recordValueNode;
try {
recordValueNode = convertRecordValueToNode(record);
} catch (Exception e) {
log.error("Exception in convertRecordValueToNode:", e);
throw new DataException(e);
}
Map<String, YTreeNode> rowMap = new HashMap<>();
if (config.getOutputTableSchemaType().equals(OutputTableSchemaType.UNSTRUCTURED)) {
rowMap.put(UnstructuredTableSchema.EColumn.DATA.name, recordValueNode);
} else {
if (!recordValueNode.isMapNode()) {
throw new DataException("Record value is not a map: " + recordValueNode);
}
rowMap = recordValueNode.asMap();
}
rowMap.put(UnstructuredTableSchema.EColumn.KEY.name, recordKeyNode);
rowMap.put(UnstructuredTableSchema.EColumn.TOPIC.name, YTree.stringNode(record.topic()));
rowMap.put(UnstructuredTableSchema.EColumn.PARTITION.name,
YTree.unsignedLongNode(record.kafkaPartition()));
rowMap.put(UnstructuredTableSchema.EColumn.OFFSET.name,
YTree.unsignedLongNode(record.kafkaOffset()));
rowMap.put(UnstructuredTableSchema.EColumn.TIMESTAMP.name,
YTree.unsignedLongNode(System.currentTimeMillis()));
rowMap.put(UnstructuredTableSchema.EColumn.HEADERS.name, headersBuilder.buildList());
mapNodesToWrite.add(rowMap);
}
return mapNodesToWrite;
}
protected void writeRows(ApiServiceTransaction trx, Collection<SinkRecord> records)
throws Exception {
}
protected void writeRows(ApiServiceTransaction trx, Collection<SinkRecord> records,
Set<TopicPartition> topicPartitions)
throws Exception {
writeRows(trx, records);
}
public void writeBatch(Collection<SinkRecord> records) throws Exception {
var startTime = System.currentTimeMillis();
try (var trx = createTransaction()) {
var maxOffsets = offsetsManager.getMaxOffsets(records);
offsetsManager.lockPartitions(trx, maxOffsets.keySet());
var prevOffsets = offsetsManager.getPrevOffsets(trx,
maxOffsets.keySet());
var filteredRecords = offsetsManager.filterRecords(records, prevOffsets);
if (filteredRecords.isEmpty()) {
trx.close();
} else {
writeRows(trx, filteredRecords, maxOffsets.keySet());
offsetsManager.writeOffsets(trx, maxOffsets);
trx.commit().get();
}
var elapsed = Duration.ofMillis(System.currentTimeMillis() - startTime);
log.info("Done processing batch in {}: {} total, {} written, {} skipped",
Util.toHumanReadableDuration(elapsed), records.size(), filteredRecords.size(),
records.size() - filteredRecords.size());
} catch (Exception ex) {
throw ex;
}
}
public abstract TableWriterManager getManager();
}
| src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseTableWriter.java | Dzen-Platform-kafka-connect-ytsaurus-518a6b8 | [
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseOffsetsManager.java",
"retrieved_chunk": " public Collection<SinkRecord> filterRecords(Collection<SinkRecord> sinkRecords,\n Map<TopicPartition, OffsetAndMetadata> prevOffsetsMap) {\n return sinkRecords.stream()\n .filter(record -> {\n var topicPartition = new TopicPartition(record.topic(), record.kafkaPartition());\n return !prevOffsetsMap.containsKey(topicPartition)\n || prevOffsetsMap.get(topicPartition).offset() < record.kafkaOffset();\n })\n .collect(Collectors.toList());\n }",
"score": 32.518960825693696
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseOffsetsManager.java",
"retrieved_chunk": " public Map<TopicPartition, OffsetAndMetadata> getMaxOffsets(Collection<SinkRecord> sinkRecords) {\n return sinkRecords.stream()\n .collect(Collectors.toMap(\n record -> new TopicPartition(record.topic(), record.kafkaPartition()),\n record -> new OffsetAndMetadata(record.kafkaOffset()),\n (prev, curr) -> curr.offset() > prev.offset() ? curr : prev\n ));\n }\n public abstract Map<TopicPartition, OffsetAndMetadata> getPrevOffsets(ApiServiceTransaction trx,\n Set<TopicPartition> topicPartitions)",
"score": 29.436875621792893
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/Util.java",
"retrieved_chunk": " public static YTreeNode convertJsonNodeToYTree(JsonNode jsonNode) {\n if (jsonNode.isObject()) {\n var mapBuilder = YTree.mapBuilder();\n jsonNode.fields().forEachRemaining(entry -> {\n var key = entry.getKey();\n var valueNode = entry.getValue();\n mapBuilder.key(key).value(convertJsonNodeToYTree(valueNode));\n });\n return mapBuilder.buildMap();\n } else if (jsonNode.isArray()) {",
"score": 27.628778328749238
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/Util.java",
"retrieved_chunk": " var listBuilder = YTree.listBuilder();\n jsonNode.forEach(element -> listBuilder.value(convertJsonNodeToYTree(element)));\n return listBuilder.buildList();\n } else if (jsonNode.isTextual()) {\n return YTree.stringNode(jsonNode.asText());\n } else if (jsonNode.isNumber()) {\n if (jsonNode.isIntegralNumber()) {\n return YTree.longNode(jsonNode.asLong());\n } else {\n return YTree.doubleNode(jsonNode.asDouble());",
"score": 23.947902444213607
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/Util.java",
"retrieved_chunk": " }\n } else if (jsonNode.isBoolean()) {\n return YTree.booleanNode(jsonNode.asBoolean());\n } else if (jsonNode.isNull()) {\n return YTree.nullNode();\n } else {\n throw new UnsupportedOperationException(\n \"Unsupported JsonNode type: \" + jsonNode.getNodeType());\n }\n }",
"score": 23.781641497763903
}
] | java | (config.getValueOutputFormat() == BaseTableWriterConfig.OutputFormat.STRING
&& !(recordValue instanceof String)) { |
package ru.dzen.kafka.connect.ytsaurus.common;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigException;
import org.apache.kafka.common.utils.Utils;
import tech.ytsaurus.client.rpc.YTsaurusClientAuth;
import tech.ytsaurus.core.cypress.YPath;
import tech.ytsaurus.typeinfo.TiType;
public class BaseTableWriterConfig extends AbstractConfig {
public static final String AUTH_TYPE = "yt.connection.auth.type";
public static final String YT_USER = "yt.connection.user";
public static final String YT_TOKEN = "yt.connection.token";
public static final String SERVICE_TICKET_PROVIDER_URL = "yt.connection.service.ticket.provider.url";
public static final String YT_CLUSTER = "yt.connection.cluster";
public static final String OUTPUT_TYPE = "yt.sink.output.type";
public static final String OUTPUT_TABLE_SCHEMA_TYPE = "yt.sink.output.table.schema.type";
public static final String KEY_OUTPUT_FORMAT = "yt.sink.output.key.format";
public static final String VALUE_OUTPUT_FORMAT = "yt.sink.output.value.format";
public static final String OUTPUT_DIRECTORY = "yt.sink.output.directory";
public static final String OUTPUT_TTL = "yt.sink.output.ttl";
public static final String METADATA_DIRECTORY_NAME = "yt.sink.metadata.directory.name";
public static ConfigDef CONFIG_DEF = new ConfigDef()
.define(AUTH_TYPE, ConfigDef.Type.STRING, AuthType.TOKEN.name(),
ValidUpperString.in(AuthType.TOKEN.name(), AuthType.SERVICE_TICKET.name()),
ConfigDef.Importance.HIGH,
"Specifies the auth type: 'token' for token authentication or 'service_ticket' for service ticket authentication")
.define(YT_USER, ConfigDef.Type.STRING, null, ConfigDef.Importance.HIGH,
"Username for the YT API authentication")
.define(YT_TOKEN, ConfigDef.Type.PASSWORD, null, ConfigDef.Importance.HIGH,
"Access token for the YT API authentication")
.define(SERVICE_TICKET_PROVIDER_URL, ConfigDef.Type.PASSWORD, "", ConfigDef.Importance.HIGH,
"URL of the service ticket provider, required if 'yt.connection.auth.type' is 'SERVICE_TICKET'")
.define(YT_CLUSTER, ConfigDef.Type.STRING, ConfigDef.Importance.HIGH,
"Identifier of the YT cluster to connect to")
.define(OUTPUT_TYPE, ConfigDef.Type.STRING, OutputType.DYNAMIC_TABLE.name(),
ValidUpperString.in(OutputType.DYNAMIC_TABLE.name(),
OutputType.STATIC_TABLES.name()),
ConfigDef.Importance.HIGH,
"Specifies the output type: 'dynamic_table' for a sharded queue similar to Apache Kafka or 'static_tables' for separate time-based tables")
.define(KEY_OUTPUT_FORMAT, ConfigDef.Type.STRING, OutputFormat.ANY.name(),
ValidUpperString.in(OutputFormat.STRING.name(), OutputFormat.ANY.name()),
ConfigDef.Importance.HIGH,
"Determines the output format for keys: 'string' for plain string keys or 'any' for keys with no specific format")
.define(VALUE_OUTPUT_FORMAT, ConfigDef.Type.STRING, OutputFormat.ANY.name(),
ValidUpperString.in(OutputFormat.STRING.name(), OutputFormat.ANY.name()),
ConfigDef.Importance.HIGH,
"Determines the output format for values: 'string' for plain string values or 'any' for values with no specific format")
.define(OUTPUT_TABLE_SCHEMA_TYPE, ConfigDef.Type.STRING,
OutputTableSchemaType.UNSTRUCTURED.name(),
ValidUpperString.in(OutputTableSchemaType.UNSTRUCTURED.name(),
OutputTableSchemaType.STRICT.name(), OutputTableSchemaType.WEAK.name()),
ConfigDef.Importance.HIGH,
"Defines the schema type for output tables: 'unstructured' for schema-less tables, 'strict' for tables with a fixed schema, or 'weak' for tables with a flexible schema")
.define(OUTPUT_DIRECTORY, ConfigDef.Type.STRING, ConfigDef.NO_DEFAULT_VALUE,
new YPathValidator(), ConfigDef.Importance.HIGH,
"Specifies the directory path for storing the output data")
.define(METADATA_DIRECTORY_NAME, ConfigDef.Type.STRING, "__connect_sink_metadata__",
ConfigDef.Importance.MEDIUM, "Suffix for the metadata directory used by the system")
.define(OUTPUT_TTL, ConfigDef.Type.STRING, "30d", new DurationValidator(),
ConfigDef.Importance.MEDIUM,
"Time-to-live (TTL) for output tables or rows, specified as a duration (e.g., '30d' for 30 days)");
public BaseTableWriterConfig(ConfigDef configDef, Map<String, String> originals) {
super(configDef, originals);
if (getAuthType() == AuthType.SERVICE_TICKET && getPassword(SERVICE_TICKET_PROVIDER_URL).value()
.isEmpty()) {
throw new ConfigException(SERVICE_TICKET_PROVIDER_URL, null,
"Must be set when 'yt.connection.auth.type' is 'SERVICE_TICKET'");
} else if (getAuthType() == AuthType.TOKEN && (get(YT_USER) == null || get(YT_TOKEN) == null)) {
throw new ConfigException(
"Both 'yt.connection.user' and 'yt.connection.token' must be set when 'yt.connection.auth.type' is 'TOKEN'");
}
}
public BaseTableWriterConfig(Map<String, String> originals) {
super(CONFIG_DEF, originals);
}
public String getYtUser() {
return getString(YT_USER);
}
public String getYtToken() {
return getPassword(YT_TOKEN).value();
}
public String getYtCluster() {
return getString(YT_CLUSTER);
}
public OutputType getOutputType() {
return OutputType.valueOf(getString(OUTPUT_TYPE).toUpperCase());
}
public OutputTableSchemaType getOutputTableSchemaType() {
return OutputTableSchemaType.valueOf(getString(OUTPUT_TABLE_SCHEMA_TYPE).toUpperCase());
}
public OutputFormat getKeyOutputFormat() {
return OutputFormat.valueOf(getString(KEY_OUTPUT_FORMAT).toUpperCase());
}
public OutputFormat getValueOutputFormat() {
return OutputFormat.valueOf(getString(VALUE_OUTPUT_FORMAT).toUpperCase());
}
public YPath getOutputDirectory() {
return YPath.simple(getString(OUTPUT_DIRECTORY));
}
public YPath getMetadataDirectory() {
return getOutputDirectory().child(getString(METADATA_DIRECTORY_NAME));
}
public Duration getOutputTTL() {
return Util.parseHumanReadableDuration(getString(OUTPUT_TTL));
}
public AuthType getAuthType() {
return AuthType.valueOf(getString(AUTH_TYPE).toUpperCase());
}
public String getServiceTicketProviderUrl() {
return getPassword(SERVICE_TICKET_PROVIDER_URL).value();
}
public YTsaurusClientAuth getYtClientAuth() {
var builder = YTsaurusClientAuth.builder();
if (getAuthType() == AuthType.TOKEN) {
builder.setUser(getYtUser());
builder.setToken(getYtToken());
} else if (getAuthType() == AuthType.SERVICE_TICKET) {
builder.setServiceTicketAuth(new HttpServiceTicketAuth(getServiceTicketProviderUrl()));
} else {
throw new RuntimeException("invalid AuthType!");
}
return builder.build();
}
public enum AuthType {
TOKEN,
SERVICE_TICKET
}
public enum OutputType {
DYNAMIC_TABLE,
STATIC_TABLES
}
public enum OutputFormat {
STRING,
ANY;
public TiType toTiType() {
switch (this) {
case STRING:
return TiType.string();
case ANY:
return TiType.optional(TiType.yson());
default:
throw new IllegalArgumentException("Unsupported output format: " + this);
}
}
}
public enum OutputTableSchemaType {
UNSTRUCTURED,
STRICT,
WEAK
}
public static class YPathValidator implements ConfigDef.Validator {
@Override
public void ensureValid(String name, Object value) {
try {
YPath.simple(value.toString());
} catch (Exception ex) {
throw new ConfigException(name, value, ex.toString());
}
}
}
public static class DurationValidator implements ConfigDef.Validator {
@Override
public void ensureValid(String name, Object value) {
try {
| Util.parseHumanReadableDuration(value.toString()); |
} catch (Exception ex) {
throw new ConfigException(name, value, ex.toString());
}
}
}
public static class ValidUpperString implements ConfigDef.Validator {
final List<String> validStrings;
private ValidUpperString(List<String> validStrings) {
this.validStrings = validStrings.stream().map(String::toUpperCase)
.collect(Collectors.toList());
}
public static ValidUpperString in(String... validStrings) {
return new ValidUpperString(Arrays.asList(validStrings));
}
@Override
public void ensureValid(String name, Object o) {
String s = ((String) o).toUpperCase();
if (!validStrings.contains(s)) {
throw new ConfigException(name, o,
"String must be one of: " + Utils.join(validStrings, ", "));
}
}
public String toString() {
return "[" + Utils.join(
validStrings.stream().map(String::toUpperCase).collect(Collectors.toList()), ", ") + "]";
}
}
}
| src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseTableWriterConfig.java | Dzen-Platform-kafka-connect-ytsaurus-518a6b8 | [
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/YtTableSinkTask.java",
"retrieved_chunk": " @Override\n public void put(Collection<SinkRecord> sinkRecords) {\n try {\n producer.writeBatch(sinkRecords);\n } catch (Exception ex) {\n log.warn(\"Exception in put\", ex);\n throw new RetriableException(ex);\n }\n }\n @Override",
"score": 28.13363839939772
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/staticTables/StaticTableWriterManager.java",
"retrieved_chunk": " } catch (Exception e) {\n log.warn(\"Can't freeze tables\", e);\n if (i == retriesCount) {\n throw e;\n }\n try {\n Thread.sleep(5000);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }",
"score": 20.526054361140197
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/dynamicTable/DynTableWriterManager.java",
"retrieved_chunk": " throw new RetriableException(ex);\n }\n }\n @Override\n public void stop() {\n }\n}",
"score": 20.48321875858554
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseTableWriter.java",
"retrieved_chunk": " protected Object convertRecordValue(SinkRecord record) throws Exception {\n if (record.value() == null) {\n return JsonNodeFactory.instance.nullNode();\n }\n if (record.value() instanceof String) {\n return record.value();\n }\n byte[] jsonBytes = JSON_CONVERTER.fromConnectData(record.topic(), record.valueSchema(),\n record.value());\n var jsonString = new String(jsonBytes, StandardCharsets.UTF_8);",
"score": 20.278411741879182
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/YtTableSinkTask.java",
"retrieved_chunk": " public Map<TopicPartition, OffsetAndMetadata> preCommit(\n Map<TopicPartition, OffsetAndMetadata> currentOffsets) {\n try {\n return producer.getSafeToCommitOffsets(currentOffsets);\n } catch (Exception ex) {\n log.warn(\"Exception in preCommit\", ex);\n return Collections.emptyMap();\n }\n }\n}",
"score": 18.69885680716315
}
] | java | Util.parseHumanReadableDuration(value.toString()); |
package com.example.duckling_movies;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class Login extends AppCompatActivity {
Button btn_login;
TextInputEditText email, senha;
DatabaseReference usuarioRef = FirebaseDatabase.getInstance().getReference().child("usuario");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = findViewById(R.id.email);
senha = findViewById(R.id.senha);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Chamar a função EnviaDadosUsuario() dentro do onClick()
ValidaLogin();
}
});
}
public void RedirecionaLogin(){
Intent intent = new Intent(getApplicationContext(), Anime_feed.class);
startActivity(intent);
}
public void ValidaLogin(){
String Email = email.getText().toString();
String Senha = senha.getText().toString();
if (TextUtils.isEmpty(Email)) {
email.setError("Por favor, digite o e-mail");
email.requestFocus();
return;
}
if (TextUtils.isEmpty(Senha)) {
senha.setError("Por favor, digite a senha");
senha.requestFocus();
return;
}
Query query = usuarioRef.orderByChild("email").equalTo(Email);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Iterar sobre os usuários com o email fornecido e verificar a senha
boolean senhaCorreta = false;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Usuario usuario = snapshot.getValue(Usuario.class);
| if (usuario.getPassword().equals(Senha)) { |
// Senha correta, fazer o login
Toast.makeText(Login.this, "Login realizado com sucesso", Toast.LENGTH_SHORT).show();
RedirecionaLogin();
GlobalVariables.RA_atual = usuario.getMatricula();
senhaCorreta = true;
break;
}
}
if (!senhaCorreta) {
// Senha incorreta, mostrar mensagem de erro
Toast.makeText(Login.this, "Senha incorreta", Toast.LENGTH_SHORT).show();
}
} else {
// Usuário com o email fornecido não encontrado, mostrar mensagem de erro
Toast.makeText(Login.this, "Usuário não encontrado", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
// Ocorreu um erro ao consultar o banco de dados Firebase, mostrar mensagem de erro
Toast.makeText(Login.this, "Erro ao consultar o banco de dados Firebase", Toast.LENGTH_SHORT).show();
}
});
}
} | src/app/src/main/java/com/example/duckling_movies/Login.java | enzogebauer-duckling_animes-a00d26d | [
{
"filename": "src/app/src/main/java/com/example/duckling_movies/Register.java",
"retrieved_chunk": " }\n // Verificar se já existe um usuário com o mesmo email\n Query query = usuarioRef.orderByChild(\"email\").equalTo(Email);\n query.addListenerForSingleValueEvent(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n // Se já existe um usuário com o mesmo email, mostrar um toast de erro\n if (snapshot.exists()) {\n Toast.makeText(Register.this, \"Já existe um usuário com o mesmo email\", Toast.LENGTH_SHORT).show();\n return;",
"score": 42.21297615630348
},
{
"filename": "src/app/src/main/java/com/example/duckling_movies/Register.java",
"retrieved_chunk": " // Criar um objeto UserModel com os dados de entrada do usuário\n Usuario user = new Usuario(Nome, Email, Senha, Matricula);\n Query query = usuarioRef.orderByChild(\"matricula\").equalTo(Matricula);\n query.addListenerForSingleValueEvent(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n // Se já existe um usuário com a mesma matrícula, mostrar um toast de erro\n if (snapshot.exists()) {\n Toast.makeText(Register.this, \"Já existe um usuário com a mesma matrícula\", Toast.LENGTH_SHORT).show();\n return; // não sei se precisa do return",
"score": 41.758462551977274
},
{
"filename": "src/app/src/main/java/com/example/duckling_movies/Anime_feed.java",
"retrieved_chunk": " public void onDataChange(DataSnapshot dataSnapshot) {\n // Limpa a lista de animes antes de adicionar os dados atualizados\n animeList.clear();\n // Itera sobre todos os filhos do nó \"anime\"\n for (DataSnapshot animeSnapshot : dataSnapshot.getChildren()) {\n // Cria um objeto Anime com os dados do snapshot\n Anime anime = animeSnapshot.getValue(Anime.class);\n // Adiciona o objeto Anime à lista de animes\n animeList.add(anime.getName() + \"Ano: \" + anime.getYear());\n }",
"score": 38.77671192498518
},
{
"filename": "src/app/src/main/java/com/example/duckling_movies/Register.java",
"retrieved_chunk": " }\n // Verificar se já existe um usuário com o mesmo nome\n Query query = usuarioRef.orderByChild(\"nome\").equalTo(Nome);\n query.addListenerForSingleValueEvent(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n // Se já existe um usuário com o mesmo nome, mostrar um toast de erro\n if (snapshot.exists()) {\n Toast.makeText(Register.this, \"Já existe um usuário com o mesmo nome\", Toast.LENGTH_SHORT).show();\n return;",
"score": 35.55829012772658
},
{
"filename": "src/app/src/main/java/com/example/duckling_movies/PostAnimes.java",
"retrieved_chunk": " if (snapshot.exists()) {\n query_ano.addListenerForSingleValueEvent(new ValueEventListener() {\n @Override\n public void onDataChange(@NonNull DataSnapshot snapshot) {\n if (snapshot.exists()) {\n Toast.makeText(PostAnimes.this, \"Já existe um anime com mesmo nome e mesmo ano\", Toast.LENGTH_SHORT).show();\n return;\n }\n }\n @Override",
"score": 31.506981314827115
}
] | java | if (usuario.getPassword().equals(Senha)) { |
package ru.dzen.kafka.connect.ytsaurus.common;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kafka.connect.header.Header;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.sink.SinkRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.dzen.kafka.connect.ytsaurus.common.BaseTableWriterConfig.AuthType;
import ru.dzen.kafka.connect.ytsaurus.common.BaseTableWriterConfig.OutputTableSchemaType;
import tech.ytsaurus.client.ApiServiceTransaction;
import tech.ytsaurus.client.YTsaurusClient;
import tech.ytsaurus.client.YTsaurusClientConfig;
import tech.ytsaurus.client.request.StartTransaction;
import tech.ytsaurus.ysontree.YTree;
import tech.ytsaurus.ysontree.YTreeNode;
public abstract class BaseTableWriter {
protected static final ObjectMapper objectMapper = new ObjectMapper();
private static final Logger log = LoggerFactory.getLogger(BaseTableWriter.class);
private static final JsonConverter JSON_CONVERTER;
static {
JSON_CONVERTER = new JsonConverter();
JSON_CONVERTER.configure(Collections.singletonMap("schemas.enable", "false"), false);
}
protected final YTsaurusClient client;
protected final BaseOffsetsManager offsetsManager;
protected final BaseTableWriterConfig config;
protected BaseTableWriter(BaseTableWriterConfig config, BaseOffsetsManager offsetsManager) {
this.config = config;
this.client = YTsaurusClient.builder()
.setConfig(YTsaurusClientConfig.builder()
.setTvmOnly(config.getAuthType().equals(AuthType.SERVICE_TICKET)).build())
.setCluster(config.getYtCluster()).setAuth(config.getYtClientAuth()).build();
this.offsetsManager = offsetsManager;
}
protected ApiServiceTransaction createTransaction() throws Exception {
return client.startTransaction(StartTransaction.master()).get();
}
public Map<TopicPartition, OffsetAndMetadata> getSafeToCommitOffsets(
Map<TopicPartition, OffsetAndMetadata> unsafeOffsets) throws Exception {
return offsetsManager.getPrevOffsets(createTransaction(), unsafeOffsets.keySet()).entrySet()
.stream()
.filter(entry -> unsafeOffsets.containsKey(entry.getKey()))
.map(entry -> {
var topicPartition = entry.getKey();
var prevOffset = entry.getValue();
var unsafeOffset = unsafeOffsets.get(topicPartition);
return unsafeOffset.offset() >= prevOffset.offset() ?
Map.entry(topicPartition, prevOffset) :
Map.entry(topicPartition, unsafeOffset);
})
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
protected Object convertRecordKey(SinkRecord record) throws Exception {
if (record.key() == null) {
return JsonNodeFactory.instance.nullNode();
}
if (record.key() instanceof String) {
return record.key();
}
byte[] jsonBytes = JSON_CONVERTER.fromConnectData(record.topic(), record.keySchema(),
record.key());
var jsonString = new String(jsonBytes, StandardCharsets.UTF_8);
JsonNode jsonNode = objectMapper.readTree(jsonString);
return jsonNode;
}
protected YTreeNode convertRecordKeyToNode(SinkRecord record) throws Exception {
var recordKey = convertRecordKey(record);
if | (config.getKeyOutputFormat() == BaseTableWriterConfig.OutputFormat.STRING
&& !(recordKey instanceof String)) { |
recordKey = objectMapper.writeValueAsString(recordKey);
} else if (!(recordKey instanceof String)) {
recordKey = Util.convertJsonNodeToYTree((JsonNode) recordKey);
}
return YTree.node(recordKey);
}
protected Object convertRecordValue(SinkRecord record) throws Exception {
if (record.value() == null) {
return JsonNodeFactory.instance.nullNode();
}
if (record.value() instanceof String) {
return record.value();
}
byte[] jsonBytes = JSON_CONVERTER.fromConnectData(record.topic(), record.valueSchema(),
record.value());
var jsonString = new String(jsonBytes, StandardCharsets.UTF_8);
JsonNode jsonNode = objectMapper.readTree(jsonString);
return jsonNode;
}
protected YTreeNode convertRecordValueToNode(SinkRecord record) throws Exception {
var recordValue = convertRecordValue(record);
if (config.getValueOutputFormat() == BaseTableWriterConfig.OutputFormat.STRING
&& !(recordValue instanceof String)) {
recordValue = objectMapper.writeValueAsString(recordValue);
} else if (!(recordValue instanceof String)) {
recordValue = Util.convertJsonNodeToYTree((JsonNode) recordValue);
}
return YTree.node(recordValue);
}
protected List<Map<String, YTreeNode>> recordsToRows(Collection<SinkRecord> records) {
var mapNodesToWrite = new ArrayList<Map<String, YTreeNode>>();
for (SinkRecord record : records) {
var headersBuilder = YTree.builder().beginList();
for (Header header : record.headers()) {
headersBuilder.value(
YTree.builder().beginList().value(header.key()).value(header.value().toString())
.buildList());
}
YTreeNode recordKeyNode;
try {
recordKeyNode = convertRecordKeyToNode(record);
} catch (Exception e) {
log.error("Exception in convertRecordKeyToNode:", e);
throw new DataException(e);
}
YTreeNode recordValueNode;
try {
recordValueNode = convertRecordValueToNode(record);
} catch (Exception e) {
log.error("Exception in convertRecordValueToNode:", e);
throw new DataException(e);
}
Map<String, YTreeNode> rowMap = new HashMap<>();
if (config.getOutputTableSchemaType().equals(OutputTableSchemaType.UNSTRUCTURED)) {
rowMap.put(UnstructuredTableSchema.EColumn.DATA.name, recordValueNode);
} else {
if (!recordValueNode.isMapNode()) {
throw new DataException("Record value is not a map: " + recordValueNode);
}
rowMap = recordValueNode.asMap();
}
rowMap.put(UnstructuredTableSchema.EColumn.KEY.name, recordKeyNode);
rowMap.put(UnstructuredTableSchema.EColumn.TOPIC.name, YTree.stringNode(record.topic()));
rowMap.put(UnstructuredTableSchema.EColumn.PARTITION.name,
YTree.unsignedLongNode(record.kafkaPartition()));
rowMap.put(UnstructuredTableSchema.EColumn.OFFSET.name,
YTree.unsignedLongNode(record.kafkaOffset()));
rowMap.put(UnstructuredTableSchema.EColumn.TIMESTAMP.name,
YTree.unsignedLongNode(System.currentTimeMillis()));
rowMap.put(UnstructuredTableSchema.EColumn.HEADERS.name, headersBuilder.buildList());
mapNodesToWrite.add(rowMap);
}
return mapNodesToWrite;
}
protected void writeRows(ApiServiceTransaction trx, Collection<SinkRecord> records)
throws Exception {
}
protected void writeRows(ApiServiceTransaction trx, Collection<SinkRecord> records,
Set<TopicPartition> topicPartitions)
throws Exception {
writeRows(trx, records);
}
public void writeBatch(Collection<SinkRecord> records) throws Exception {
var startTime = System.currentTimeMillis();
try (var trx = createTransaction()) {
var maxOffsets = offsetsManager.getMaxOffsets(records);
offsetsManager.lockPartitions(trx, maxOffsets.keySet());
var prevOffsets = offsetsManager.getPrevOffsets(trx,
maxOffsets.keySet());
var filteredRecords = offsetsManager.filterRecords(records, prevOffsets);
if (filteredRecords.isEmpty()) {
trx.close();
} else {
writeRows(trx, filteredRecords, maxOffsets.keySet());
offsetsManager.writeOffsets(trx, maxOffsets);
trx.commit().get();
}
var elapsed = Duration.ofMillis(System.currentTimeMillis() - startTime);
log.info("Done processing batch in {}: {} total, {} written, {} skipped",
Util.toHumanReadableDuration(elapsed), records.size(), filteredRecords.size(),
records.size() - filteredRecords.size());
} catch (Exception ex) {
throw ex;
}
}
public abstract TableWriterManager getManager();
}
| src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseTableWriter.java | Dzen-Platform-kafka-connect-ytsaurus-518a6b8 | [
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseOffsetsManager.java",
"retrieved_chunk": " public Collection<SinkRecord> filterRecords(Collection<SinkRecord> sinkRecords,\n Map<TopicPartition, OffsetAndMetadata> prevOffsetsMap) {\n return sinkRecords.stream()\n .filter(record -> {\n var topicPartition = new TopicPartition(record.topic(), record.kafkaPartition());\n return !prevOffsetsMap.containsKey(topicPartition)\n || prevOffsetsMap.get(topicPartition).offset() < record.kafkaOffset();\n })\n .collect(Collectors.toList());\n }",
"score": 32.518960825693696
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/Util.java",
"retrieved_chunk": " public static YTreeNode convertJsonNodeToYTree(JsonNode jsonNode) {\n if (jsonNode.isObject()) {\n var mapBuilder = YTree.mapBuilder();\n jsonNode.fields().forEachRemaining(entry -> {\n var key = entry.getKey();\n var valueNode = entry.getValue();\n mapBuilder.key(key).value(convertJsonNodeToYTree(valueNode));\n });\n return mapBuilder.buildMap();\n } else if (jsonNode.isArray()) {",
"score": 29.718617417529668
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/BaseOffsetsManager.java",
"retrieved_chunk": " public Map<TopicPartition, OffsetAndMetadata> getMaxOffsets(Collection<SinkRecord> sinkRecords) {\n return sinkRecords.stream()\n .collect(Collectors.toMap(\n record -> new TopicPartition(record.topic(), record.kafkaPartition()),\n record -> new OffsetAndMetadata(record.kafkaOffset()),\n (prev, curr) -> curr.offset() > prev.offset() ? curr : prev\n ));\n }\n public abstract Map<TopicPartition, OffsetAndMetadata> getPrevOffsets(ApiServiceTransaction trx,\n Set<TopicPartition> topicPartitions)",
"score": 29.436875621792893
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/Util.java",
"retrieved_chunk": " }\n } else if (jsonNode.isBoolean()) {\n return YTree.booleanNode(jsonNode.asBoolean());\n } else if (jsonNode.isNull()) {\n return YTree.nullNode();\n } else {\n throw new UnsupportedOperationException(\n \"Unsupported JsonNode type: \" + jsonNode.getNodeType());\n }\n }",
"score": 23.781641497763903
},
{
"filename": "src/main/java/ru/dzen/kafka/connect/ytsaurus/common/Util.java",
"retrieved_chunk": " var listBuilder = YTree.listBuilder();\n jsonNode.forEach(element -> listBuilder.value(convertJsonNodeToYTree(element)));\n return listBuilder.buildList();\n } else if (jsonNode.isTextual()) {\n return YTree.stringNode(jsonNode.asText());\n } else if (jsonNode.isNumber()) {\n if (jsonNode.isIntegralNumber()) {\n return YTree.longNode(jsonNode.asLong());\n } else {\n return YTree.doubleNode(jsonNode.asDouble());",
"score": 21.94815803099836
}
] | java | (config.getKeyOutputFormat() == BaseTableWriterConfig.OutputFormat.STRING
&& !(recordKey instanceof String)) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.