repo_name stringlengths 7 70 | file_path stringlengths 9 215 | context list | import_statement stringlengths 47 10.3k | token_num int64 643 100k | cropped_code stringlengths 62 180k | all_code stringlengths 62 224k | next_line stringlengths 9 1.07k | gold_snippet_index int64 0 117 | created_at stringlengths 25 25 | level stringclasses 9
values |
|---|---|---|---|---|---|---|---|---|---|---|
awesome-java-web/groovy-script-executor | src/main/java/com/github/awesome/scripting/groovy/GroovyScriptExecutor.java | [
{
"identifier": "LocalCacheManager",
"path": "src/main/java/com/github/awesome/scripting/groovy/cache/LocalCacheManager.java",
"snippet": "public class LocalCacheManager implements LocalCache {\n\n private LocalCache localCache;\n\n public static LocalCacheManager newBuilder() {\n return ne... | import com.github.awesome.scripting.groovy.cache.LocalCacheManager;
import com.github.awesome.scripting.groovy.exception.GroovyObjectInvokeMethodException;
import com.github.awesome.scripting.groovy.exception.GroovyScriptParseException;
import com.github.awesome.scripting.groovy.exception.InvalidGroovyScriptException;
import com.github.awesome.scripting.groovy.security.DefaultGroovyScriptSecurityChecker;
import com.github.awesome.scripting.groovy.security.GroovyScriptSecurityChecker;
import com.github.awesome.scripting.groovy.util.Md5Utils;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.IOException; | 1,745 | package com.github.awesome.scripting.groovy;
public class GroovyScriptExecutor {
private LocalCacheManager localCacheManager;
private GroovyScriptSecurityChecker groovyScriptSecurityChecker;
public static GroovyScriptExecutor newBuilder() {
return new GroovyScriptExecutor();
}
public GroovyScriptExecutor() {
this.groovyScriptSecurityChecker = new DefaultGroovyScriptSecurityChecker();
}
public GroovyScriptExecutor withCacheManager(LocalCacheManager localCacheManager) {
this.localCacheManager = localCacheManager;
return this;
}
public GroovyScriptExecutor withSecurityChecker(GroovyScriptSecurityChecker groovyScriptSecurityChecker) {
this.groovyScriptSecurityChecker = groovyScriptSecurityChecker;
return this;
}
public LocalCacheManager getCacheManager() {
return localCacheManager;
}
public Object execute(final String classScript, final String function, final Object... parameters) {
if (classScript == null) {
throw new InvalidGroovyScriptException("Groovy script is null");
}
final String trimmedScript = classScript.trim();
if (trimmedScript.isEmpty()) {
throw new InvalidGroovyScriptException("Groovy script is empty");
}
// Check if the script contains any unsafe keywords
this.groovyScriptSecurityChecker.checkOrThrow(trimmedScript);
// Find groovy object from cache first
final String scriptCacheKey = Md5Utils.md5Hex(trimmedScript);
GroovyObject groovyObjectCache = this.localCacheManager.getIfPresent(scriptCacheKey);
// Parse the script and put it into cache instantly if it is not in cache
if (groovyObjectCache == null) {
groovyObjectCache = parseClassScript(trimmedScript);
this.localCacheManager.put(scriptCacheKey, groovyObjectCache);
}
// Script is parsed successfully
return invokeMethod(groovyObjectCache, function, parameters);
}
private GroovyObject parseClassScript(final String classScript) {
try (GroovyClassLoader groovyClassLoader = new GroovyClassLoader()) {
Class<?> scriptClass = groovyClassLoader.parseClass(classScript);
return (GroovyObject) scriptClass.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException e) {
throw new GroovyScriptParseException("Failed to parse groovy script, the nested exception is: " + e.getMessage());
}
}
private Object invokeMethod(GroovyObject groovyObject, String function, Object... parameters) {
try {
return groovyObject.invokeMethod(function, parameters);
} catch (Exception e) {
final String errorMessage = String.format("Failed to invoke groovy method '%s', the nested exception is: %s", function, e.getMessage()); | package com.github.awesome.scripting.groovy;
public class GroovyScriptExecutor {
private LocalCacheManager localCacheManager;
private GroovyScriptSecurityChecker groovyScriptSecurityChecker;
public static GroovyScriptExecutor newBuilder() {
return new GroovyScriptExecutor();
}
public GroovyScriptExecutor() {
this.groovyScriptSecurityChecker = new DefaultGroovyScriptSecurityChecker();
}
public GroovyScriptExecutor withCacheManager(LocalCacheManager localCacheManager) {
this.localCacheManager = localCacheManager;
return this;
}
public GroovyScriptExecutor withSecurityChecker(GroovyScriptSecurityChecker groovyScriptSecurityChecker) {
this.groovyScriptSecurityChecker = groovyScriptSecurityChecker;
return this;
}
public LocalCacheManager getCacheManager() {
return localCacheManager;
}
public Object execute(final String classScript, final String function, final Object... parameters) {
if (classScript == null) {
throw new InvalidGroovyScriptException("Groovy script is null");
}
final String trimmedScript = classScript.trim();
if (trimmedScript.isEmpty()) {
throw new InvalidGroovyScriptException("Groovy script is empty");
}
// Check if the script contains any unsafe keywords
this.groovyScriptSecurityChecker.checkOrThrow(trimmedScript);
// Find groovy object from cache first
final String scriptCacheKey = Md5Utils.md5Hex(trimmedScript);
GroovyObject groovyObjectCache = this.localCacheManager.getIfPresent(scriptCacheKey);
// Parse the script and put it into cache instantly if it is not in cache
if (groovyObjectCache == null) {
groovyObjectCache = parseClassScript(trimmedScript);
this.localCacheManager.put(scriptCacheKey, groovyObjectCache);
}
// Script is parsed successfully
return invokeMethod(groovyObjectCache, function, parameters);
}
private GroovyObject parseClassScript(final String classScript) {
try (GroovyClassLoader groovyClassLoader = new GroovyClassLoader()) {
Class<?> scriptClass = groovyClassLoader.parseClass(classScript);
return (GroovyObject) scriptClass.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException e) {
throw new GroovyScriptParseException("Failed to parse groovy script, the nested exception is: " + e.getMessage());
}
}
private Object invokeMethod(GroovyObject groovyObject, String function, Object... parameters) {
try {
return groovyObject.invokeMethod(function, parameters);
} catch (Exception e) {
final String errorMessage = String.format("Failed to invoke groovy method '%s', the nested exception is: %s", function, e.getMessage()); | throw new GroovyObjectInvokeMethodException(errorMessage); | 1 | 2023-12-11 03:30:22+00:00 | 4k |
IzanagiCraft/data-storage | src/test/java/tests/InMemoryDataRepositoryTest.java | [
{
"identifier": "DataRepository",
"path": "src/main/java/com/izanagicraft/storage/repository/DataRepository.java",
"snippet": "public interface DataRepository<T> {\n\n /**\n * Retrieves data associated with the specified key.\n *\n * @param key the key to retrieve data\n * @return the... | import com.izanagicraft.storage.repository.DataRepository;
import com.izanagicraft.storage.repository.InMemoryDataRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; | 1,829 | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package tests;
/**
* data-storage; tests:InMemoryDataRepositoryTest
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
class InMemoryDataRepositoryTest {
private DataRepository<String> stringRepository;
private DataRepository<Integer> integerRepository;
@BeforeEach
void setUp() {
// Initialize a new InMemoryDataRepository for String and Integer types before each test | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package tests;
/**
* data-storage; tests:InMemoryDataRepositoryTest
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
class InMemoryDataRepositoryTest {
private DataRepository<String> stringRepository;
private DataRepository<Integer> integerRepository;
@BeforeEach
void setUp() {
// Initialize a new InMemoryDataRepository for String and Integer types before each test | stringRepository = new InMemoryDataRepository<>(); | 1 | 2023-12-13 17:05:12+00:00 | 4k |
ItzOverS/CoReScreen | src/main/java/me/overlight/corescreen/ClientSettings/CSManager.java | [
{
"identifier": "ChatVisibility",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/Modules/ChatVisibility.java",
"snippet": "public class ChatVisibility extends CSModule {\n public ChatVisibility() {\n super(\"ChatVisibility\", \"chatvisibility\");\n }\n\n @Override\n pub... | import me.overlight.corescreen.ClientSettings.Modules.ChatVisibility;
import me.overlight.corescreen.ClientSettings.Modules.ClientVersion;
import me.overlight.corescreen.ClientSettings.Modules.Locale;
import me.overlight.corescreen.ClientSettings.Modules.RenderDistance;
import me.overlight.corescreen.Test.TestCheck;
import me.overlight.corescreen.Test.Tests.Knockback;
import me.overlight.corescreen.Test.Tests.Rotation;
import me.overlight.corescreen.Test.Tests.Shuffle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | 1,900 | package me.overlight.corescreen.ClientSettings;
public class CSManager {
public final static List<CSModule> modules = new ArrayList<>();
static { | package me.overlight.corescreen.ClientSettings;
public class CSManager {
public final static List<CSModule> modules = new ArrayList<>();
static { | modules.addAll(Arrays.asList(new ClientVersion(), new Locale(), new RenderDistance(), new ChatVisibility())); | 1 | 2023-12-07 16:34:39+00:00 | 4k |
Erdi-Topuzlu/RentACar_Tobeto_Project | src/main/java/com/tobeto/RentACar/services/concretes/CarManager.java | [
{
"identifier": "ModelMapperService",
"path": "src/main/java/com/tobeto/RentACar/core/mapper/ModelMapperService.java",
"snippet": "public interface ModelMapperService {\n ModelMapper entityToDto();\n ModelMapper dtoToEntity();\n}"
},
{
"identifier": "Car",
"path": "src/main/java/com/to... | import com.tobeto.RentACar.core.mapper.ModelMapperService;
import com.tobeto.RentACar.entities.concretes.Car;
import com.tobeto.RentACar.repositories.CarRepository;
import com.tobeto.RentACar.rules.car.CarBusinessRulesService;
import com.tobeto.RentACar.services.abstracts.CarService;
import com.tobeto.RentACar.services.dtos.requests.car.AddCarRequest;
import com.tobeto.RentACar.services.dtos.requests.car.DeleteCarRequest;
import com.tobeto.RentACar.services.dtos.requests.car.UpdateCarRequest;
import com.tobeto.RentACar.services.dtos.responses.car.GetAllCarResponse;
import com.tobeto.RentACar.services.dtos.responses.car.GetByIdCarResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List; | 1,870 | package com.tobeto.RentACar.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final CarBusinessRulesService carBusinessRulesService;
@Override
public void add(AddCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public void update(UpdateCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfByIdExists(request.getId());
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public DeleteCarRequest delete(int id) {
Car car = carRepository.findById(id).orElseThrow();
carRepository.deleteById(car.getId());
return modelMapperService.entityToDto().map(car, DeleteCarRequest.class);
}
@Override | package com.tobeto.RentACar.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final CarBusinessRulesService carBusinessRulesService;
@Override
public void add(AddCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public void update(UpdateCarRequest request) {
//Business Rules
carBusinessRulesService.checkIfByIdExists(request.getId());
carBusinessRulesService.checkIfPlateNameExists(request.getPlate());
carBusinessRulesService.checkIfColorIdExists(request.getColorId());
carBusinessRulesService.checkIfModelIdExists(request.getModelId());
Car car = modelMapperService.dtoToEntity().map(request, Car.class);
car.setPlate(request.getPlate().toUpperCase());
carRepository.save(car);
}
@Override
public DeleteCarRequest delete(int id) {
Car car = carRepository.findById(id).orElseThrow();
carRepository.deleteById(car.getId());
return modelMapperService.entityToDto().map(car, DeleteCarRequest.class);
}
@Override | public List<GetAllCarResponse> getAll() { | 8 | 2023-12-11 08:33:34+00:00 | 4k |
Khoshimjonov/SalahTimes | src/main/java/uz/khoshimjonov/widget/SalahWidget.java | [
{
"identifier": "WidgetTextDto",
"path": "src/main/java/uz/khoshimjonov/dto/WidgetTextDto.java",
"snippet": "public class WidgetTextDto {\n\n private String nextSalah;\n private String remainingTime;\n private Color textColor;\n\n public WidgetTextDto(String nextSalah, String remainingTime, ... | import uz.khoshimjonov.dto.WidgetTextDto;
import uz.khoshimjonov.service.ConfigurationManager;
import uz.khoshimjonov.service.LanguageHelper;
import uz.khoshimjonov.service.SalahTimeService;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | 3,469 | package uz.khoshimjonov.widget;
public class SalahWidget {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final ConfigurationManager configurationManager = ConfigurationManager.getInstance();
private final SalahTimeService salahTimeService = new SalahTimeService();
private FrameDragListener frameDragListener = null;
private SalahTimesWindow salahTimesWindow;
private final TrayIcon trayIcon;
private final SystemTray tray;
private final boolean SET_LOOK_AND_FEEL;
private final int UPDATE_DELAY;
private final int POINT_X;
private final int POINT_Y;
public SalahWidget() {
try {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
throw new UnsupportedOperationException();
}
this.SET_LOOK_AND_FEEL = configurationManager.getLookAndFeelEnabled();
this.UPDATE_DELAY = configurationManager.getUpdateDelay();
this.POINT_X = configurationManager.getPointX();
this.POINT_Y = configurationManager.getPointY();
this.tray = SystemTray.getSystemTray();
BufferedImage trayIconImage = ImageIO.read(Objects.requireNonNull(getClass().getResource("/images/app.png")));
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
this.trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH), LanguageHelper.getText("tooltipTitle"));
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
showSalahTimesWindow(e);
}
}
});
tray.add(trayIcon);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void displayWidget() {
Runnable runnable = () -> {
if (SET_LOOK_AND_FEEL) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
}
final JDialog dialog = new JDialog();
final JLabel timeLabel = new AntiAliasedLabel();
final JLabel remainingLabel = new AntiAliasedLabel();
dialog.setLayout(new FlowLayout(FlowLayout.LEFT));
dialog.requestFocus();
dialog.setMinimumSize(new Dimension(350, 30));
dialog.setFocusableWindowState(false);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setUndecorated(true);
dialog.setBackground(new Color(0, 0, 0, 0));
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.add(timeLabel);
dialog.add(remainingLabel);
dialog.toFront();
scheduler.scheduleAtFixedRate(() -> { | package uz.khoshimjonov.widget;
public class SalahWidget {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final ConfigurationManager configurationManager = ConfigurationManager.getInstance();
private final SalahTimeService salahTimeService = new SalahTimeService();
private FrameDragListener frameDragListener = null;
private SalahTimesWindow salahTimesWindow;
private final TrayIcon trayIcon;
private final SystemTray tray;
private final boolean SET_LOOK_AND_FEEL;
private final int UPDATE_DELAY;
private final int POINT_X;
private final int POINT_Y;
public SalahWidget() {
try {
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
throw new UnsupportedOperationException();
}
this.SET_LOOK_AND_FEEL = configurationManager.getLookAndFeelEnabled();
this.UPDATE_DELAY = configurationManager.getUpdateDelay();
this.POINT_X = configurationManager.getPointX();
this.POINT_Y = configurationManager.getPointY();
this.tray = SystemTray.getSystemTray();
BufferedImage trayIconImage = ImageIO.read(Objects.requireNonNull(getClass().getResource("/images/app.png")));
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
this.trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH), LanguageHelper.getText("tooltipTitle"));
trayIcon.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
showSalahTimesWindow(e);
}
}
});
tray.add(trayIcon);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void displayWidget() {
Runnable runnable = () -> {
if (SET_LOOK_AND_FEEL) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
}
final JDialog dialog = new JDialog();
final JLabel timeLabel = new AntiAliasedLabel();
final JLabel remainingLabel = new AntiAliasedLabel();
dialog.setLayout(new FlowLayout(FlowLayout.LEFT));
dialog.requestFocus();
dialog.setMinimumSize(new Dimension(350, 30));
dialog.setFocusableWindowState(false);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setUndecorated(true);
dialog.setBackground(new Color(0, 0, 0, 0));
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setAlwaysOnTop(true);
dialog.add(timeLabel);
dialog.add(remainingLabel);
dialog.toFront();
scheduler.scheduleAtFixedRate(() -> { | WidgetTextDto widgetText = salahTimeService.getWidgetText(trayIcon); | 0 | 2023-12-07 13:40:16+00:00 | 4k |
Akshar062/MovieReviews | app/src/main/java/com/akshar/moviereviews/ApiUtils/AllMovieApi.java | [
{
"identifier": "AllModel",
"path": "app/src/main/java/com/akshar/moviereviews/Models/AllModel.java",
"snippet": "public class AllModel {\n\n public int page;\n\n @SerializedName(\"results\")\n public List<Result> results;\n\n @SerializedName(\"total_pages\")\n public int totalPages;\n\n ... | import com.akshar.moviereviews.Models.AllModel;
import com.akshar.moviereviews.Models.MovieModel;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query; | 2,769 | package com.akshar.moviereviews.ApiUtils;
public interface AllMovieApi {
@GET("trending/all/week") | package com.akshar.moviereviews.ApiUtils;
public interface AllMovieApi {
@GET("trending/all/week") | Call<AllModel> getTrendingAll(@Query("api_key") String apiKey); | 0 | 2023-12-05 10:20:16+00:00 | 4k |
ShardMC/arte | common/src/main/java/io/shardmc/arte/common/pack/manager/PackManager.java | [
{
"identifier": "Arte",
"path": "common/src/main/java/io/shardmc/arte/common/Arte.java",
"snippet": "public interface Arte {\n ArteLogger logger();\n ArteConfig config();\n PackManager getPackManager();\n\n File getDataFolder();\n File getConfigFile();\n\n URL getResourceUrl(String pat... | import io.shardmc.arte.common.Arte;
import io.shardmc.arte.common.config.ArteConfig;
import io.shardmc.arte.common.config.data.FilterList;
import io.shardmc.arte.common.config.data.PackMode;
import io.shardmc.arte.common.pack.zipper.PackZipper;
import io.shardmc.arte.common.util.lambda.PackZipperCreator;
import io.shardmc.arte.common.web.WebServer;
import java.io.IOException;
import java.nio.file.Path; | 3,021 | package io.shardmc.arte.common.pack.manager;
public class PackManager {
protected final Arte arte;
protected final WebServer server;
protected final Path root;
protected final Path output;
protected PackZipper zipper;
public PackManager(Arte arte) {
this.arte = arte;
this.server = new WebServer(this.arte);
this.root = this.arte.getDataFolder()
.toPath().resolve("resourcepack");
this.output = this.arte.getDataFolder()
.toPath().resolve("generated");
ArteConfig config = this.arte.config();
this.reload(config.shouldUseCache()
? PackMode.CACHED : config.getMode());
}
public void reload() {
this.reload(this.arte.config().getMode());
}
protected void reload(PackMode mode) {
this.reload(mode.creator());
}
| package io.shardmc.arte.common.pack.manager;
public class PackManager {
protected final Arte arte;
protected final WebServer server;
protected final Path root;
protected final Path output;
protected PackZipper zipper;
public PackManager(Arte arte) {
this.arte = arte;
this.server = new WebServer(this.arte);
this.root = this.arte.getDataFolder()
.toPath().resolve("resourcepack");
this.output = this.arte.getDataFolder()
.toPath().resolve("generated");
ArteConfig config = this.arte.config();
this.reload(config.shouldUseCache()
? PackMode.CACHED : config.getMode());
}
public void reload() {
this.reload(this.arte.config().getMode());
}
protected void reload(PackMode mode) {
this.reload(mode.creator());
}
| protected void reload(PackZipperCreator zipper) { | 4 | 2023-12-09 10:58:32+00:00 | 4k |
nurseld/RentACar | pair2/src/main/java/com/tobeto/pair2/services/concretes/CarManager.java | [
{
"identifier": "ModelMapperService",
"path": "pair2/src/main/java/com/tobeto/pair2/core/utilities/mapper/ModelMapperService.java",
"snippet": "public interface ModelMapperService {\n ModelMapper forResponse();\n ModelMapper forRequest();\n\n\n}"
},
{
"identifier": "Car",
"path": "pair... | import com.tobeto.pair2.core.utilities.mapper.ModelMapperService;
import com.tobeto.pair2.entitites.Car;
import com.tobeto.pair2.repositories.CarRepository;
import com.tobeto.pair2.services.abstracts.CarService;
import com.tobeto.pair2.services.abstracts.ColorService;
import com.tobeto.pair2.services.abstracts.ModelService;
import com.tobeto.pair2.services.dtos.car.requests.AddCarRequest;
import com.tobeto.pair2.services.dtos.car.requests.UpdateCarRequest;
import com.tobeto.pair2.services.dtos.car.responses.GetAllCarResponse;
import com.tobeto.pair2.services.dtos.car.responses.GetByIdCarResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List; | 1,882 | package com.tobeto.pair2.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final ModelService modelService;
private final ColorService colorService;
@Override
public void add(AddCarRequest request) {
if(carRepository.existsCarByPlate(request.getPlate())){
throw new RuntimeException("Another car cannot be added with the same license plate.");
}
if(!modelService.existsByModelId(request.getModelId())) {
throw new RuntimeException("The ModelId must exist in the database.");
}
if(!colorService.existsByColorId(request.getColorId())) {
throw new RuntimeException("The ColorId must exist in the database.");
}
Car car = this.modelMapperService.forRequest().map(request, Car.class);
this.carRepository.save(car);
}
@Override | package com.tobeto.pair2.services.concretes;
@Service
@AllArgsConstructor
public class CarManager implements CarService {
private final CarRepository carRepository;
private final ModelMapperService modelMapperService;
private final ModelService modelService;
private final ColorService colorService;
@Override
public void add(AddCarRequest request) {
if(carRepository.existsCarByPlate(request.getPlate())){
throw new RuntimeException("Another car cannot be added with the same license plate.");
}
if(!modelService.existsByModelId(request.getModelId())) {
throw new RuntimeException("The ModelId must exist in the database.");
}
if(!colorService.existsByColorId(request.getColorId())) {
throw new RuntimeException("The ColorId must exist in the database.");
}
Car car = this.modelMapperService.forRequest().map(request, Car.class);
this.carRepository.save(car);
}
@Override | public void update(UpdateCarRequest request) { | 7 | 2023-12-11 12:26:27+00:00 | 4k |
fabriciofx/cactoos-pdf | src/main/java/com/github/fabriciofx/cactoos/pdf/image/png/Safe.java | [
{
"identifier": "Indirect",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/Indirect.java",
"snippet": "public interface Indirect extends Bytes {\n /**\n * Create an object reference.\n *\n * @return A reference\n */\n Reference reference();\n\n /**\n * Create a dic... | import java.util.Arrays;
import com.github.fabriciofx.cactoos.pdf.Indirect;
import com.github.fabriciofx.cactoos.pdf.image.Body;
import com.github.fabriciofx.cactoos.pdf.image.Flow;
import com.github.fabriciofx.cactoos.pdf.image.Header;
import com.github.fabriciofx.cactoos.pdf.image.InvalidFormatException;
import com.github.fabriciofx.cactoos.pdf.image.Palette;
import com.github.fabriciofx.cactoos.pdf.image.Raw; | 2,303 | /*
* The MIT License (MIT)
*
* Copyright (C) 2023-2024 Fabrício Barros Cabral
*
* 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 NON-INFRINGEMENT. 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.fabriciofx.cactoos.pdf.image.png;
/**
* SafePngRaw: Safe decorator for a PNG image raw.
*
* @since 0.0.1
*/
public final class Safe implements Raw {
/**
* PNG file signature.
*/
private static final byte[] SIGNATURE = {
(byte) 137, 'P', 'N', 'G', '\r', '\n', 26, '\n',
};
/**
* Raw origin.
*/
private final PngRaw origin;
/**
* Ctor.
*
* @param raw Image raw
*/
public Safe(final PngRaw raw) {
this.origin = raw;
}
@Override | /*
* The MIT License (MIT)
*
* Copyright (C) 2023-2024 Fabrício Barros Cabral
*
* 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 NON-INFRINGEMENT. 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.fabriciofx.cactoos.pdf.image.png;
/**
* SafePngRaw: Safe decorator for a PNG image raw.
*
* @since 0.0.1
*/
public final class Safe implements Raw {
/**
* PNG file signature.
*/
private static final byte[] SIGNATURE = {
(byte) 137, 'P', 'N', 'G', '\r', '\n', 26, '\n',
};
/**
* Raw origin.
*/
private final PngRaw origin;
/**
* Ctor.
*
* @param raw Image raw
*/
public Safe(final PngRaw raw) {
this.origin = raw;
}
@Override | public Header header() throws Exception { | 3 | 2023-12-05 00:07:24+00:00 | 4k |
IzanagiCraft/message-format | src/main/java/com/izanagicraft/messages/translations/GlobalTranslations.java | [
{
"identifier": "StaticMessagePlaceholders",
"path": "src/main/java/com/izanagicraft/messages/placeholders/StaticMessagePlaceholders.java",
"snippet": "public class StaticMessagePlaceholders {\n\n private static MessagePlaceholderHandler placeholderHandler = new MessagePlaceholderHandler();\n\n //... | import com.izanagicraft.messages.placeholders.StaticMessagePlaceholders;
import com.izanagicraft.messages.strings.WrappedString;
import java.io.File;
import java.util.Locale;
import java.util.Map;
import java.util.Properties; | 2,794 | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.messages.translations;
/**
* message-format; com.izanagicraft.messages.translations:GlobalTranslations
* <p>
* Utility class for handling translations with placeholders.
* <p>
* Example usage:
* <pre>
* {@code
* GlobalTranslations.init(new File("en_US.properties"), new File("es_ES.properties"));
* String translatedText = GlobalTranslations.translate("greeting", "John");
* }
* </pre>
* <p>
* This class provides static methods to interact with the TranslationHandler,
* which manages translations for different locales with support for placeholders.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
public final class GlobalTranslations {
private static TranslationHandler translationHandler = new TranslationHandler();
// instantiation prevention
private GlobalTranslations() {
}
/**
* Gets the TranslationHandler instance.
*
* @return The TranslationHandler instance.
*/
public static TranslationHandler getTranslationHandler() {
return translationHandler;
}
/**
* Gets the map of translations for different locales.
*
* @return The map of translations with locale codes as keys and Properties objects as values.
*/
public static Map<String, Properties> getTranslations() {
return translationHandler.getTranslations();
}
/**
* Gets the fallback Properties object.
*
* @return The fallback Properties object.
*/
public static Properties getFallback() {
return translationHandler.getFallback();
}
/**
* Gets the default replacements used by the Formatter for placeholder substitution.
*
* @return A map of default replacements with String keys and Object values.
* These replacements are used by the {@link StaticMessagePlaceholders} class during text formatting.
*/
public static Map<String, Object> getDefaultReplacements() {
return translationHandler.getDefaultReplacements();
}
/**
* Load language properties from a file and process them.
*
* @param properties The properties object to load into.
* @param file The file to load properties from.
*/
private static void loadLang(Properties properties, File file) {
translationHandler.loadLang(properties, file);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param files Language properties files to load.
*/
public static void init(File... files) {
translationHandler.init(files);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param defaultReplacements Default replacement map for placeholders.
* @param files Language properties files to load.
*/
public static void init(Map<String, Object> defaultReplacements, File... files) {
translationHandler.init(defaultReplacements, files);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, Object... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, String... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(String key) {
return translationHandler.translate(key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, Object... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, String... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key) {
return translationHandler.translate(locale, key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param langName The language name to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/ | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.messages.translations;
/**
* message-format; com.izanagicraft.messages.translations:GlobalTranslations
* <p>
* Utility class for handling translations with placeholders.
* <p>
* Example usage:
* <pre>
* {@code
* GlobalTranslations.init(new File("en_US.properties"), new File("es_ES.properties"));
* String translatedText = GlobalTranslations.translate("greeting", "John");
* }
* </pre>
* <p>
* This class provides static methods to interact with the TranslationHandler,
* which manages translations for different locales with support for placeholders.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 13.12.2023
*/
public final class GlobalTranslations {
private static TranslationHandler translationHandler = new TranslationHandler();
// instantiation prevention
private GlobalTranslations() {
}
/**
* Gets the TranslationHandler instance.
*
* @return The TranslationHandler instance.
*/
public static TranslationHandler getTranslationHandler() {
return translationHandler;
}
/**
* Gets the map of translations for different locales.
*
* @return The map of translations with locale codes as keys and Properties objects as values.
*/
public static Map<String, Properties> getTranslations() {
return translationHandler.getTranslations();
}
/**
* Gets the fallback Properties object.
*
* @return The fallback Properties object.
*/
public static Properties getFallback() {
return translationHandler.getFallback();
}
/**
* Gets the default replacements used by the Formatter for placeholder substitution.
*
* @return A map of default replacements with String keys and Object values.
* These replacements are used by the {@link StaticMessagePlaceholders} class during text formatting.
*/
public static Map<String, Object> getDefaultReplacements() {
return translationHandler.getDefaultReplacements();
}
/**
* Load language properties from a file and process them.
*
* @param properties The properties object to load into.
* @param file The file to load properties from.
*/
private static void loadLang(Properties properties, File file) {
translationHandler.loadLang(properties, file);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param files Language properties files to load.
*/
public static void init(File... files) {
translationHandler.init(files);
}
/**
* Initialize the translations with default replacements and language files.
*
* @param defaultReplacements Default replacement map for placeholders.
* @param files Language properties files to load.
*/
public static void init(Map<String, Object> defaultReplacements, File... files) {
translationHandler.init(defaultReplacements, files);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, Object... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(String key, String... args) {
return translationHandler.translate(key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(String key) {
return translationHandler.translate(key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, Object... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key, String... args) {
return translationHandler.translate(locale, key, args);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param locale The locale to translate in.
* @param key The translation key.
* @return Translated and formatted text.
*/
public static String translate(Locale locale, String key) {
return translationHandler.translate(locale, key);
}
/**
* Translate a key using default replacements and fallback properties.
*
* @param langName The language name to translate in.
* @param key The translation key.
* @param args Arguments for placeholders.
* @return Translated and formatted text.
*/ | public static String translate(WrappedString langName, String key, Object... args) { | 1 | 2023-12-13 02:31:22+00:00 | 4k |
ibm-messaging/kafka-connect-xml-converter | src/test/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/XmlTransformationMapTest.java | [
{
"identifier": "ByteGenerators",
"path": "src/test/java/com/ibm/eventstreams/kafkaconnect/plugins/xml/testutils/ByteGenerators.java",
"snippet": "public class ByteGenerators {\n\n public static byte[] getXml(String testCaseId) {\n try {\n return Files.readAllBytes(FileGenerators.ge... | import com.ibm.eventstreams.kafkaconnect.plugins.xml.testutils.ConfigGenerators;
import com.ibm.eventstreams.kafkaconnect.plugins.xml.testutils.RecordGenerators;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
import java.util.Arrays;
import java.util.Collection;
import org.apache.kafka.connect.source.SourceRecord;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.xmlunit.builder.Input;
import org.xmlunit.builder.Input.Builder;
import com.ibm.eventstreams.kafkaconnect.plugins.xml.testutils.ByteGenerators; | 2,077 | /**
* Copyright 2023 IBM Corp. All Rights Reserved.
*
* 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.ibm.eventstreams.kafkaconnect.plugins.xml;
@RunWith(Parameterized.class)
public class XmlTransformationMapTest {
private final XmlTransformation<SourceRecord> transformer = new XmlTransformation<>();
private final String currentTestCase;
private final boolean ambiguousMap;
@Parameterized.Parameters
public static Collection<Object[]> testCases() {
return Arrays.asList(new Object[][] {
{ "000", false },
{ "001", true }, // uses attributes
{ "002", false },
{ "003", false },
{ "004", false },
{ "005", false },
{ "006", true }, // uses attributes
{ "007", false },
{ "008", false },
{ "009", false },
{ "010", true }, // uses maps
{ "011", true }, // uses maps
{ "012", true },
{ "013", false },
{ "014", false },
{ "015", false },
{ "016", false },
{ "017", false },
{ "018", true },
{ "019", true },
{ "020", true },
{ "021", true },
{ "022", true },
{ "023", true },
{ "024", false },
{ "025", true },
{ "026", false },
{ "027", false },
{ "028", true },
{ "029", true },
{ "030", true },
{ "031", true },
{ "032", true },
{ "033", true },
{ "034", true },
{ "035", true },
{ "036", true },
// { "037", true },
{ "038", true },
// { "039", false },
// { "040", true }
{ "043", true },
{ "044", false },
{ "045", false },
{ "046", false },
{ "049", false }
});
}
public XmlTransformationMapTest(String testCase, boolean ambiguousMap) {
this.currentTestCase = testCase;
this.ambiguousMap = ambiguousMap;
}
@After
public void cleanup() {
transformer.close();
}
@Test
public void map() { | /**
* Copyright 2023 IBM Corp. All Rights Reserved.
*
* 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.ibm.eventstreams.kafkaconnect.plugins.xml;
@RunWith(Parameterized.class)
public class XmlTransformationMapTest {
private final XmlTransformation<SourceRecord> transformer = new XmlTransformation<>();
private final String currentTestCase;
private final boolean ambiguousMap;
@Parameterized.Parameters
public static Collection<Object[]> testCases() {
return Arrays.asList(new Object[][] {
{ "000", false },
{ "001", true }, // uses attributes
{ "002", false },
{ "003", false },
{ "004", false },
{ "005", false },
{ "006", true }, // uses attributes
{ "007", false },
{ "008", false },
{ "009", false },
{ "010", true }, // uses maps
{ "011", true }, // uses maps
{ "012", true },
{ "013", false },
{ "014", false },
{ "015", false },
{ "016", false },
{ "017", false },
{ "018", true },
{ "019", true },
{ "020", true },
{ "021", true },
{ "022", true },
{ "023", true },
{ "024", false },
{ "025", true },
{ "026", false },
{ "027", false },
{ "028", true },
{ "029", true },
{ "030", true },
{ "031", true },
{ "032", true },
{ "033", true },
{ "034", true },
{ "035", true },
{ "036", true },
// { "037", true },
{ "038", true },
// { "039", false },
// { "040", true }
{ "043", true },
{ "044", false },
{ "045", false },
{ "046", false },
{ "049", false }
});
}
public XmlTransformationMapTest(String testCase, boolean ambiguousMap) {
this.currentTestCase = testCase;
this.ambiguousMap = ambiguousMap;
}
@After
public void cleanup() {
transformer.close();
}
@Test
public void map() { | transformer.configure(ConfigGenerators.defaultRootNoSchemasProps()); | 1 | 2023-12-11 13:56:48+00:00 | 4k |
BeansGalaxy/Beans-Backpacks-2 | forge/src/main/java/com/beansgalaxy/backpacks/network/NetworkPackages.java | [
{
"identifier": "Constants",
"path": "common/src/main/java/com/beansgalaxy/backpacks/Constants.java",
"snippet": "public class Constants {\n\n\tpublic static final String MOD_ID = \"beansbackpacks\";\n\tpublic static final String MOD_NAME = \"Beans' Backpacks\";\n\tpublic static final Logger LOG = Logge... | import com.beansgalaxy.backpacks.Constants;
import com.beansgalaxy.backpacks.network.client.ConfigureKeys2C;
import com.beansgalaxy.backpacks.network.client.SyncBackInventory2C;
import com.beansgalaxy.backpacks.network.client.SyncBackSlot2C;
import com.beansgalaxy.backpacks.network.client.SyncViewersPacket2C;
import com.beansgalaxy.backpacks.network.packages.CallBackInventory2S;
import com.beansgalaxy.backpacks.network.packages.CallBackSlot2S;
import com.beansgalaxy.backpacks.network.packages.SprintKeyPacket2S;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.network.ChannelBuilder;
import net.minecraftforge.network.PacketDistributor;
import net.minecraftforge.network.SimpleChannel; | 2,333 | package com.beansgalaxy.backpacks.network;
public class NetworkPackages {
public static SimpleChannel INSTANCE = ChannelBuilder.named(
new ResourceLocation(Constants.MOD_ID, "main"))
.serverAcceptedVersions(((status, version) -> true))
.clientAcceptedVersions(((status, version) -> true))
.networkProtocolVersion(1)
.simpleChannel();
public static void register() { | package com.beansgalaxy.backpacks.network;
public class NetworkPackages {
public static SimpleChannel INSTANCE = ChannelBuilder.named(
new ResourceLocation(Constants.MOD_ID, "main"))
.serverAcceptedVersions(((status, version) -> true))
.clientAcceptedVersions(((status, version) -> true))
.networkProtocolVersion(1)
.simpleChannel();
public static void register() { | SprintKeyPacket2S.register(); | 7 | 2023-12-14 21:55:00+00:00 | 4k |
CADIndie/Scout | src/main/java/pm/c7/scout/ScoutUtil.java | [
{
"identifier": "BaseBagItem",
"path": "src/main/java/pm/c7/scout/item/BaseBagItem.java",
"snippet": "@SuppressWarnings(\"deprecation\")\npublic class BaseBagItem extends TrinketItem {\n private static final String ITEMS_KEY = \"Items\";\n\n private final int slots;\n private final BagType type;\n... | import java.util.Optional;
import dev.emi.trinkets.api.SlotReference;
import dev.emi.trinkets.api.TrinketComponent;
import dev.emi.trinkets.api.TrinketsApi;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.SimpleInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtList;
import net.minecraft.util.Identifier;
import net.minecraft.util.Pair;
import pm.c7.scout.item.BaseBagItem;
import pm.c7.scout.item.BaseBagItem.BagType; | 2,661 | package pm.c7.scout;
public class ScoutUtil {
public static final Identifier SLOT_TEXTURE = new Identifier("scout", "textures/gui/slots.png");
| package pm.c7.scout;
public class ScoutUtil {
public static final Identifier SLOT_TEXTURE = new Identifier("scout", "textures/gui/slots.png");
| public static ItemStack findBagItem(PlayerEntity player, BaseBagItem.BagType type, boolean right) { | 1 | 2023-12-10 07:43:34+00:00 | 4k |
courage0916/mybatis-gain | src/main/java/com/gain/MybatisGainInterceptor.java | [
{
"identifier": "FillService",
"path": "src/main/java/com/gain/fill/FillService.java",
"snippet": "@Service\npublic class FillService {\n\n private final ListenerSupport listenerSupport;\n\n public FillService() {\n listenerSupport = ListenerSupport.getInstance();\n }\n\n public void ... | import com.gain.fill.FillService;
import com.gain.log.LogService;
import com.gain.safe.AllowUpdateTables;
import com.gain.safe.SafeService;
import jakarta.annotation.Resource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.stereotype.Component; | 2,179 | package com.gain;
/**
* Mybatis Gain(增益) 拦截器
* 主要实现一些需要额外的功能,如填充字段、新增 Mybatis Sql 日志
*/
@Component
@Intercepts({@Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class})})
public class MybatisGainInterceptor implements Interceptor {
@Resource
LogService logService;
@Resource
SafeService safeService;
// 关于该插件的配置 | package com.gain;
/**
* Mybatis Gain(增益) 拦截器
* 主要实现一些需要额外的功能,如填充字段、新增 Mybatis Sql 日志
*/
@Component
@Intercepts({@Signature(
type = Executor.class,
method = "update",
args = {MappedStatement.class, Object.class})})
public class MybatisGainInterceptor implements Interceptor {
@Resource
LogService logService;
@Resource
SafeService safeService;
// 关于该插件的配置 | private final AllowUpdateTables allowUpdateTables; | 2 | 2023-12-11 05:28:00+00:00 | 4k |
Viola-Siemens/Mod-Whitelist | src/main/java/com/hexagram2021/mod_whitelist/server/config/MWServerConfig.java | [
{
"identifier": "ModWhitelist",
"path": "src/main/java/com/hexagram2021/mod_whitelist/ModWhitelist.java",
"snippet": "public class ModWhitelist implements ModInitializer {\n\tpublic static final String MODID = \"mod_whitelist\";\n\tpublic static final String MOD_NAME = \"Mod Whitelist\";\n\tpublic stati... | import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hexagram2021.mod_whitelist.ModWhitelist;
import com.hexagram2021.mod_whitelist.common.utils.MWLogger;
import org.apache.commons.lang3.tuple.Pair;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.hexagram2021.mod_whitelist.ModWhitelist.MODID; | 1,932 | this.name = name;
this.value = value;
configValues.add(this);
}
@Override
public void checkValueRange() throws ConfigValueException {
}
@Override
public void parseAsValue(JsonElement element) {
this.value = element.getAsBoolean();
}
@Override
public String name() {
return this.name;
}
@Override
public Boolean value() {
return this.value;
}
}
public static final File filePath = new File("./config/");
private static final File configFile = new File(filePath + "/" + MODID + "-config.json");
private static final File readmeFile = new File(filePath + "/" + MODID + "-config-readme.md");
//WhiteLists
public static final BoolConfigValue USE_WHITELIST_ONLY = new BoolConfigValue("USE_WHITELIST_ONLY", false);
public static final ModIdListConfigValue CLIENT_MOD_NECESSARY = new ModIdListConfigValue("CLIENT_MOD_NECESSARY", MODID);
public static final ModIdListConfigValue CLIENT_MOD_WHITELIST = new ModIdListConfigValue("CLIENT_MOD_WHITELIST",
"fabric-api",
"fabric-api-base",
"fabric-api-lookup-api-v1",
"fabric-biome-api-v1",
"fabric-block-api-v1",
"fabric-block-view-api-v2",
"fabric-blockrenderlayer-v1",
"fabric-client-tags-api-v1",
"fabric-command-api-v1",
"fabric-command-api-v2",
"fabric-commands-v0",
"fabric-containers-v0",
"fabric-content-registries-v0",
"fabric-convention-tags-v1",
"fabric-crash-report-info-v1",
"fabric-data-generation-api-v1",
"fabric-dimensions-v1",
"fabric-entity-events-v1",
"fabric-events-interaction-v0",
"fabric-events-lifecycle-v0",
"fabric-game-rule-api-v1",
"fabric-item-api-v1",
"fabric-item-group-api-v1",
"fabric-key-binding-api-v1",
"fabric-keybindings-v0",
"fabric-lifecycle-events-v1",
"fabric-loot-api-v2",
"fabric-loot-tables-v1",
"fabric-message-api-v1",
"fabric-mining-level-api-v1",
"fabric-model-loading-api-v1",
"fabric-models-v0",
"fabric-networking-api-v1",
"fabric-networking-v0",
"fabric-object-builder-api-v1",
"fabric-particles-v1",
"fabric-recipe-api-v1",
"fabric-registry-sync-v0",
"fabric-renderer-api-v1",
"fabric-renderer-indigo",
"fabric-renderer-registries-v1",
"fabric-rendering-data-attachment-v1",
"fabric-rendering-fluids-v1",
"fabric-rendering-v0",
"fabric-rendering-v1",
"fabric-resource-conditions-api-v1",
"fabric-resource-loader-v0",
"fabric-screen-api-v1",
"fabric-screen-handler-api-v1",
"fabric-sound-api-v1",
"fabric-transfer-api-v1",
"fabric-transitive-access-wideners-v1",
"fabricloader",
"java", MODID);
public static final ModIdListConfigValue CLIENT_MOD_BLACKLIST = new ModIdListConfigValue("CLIENT_MOD_BLACKLIST", "aristois", "bleachhack", "meteor-client", "wurst");
public static List<Pair<String, MismatchType>> test(List<String> mods) {
List<Pair<String, MismatchType>> ret = Lists.newArrayList();
for(String mod: CLIENT_MOD_NECESSARY.value()) {
if(!mods.contains(mod)) {
ret.add(Pair.of(mod, MismatchType.UNINSTALLED_BUT_SHOULD_INSTALL));
}
}
if(USE_WHITELIST_ONLY.value()) {
for(String mod: mods) {
if(!CLIENT_MOD_WHITELIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
} else {
for(String mod: mods) {
if(CLIENT_MOD_BLACKLIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
}
return ret;
}
static {
lazyInit();
}
private static void lazyInit() {
try {
if (!filePath.exists() && !filePath.mkdir()) { | package com.hexagram2021.mod_whitelist.server.config;
public class MWServerConfig {
public interface IConfigValue<T extends Serializable> {
List<IConfigValue<?>> configValues = Lists.newArrayList();
String name();
T value();
void parseAsValue(JsonElement element);
void checkValueRange() throws ConfigValueException;
}
public static abstract class ListConfigValue<T extends Serializable> implements IConfigValue<ArrayList<T>> {
private final String name;
private final ArrayList<T> value;
@SafeVarargs
public ListConfigValue(String name, T... defaultValues) {
this(name, Arrays.stream(defaultValues).collect(Collectors.toCollection(Lists::newArrayList)));
configValues.add(this);
}
public ListConfigValue(String name, ArrayList<T> value) {
this.name = name;
this.value = value;
}
@Override
public void checkValueRange() throws ConfigValueException {
this.value.forEach(v -> {
if(!this.isValid(v)) {
throw new ConfigValueException(this.createExceptionDescription(v));
}
});
}
@Override
public void parseAsValue(JsonElement element) {
this.value.clear();
element.getAsJsonArray().asList().forEach(e -> this.value.add(this.parseAsElementValue(e)));
}
@Override
public String name() {
return this.name;
}
@Override
public ArrayList<T> value() {
return this.value;
}
protected abstract boolean isValid(T element);
protected abstract String createExceptionDescription(T element);
protected abstract T parseAsElementValue(JsonElement element);
}
public static class ModIdListConfigValue extends ListConfigValue<String> {
public ModIdListConfigValue(String name, String... defaultValues) {
super(name, defaultValues);
}
@SuppressWarnings("unused")
public ModIdListConfigValue(String name, ArrayList<String> value) {
super(name, value);
}
@Override
protected boolean isValid(String element) {
return Pattern.matches("[a-z\\d\\-._]+", element);
}
@Override
protected String createExceptionDescription(String element) {
return "\"%s\" is not a valid modid!".formatted(element);
}
@Override
protected String parseAsElementValue(JsonElement element) {
return element.getAsString();
}
}
public static class BoolConfigValue implements IConfigValue<Boolean> {
private final String name;
private boolean value;
public BoolConfigValue(String name, boolean value) {
this.name = name;
this.value = value;
configValues.add(this);
}
@Override
public void checkValueRange() throws ConfigValueException {
}
@Override
public void parseAsValue(JsonElement element) {
this.value = element.getAsBoolean();
}
@Override
public String name() {
return this.name;
}
@Override
public Boolean value() {
return this.value;
}
}
public static final File filePath = new File("./config/");
private static final File configFile = new File(filePath + "/" + MODID + "-config.json");
private static final File readmeFile = new File(filePath + "/" + MODID + "-config-readme.md");
//WhiteLists
public static final BoolConfigValue USE_WHITELIST_ONLY = new BoolConfigValue("USE_WHITELIST_ONLY", false);
public static final ModIdListConfigValue CLIENT_MOD_NECESSARY = new ModIdListConfigValue("CLIENT_MOD_NECESSARY", MODID);
public static final ModIdListConfigValue CLIENT_MOD_WHITELIST = new ModIdListConfigValue("CLIENT_MOD_WHITELIST",
"fabric-api",
"fabric-api-base",
"fabric-api-lookup-api-v1",
"fabric-biome-api-v1",
"fabric-block-api-v1",
"fabric-block-view-api-v2",
"fabric-blockrenderlayer-v1",
"fabric-client-tags-api-v1",
"fabric-command-api-v1",
"fabric-command-api-v2",
"fabric-commands-v0",
"fabric-containers-v0",
"fabric-content-registries-v0",
"fabric-convention-tags-v1",
"fabric-crash-report-info-v1",
"fabric-data-generation-api-v1",
"fabric-dimensions-v1",
"fabric-entity-events-v1",
"fabric-events-interaction-v0",
"fabric-events-lifecycle-v0",
"fabric-game-rule-api-v1",
"fabric-item-api-v1",
"fabric-item-group-api-v1",
"fabric-key-binding-api-v1",
"fabric-keybindings-v0",
"fabric-lifecycle-events-v1",
"fabric-loot-api-v2",
"fabric-loot-tables-v1",
"fabric-message-api-v1",
"fabric-mining-level-api-v1",
"fabric-model-loading-api-v1",
"fabric-models-v0",
"fabric-networking-api-v1",
"fabric-networking-v0",
"fabric-object-builder-api-v1",
"fabric-particles-v1",
"fabric-recipe-api-v1",
"fabric-registry-sync-v0",
"fabric-renderer-api-v1",
"fabric-renderer-indigo",
"fabric-renderer-registries-v1",
"fabric-rendering-data-attachment-v1",
"fabric-rendering-fluids-v1",
"fabric-rendering-v0",
"fabric-rendering-v1",
"fabric-resource-conditions-api-v1",
"fabric-resource-loader-v0",
"fabric-screen-api-v1",
"fabric-screen-handler-api-v1",
"fabric-sound-api-v1",
"fabric-transfer-api-v1",
"fabric-transitive-access-wideners-v1",
"fabricloader",
"java", MODID);
public static final ModIdListConfigValue CLIENT_MOD_BLACKLIST = new ModIdListConfigValue("CLIENT_MOD_BLACKLIST", "aristois", "bleachhack", "meteor-client", "wurst");
public static List<Pair<String, MismatchType>> test(List<String> mods) {
List<Pair<String, MismatchType>> ret = Lists.newArrayList();
for(String mod: CLIENT_MOD_NECESSARY.value()) {
if(!mods.contains(mod)) {
ret.add(Pair.of(mod, MismatchType.UNINSTALLED_BUT_SHOULD_INSTALL));
}
}
if(USE_WHITELIST_ONLY.value()) {
for(String mod: mods) {
if(!CLIENT_MOD_WHITELIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
} else {
for(String mod: mods) {
if(CLIENT_MOD_BLACKLIST.value().contains(mod)) {
ret.add(Pair.of(mod, MismatchType.INSTALLED_BUT_SHOULD_NOT_INSTALL));
}
}
}
return ret;
}
static {
lazyInit();
}
private static void lazyInit() {
try {
if (!filePath.exists() && !filePath.mkdir()) { | MWLogger.LOGGER.error("Could not mkdir " + filePath); | 1 | 2023-12-06 12:16:52+00:00 | 4k |
sinbad-navigator/erp-crm | system/src/main/java/com/ec/sys/service/ISysMenuService.java | [
{
"identifier": "TreeSelect",
"path": "common/src/main/java/com/ec/common/core/domain/TreeSelect.java",
"snippet": "public class TreeSelect implements Serializable {\n private static final long serialVersionUID = 1L;\n\n /**\n * 节点ID\n */\n private Long id;\n\n /**\n * 节点名称\n ... | import java.util.List;
import java.util.Set;
import com.ec.common.core.domain.TreeSelect;
import com.ec.common.core.domain.entity.SysMenu;
import com.ec.sys.domain.vo.RouterVo; | 3,018 | package com.ec.sys.service;
/**
* 菜单 业务层
*
* @author ec
*/
public interface ISysMenuService {
/**
* 根据用户查询系统菜单列表
*
* @param userId 用户ID
* @return 菜单列表
*/
public List<SysMenu> selectMenuList(Long userId);
/**
* 根据用户查询系统菜单列表
*
* @param menu 菜单信息
* @param userId 用户ID
* @return 菜单列表
*/
public List<SysMenu> selectMenuList(SysMenu menu, Long userId);
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
public Set<String> selectMenuPermsByUserId(Long userId);
/**
* 根据用户ID查询菜单树信息
*
* @param userId 用户ID
* @return 菜单列表
*/
public List<SysMenu> selectMenuTreeByUserId(Long userId);
/**
* 根据角色ID查询菜单树信息
*
* @param roleId 角色ID
* @return 选中菜单列表
*/
public List<Long> selectMenuListByRoleId(Long roleId);
/**
* 构建前端路由所需要的菜单
*
* @param menus 菜单列表
* @return 路由列表
*/ | package com.ec.sys.service;
/**
* 菜单 业务层
*
* @author ec
*/
public interface ISysMenuService {
/**
* 根据用户查询系统菜单列表
*
* @param userId 用户ID
* @return 菜单列表
*/
public List<SysMenu> selectMenuList(Long userId);
/**
* 根据用户查询系统菜单列表
*
* @param menu 菜单信息
* @param userId 用户ID
* @return 菜单列表
*/
public List<SysMenu> selectMenuList(SysMenu menu, Long userId);
/**
* 根据用户ID查询权限
*
* @param userId 用户ID
* @return 权限列表
*/
public Set<String> selectMenuPermsByUserId(Long userId);
/**
* 根据用户ID查询菜单树信息
*
* @param userId 用户ID
* @return 菜单列表
*/
public List<SysMenu> selectMenuTreeByUserId(Long userId);
/**
* 根据角色ID查询菜单树信息
*
* @param roleId 角色ID
* @return 选中菜单列表
*/
public List<Long> selectMenuListByRoleId(Long roleId);
/**
* 构建前端路由所需要的菜单
*
* @param menus 菜单列表
* @return 路由列表
*/ | public List<RouterVo> buildMenus(List<SysMenu> menus); | 2 | 2023-12-07 14:23:12+00:00 | 4k |
SteveKunG/MinecartSpawnerRevived | src/main/java/com/stevekung/msr/mixin/client/MixinMinecartSpawner.java | [
{
"identifier": "MinecartSpawnerRevived",
"path": "src/main/java/com/stevekung/msr/MinecartSpawnerRevived.java",
"snippet": "public class MinecartSpawnerRevived\n{\n public static final String MOD_ID = \"minecart_spawner_revived\";\n public static final Logger LOGGER = LogUtils.getLogger();\n\n ... | import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.stevekung.msr.MinecartSpawnerRevived;
import com.stevekung.msr.MinecartSpawnerRevivedClient;
import com.stevekung.msr.client.renderer.SpawnerClientTicker;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.entity.vehicle.MinecartSpawner;
import net.minecraft.world.level.BaseSpawner;
import net.minecraft.world.level.Level; | 1,672 | package com.stevekung.msr.mixin.client;
@Mixin(MinecartSpawner.class)
public abstract class MixinMinecartSpawner extends AbstractMinecart
{
MixinMinecartSpawner()
{
super(null, null);
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>Re-send a request SpawnData packet to the server when modifying spawner minecart data.</p>
*/
@Inject(method = "readAdditionalSaveData", at = @At("TAIL"))
private void msr$resendSpawnDataRequestOnLoad(CompoundTag compound, CallbackInfo info)
{
if (ClientPlayNetworking.canSend(MinecartSpawnerRevived.REQUEST_SPAWNDATA))
{
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>When entity recreated from a packet, send a request SpawnData packet to the server.</p>
*/
@Override
public void recreateFromPacket(ClientboundAddEntityPacket packet)
{
super.recreateFromPacket(packet);
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-66894">MC-66894</a></p>
*
* <p>Fix Spawner Minecart particles position.</p>
*/
@Redirect(method = "method_31554", at = @At(value = "INVOKE", target = "net/minecraft/world/level/BaseSpawner.clientTick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;)V"))
private void msr$createClientTicker(BaseSpawner spawner, Level level, BlockPos pos)
{ | package com.stevekung.msr.mixin.client;
@Mixin(MinecartSpawner.class)
public abstract class MixinMinecartSpawner extends AbstractMinecart
{
MixinMinecartSpawner()
{
super(null, null);
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>Re-send a request SpawnData packet to the server when modifying spawner minecart data.</p>
*/
@Inject(method = "readAdditionalSaveData", at = @At("TAIL"))
private void msr$resendSpawnDataRequestOnLoad(CompoundTag compound, CallbackInfo info)
{
if (ClientPlayNetworking.canSend(MinecartSpawnerRevived.REQUEST_SPAWNDATA))
{
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>When entity recreated from a packet, send a request SpawnData packet to the server.</p>
*/
@Override
public void recreateFromPacket(ClientboundAddEntityPacket packet)
{
super.recreateFromPacket(packet);
MinecartSpawnerRevivedClient.sendSpawnDataRequest(this.getId());
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-66894">MC-66894</a></p>
*
* <p>Fix Spawner Minecart particles position.</p>
*/
@Redirect(method = "method_31554", at = @At(value = "INVOKE", target = "net/minecraft/world/level/BaseSpawner.clientTick(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;)V"))
private void msr$createClientTicker(BaseSpawner spawner, Level level, BlockPos pos)
{ | ((SpawnerClientTicker)spawner).msr$clientTick(level, MinecartSpawner.class.cast(this)); | 2 | 2023-12-08 06:53:56+00:00 | 4k |
FRC8806/frcBT_2023 | src/main/java/frc/robot/commands/auto/TrackingPath.java | [
{
"identifier": "SwerveConstants",
"path": "src/main/java/frc/robot/constants/SwerveConstants.java",
"snippet": "public class SwerveConstants {\n //The CAN IDs\n //Throttle\n public static final int A_THROTTLE_ID = 5;\n public static final int B_THROTTLE_ID = 2;\n public static final int C_THROTTLE... | import com.pathplanner.lib.PathPlanner;
import com.pathplanner.lib.commands.PPSwerveControllerCommand;
import edu.wpi.first.math.controller.PIDController;
import frc.robot.constants.SwerveConstants;
import frc.robot.subsystems.chassis.DriveTrain; | 2,346 | // ___________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________
// 88 88 88 88 00 00 66
// 88 88 88 88 00 00 66 ________________________
// 88 88 88 88 00 00 66
// 8888888888888888 8888888888888888 00 00 6666666666666666 _____________
// 88 88 88 88 00 00 66 66
// 88 88 88 88 00 00 66 66 _____________________
// 88 88 88 88 00 00 66 66 ________________________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________
// __________________________ __________
package frc.robot.commands.auto;
public class TrackingPath extends PPSwerveControllerCommand{
public TrackingPath(DriveTrain driveTrain,String pathName) {
super( | // ___________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ___________
// 88 88 88 88 00 00 66
// 88 88 88 88 00 00 66 ________________________
// 88 88 88 88 00 00 66
// 8888888888888888 8888888888888888 00 00 6666666666666666 _____________
// 88 88 88 88 00 00 66 66
// 88 88 88 88 00 00 66 66 _____________________
// 88 88 88 88 00 00 66 66 ________________________
// 8888888888888888 8888888888888888 0000000000000000 6666666666666666 ____________________
// __________________________ __________
package frc.robot.commands.auto;
public class TrackingPath extends PPSwerveControllerCommand{
public TrackingPath(DriveTrain driveTrain,String pathName) {
super( | PathPlanner.loadPath(pathName, SwerveConstants.kMaxVelocityMetersPerSecond, SwerveConstants.kMaxAccelerationMetersPerSecond), | 0 | 2023-12-13 11:38:11+00:00 | 4k |
applepi-2067/2023_Pure_Swerve | src/main/java/frc/robot/subsystems/SteerMotor.java | [
{
"identifier": "Conversions",
"path": "src/main/java/frc/robot/utils/Conversions.java",
"snippet": "public class Conversions {\n public static double RPMToTicksPer100ms(double RPM, double ticksPerRev) {\n return RPM * ticksPerRev / (60.0 * 10.0);\n }\n\n public static double ticksPer100... | import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.SupplyCurrentLimitConfiguration;
import com.ctre.phoenix.motorcontrol.TalonFXControlMode;
import com.ctre.phoenix.motorcontrol.TalonFXFeedbackDevice;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX;
import com.ctre.phoenix.sensors.CANCoder;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.utils.Conversions;
import frc.robot.utils.Gains; | 1,893 | package frc.robot.subsystems;
public class SteerMotor {
private final WPI_TalonFX m_motor;
private final CANCoder m_canCoder;
// Motor settings.
private static final boolean ENABLE_CURRENT_LIMIT = true;
private static final double CONTINUOUS_CURRENT_LIMIT_AMPS = 55.0;
private static final double TRIGGER_THRESHOLD_LIMIT_AMPS = 60.0;
private static final double TRIGGER_THRESHOLD_TIME_SECONDS = 0.5;
private static final double PERCENT_DEADBAND = 0.001;
// Conversion constants.
private static final double TICKS_PER_REV = 2048.0;
private static final double GEAR_RATIO = 150.0 / 7.0;
// PID.
private static final int K_TIMEOUT_MS = 10;
private static final int K_PID_LOOP = 0;
private static final int K_PID_SLOT = 0;
private static final Gains PID_GAINS = new Gains(0.5, 0.0, 1.0);
private static final int CRUISE_VELOCITY_TICKS_PER_100MS = 20_000;
private static final int MAX_ACCEL_TICKS_PER_100MS_PER_SEC = CRUISE_VELOCITY_TICKS_PER_100MS * 2;
// For debugging.
private int canID;
private double wheelZeroOffsetDegrees;
public SteerMotor(int canID, int canCoderID, double wheelZeroOffsetDegrees, boolean invertMotor) {
this.canID = canID;
this.wheelZeroOffsetDegrees = wheelZeroOffsetDegrees;
// Motor.
m_motor = new WPI_TalonFX(canID);
m_motor.configFactoryDefault();
m_motor.setInverted(invertMotor);
// Coast allows for easier wheel offset tuning.
// Note that brake mode isn't neeeded b/c pid loop runs in background continuously.
m_motor.setNeutralMode(NeutralMode.Coast);
// Limit current going to motor.
SupplyCurrentLimitConfiguration talonCurrentLimit = new SupplyCurrentLimitConfiguration(
ENABLE_CURRENT_LIMIT, CONTINUOUS_CURRENT_LIMIT_AMPS,
TRIGGER_THRESHOLD_LIMIT_AMPS, TRIGGER_THRESHOLD_TIME_SECONDS
);
m_motor.configSupplyCurrentLimit(talonCurrentLimit);
// Seed encoder w/ abs encoder (CAN Coder reading) + wheel zero offset.
m_canCoder = new CANCoder(canCoderID);
| package frc.robot.subsystems;
public class SteerMotor {
private final WPI_TalonFX m_motor;
private final CANCoder m_canCoder;
// Motor settings.
private static final boolean ENABLE_CURRENT_LIMIT = true;
private static final double CONTINUOUS_CURRENT_LIMIT_AMPS = 55.0;
private static final double TRIGGER_THRESHOLD_LIMIT_AMPS = 60.0;
private static final double TRIGGER_THRESHOLD_TIME_SECONDS = 0.5;
private static final double PERCENT_DEADBAND = 0.001;
// Conversion constants.
private static final double TICKS_PER_REV = 2048.0;
private static final double GEAR_RATIO = 150.0 / 7.0;
// PID.
private static final int K_TIMEOUT_MS = 10;
private static final int K_PID_LOOP = 0;
private static final int K_PID_SLOT = 0;
private static final Gains PID_GAINS = new Gains(0.5, 0.0, 1.0);
private static final int CRUISE_VELOCITY_TICKS_PER_100MS = 20_000;
private static final int MAX_ACCEL_TICKS_PER_100MS_PER_SEC = CRUISE_VELOCITY_TICKS_PER_100MS * 2;
// For debugging.
private int canID;
private double wheelZeroOffsetDegrees;
public SteerMotor(int canID, int canCoderID, double wheelZeroOffsetDegrees, boolean invertMotor) {
this.canID = canID;
this.wheelZeroOffsetDegrees = wheelZeroOffsetDegrees;
// Motor.
m_motor = new WPI_TalonFX(canID);
m_motor.configFactoryDefault();
m_motor.setInverted(invertMotor);
// Coast allows for easier wheel offset tuning.
// Note that brake mode isn't neeeded b/c pid loop runs in background continuously.
m_motor.setNeutralMode(NeutralMode.Coast);
// Limit current going to motor.
SupplyCurrentLimitConfiguration talonCurrentLimit = new SupplyCurrentLimitConfiguration(
ENABLE_CURRENT_LIMIT, CONTINUOUS_CURRENT_LIMIT_AMPS,
TRIGGER_THRESHOLD_LIMIT_AMPS, TRIGGER_THRESHOLD_TIME_SECONDS
);
m_motor.configSupplyCurrentLimit(talonCurrentLimit);
// Seed encoder w/ abs encoder (CAN Coder reading) + wheel zero offset.
m_canCoder = new CANCoder(canCoderID);
| double initPositionTicks = Conversions.degreesToTicks( | 0 | 2023-12-13 02:33:42+00:00 | 4k |
ganeshbabugb/NASC-CMS | src/main/java/com/nasc/application/data/components/CreateBloodGroupCrud.java | [
{
"identifier": "BloodGroupEntity",
"path": "src/main/java/com/nasc/application/data/core/BloodGroupEntity.java",
"snippet": "@Entity\n@Data\n@Table(name = \"t_blood_groups\")\npublic class BloodGroupEntity implements BaseEntity {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n pr... | import com.flowingcode.vaadin.addons.fontawesome.FontAwesome;
import com.nasc.application.data.core.BloodGroupEntity;
import com.nasc.application.services.BloodGroupService;
import com.nasc.application.services.dataprovider.GenericDataProvider;
import com.nasc.application.utils.NotificationUtils;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.crud.BinderCrudEditor;
import com.vaadin.flow.component.crud.Crud;
import com.vaadin.flow.component.crud.CrudEditor;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.provider.Query;
import com.vaadin.flow.spring.annotation.UIScope;
import com.vaadin.flow.theme.lumo.LumoIcon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import software.xdev.vaadin.grid_exporter.GridExporter;
import software.xdev.vaadin.grid_exporter.column.ColumnConfigurationBuilder; | 2,803 | package com.nasc.application.data.components;
@Component
@UIScope
public class CreateBloodGroupCrud extends VerticalLayout {
private final String EDIT_COLUMN = "vaadin-crud-edit-column";
private final BloodGroupService service;
private final Crud<BloodGroupEntity> crud;
@Autowired
public CreateBloodGroupCrud(BloodGroupService service) {
this.service = service;
crud = new Crud<>(BloodGroupEntity.class, createEditor());
createGrid();
setupDataProvider();
HorizontalLayout horizontalLayout = new HorizontalLayout();
Button exportButton = new Button(
"Export",
FontAwesome.Solid.FILE_EXPORT.create(),
e -> {
int size = crud.getDataProvider().size(new Query<>());
if (size > 0) {
String fileName = "Blood Group";
GridExporter.newWithDefaults(crud.getGrid())
//Removing Edit Column For Export
.withColumnFilter(stateEntityColumn -> !stateEntityColumn.getKey().equals(EDIT_COLUMN))
.withFileName(fileName)
.withColumnConfigurationBuilder(new ColumnConfigurationBuilder())
.open();
}
}
);
exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
horizontalLayout.setWidthFull();
horizontalLayout.setJustifyContentMode(JustifyContentMode.END);
horizontalLayout.setAlignItems(Alignment.CENTER);
horizontalLayout.add(exportButton);
Button newItemBtn = new Button("Create New Blood Group", LumoIcon.PLUS.create());
newItemBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
crud.setNewButton(newItemBtn);
setAlignItems(Alignment.STRETCH);
expand(crud);
setSizeFull();
add(horizontalLayout, crud);
}
private CrudEditor<BloodGroupEntity> createEditor() {
TextField field = new TextField("Blood Group");
FormLayout form = new FormLayout(field);
form.setMaxWidth("480px");
form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1),
new FormLayout.ResponsiveStep("30em", 2));
Binder<BloodGroupEntity> binder = new Binder<>(BloodGroupEntity.class);
binder.forField(field).asRequired().bind(BloodGroupEntity::getName, BloodGroupEntity::setName);
return new BinderCrudEditor<>(binder, form);
}
private void createGrid() {
Grid<BloodGroupEntity> grid = crud.getGrid();
grid.removeColumnByKey("id");
grid.getColumnByKey(EDIT_COLUMN).setHeader("Edit");
grid.getColumnByKey(EDIT_COLUMN).setWidth("100px");
grid.getColumnByKey(EDIT_COLUMN).setResizable(false);
}
private void setupDataProvider() { | package com.nasc.application.data.components;
@Component
@UIScope
public class CreateBloodGroupCrud extends VerticalLayout {
private final String EDIT_COLUMN = "vaadin-crud-edit-column";
private final BloodGroupService service;
private final Crud<BloodGroupEntity> crud;
@Autowired
public CreateBloodGroupCrud(BloodGroupService service) {
this.service = service;
crud = new Crud<>(BloodGroupEntity.class, createEditor());
createGrid();
setupDataProvider();
HorizontalLayout horizontalLayout = new HorizontalLayout();
Button exportButton = new Button(
"Export",
FontAwesome.Solid.FILE_EXPORT.create(),
e -> {
int size = crud.getDataProvider().size(new Query<>());
if (size > 0) {
String fileName = "Blood Group";
GridExporter.newWithDefaults(crud.getGrid())
//Removing Edit Column For Export
.withColumnFilter(stateEntityColumn -> !stateEntityColumn.getKey().equals(EDIT_COLUMN))
.withFileName(fileName)
.withColumnConfigurationBuilder(new ColumnConfigurationBuilder())
.open();
}
}
);
exportButton.addThemeVariants(ButtonVariant.LUMO_SMALL);
horizontalLayout.setWidthFull();
horizontalLayout.setJustifyContentMode(JustifyContentMode.END);
horizontalLayout.setAlignItems(Alignment.CENTER);
horizontalLayout.add(exportButton);
Button newItemBtn = new Button("Create New Blood Group", LumoIcon.PLUS.create());
newItemBtn.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
crud.setNewButton(newItemBtn);
setAlignItems(Alignment.STRETCH);
expand(crud);
setSizeFull();
add(horizontalLayout, crud);
}
private CrudEditor<BloodGroupEntity> createEditor() {
TextField field = new TextField("Blood Group");
FormLayout form = new FormLayout(field);
form.setMaxWidth("480px");
form.setResponsiveSteps(new FormLayout.ResponsiveStep("0", 1),
new FormLayout.ResponsiveStep("30em", 2));
Binder<BloodGroupEntity> binder = new Binder<>(BloodGroupEntity.class);
binder.forField(field).asRequired().bind(BloodGroupEntity::getName, BloodGroupEntity::setName);
return new BinderCrudEditor<>(binder, form);
}
private void createGrid() {
Grid<BloodGroupEntity> grid = crud.getGrid();
grid.removeColumnByKey("id");
grid.getColumnByKey(EDIT_COLUMN).setHeader("Edit");
grid.getColumnByKey(EDIT_COLUMN).setWidth("100px");
grid.getColumnByKey(EDIT_COLUMN).setResizable(false);
}
private void setupDataProvider() { | GenericDataProvider<BloodGroupEntity> genericDataProvider = | 2 | 2023-12-10 18:07:28+00:00 | 4k |
Viola-Siemens/StellarForge | src/main/java/com/hexagram2021/stellarforge/common/register/SFBlocks.java | [
{
"identifier": "PillarBlock",
"path": "src/main/java/com/hexagram2021/stellarforge/common/block/PillarBlock.java",
"snippet": "@SuppressWarnings(\"deprecation\")\npublic class PillarBlock extends RotatedPillarBlock {\n\tpublic static final BooleanProperty HEAD = SFBlockStateProperties.HEAD;\n\tpublic s... | import com.google.common.collect.ImmutableList;
import com.hexagram2021.stellarforge.common.block.PillarBlock;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.*;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.SlabType;
import net.minecraft.world.level.material.MapColor;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
import org.apache.commons.lang3.tuple.Pair;
import java.util.function.Function;
import java.util.function.Supplier;
import static com.hexagram2021.stellarforge.StellarForge.MODID;
import static com.hexagram2021.stellarforge.common.util.RegistryHelper.getRegistryName; | 2,150 | package com.hexagram2021.stellarforge.common.register;
public final class SFBlocks {
public static final DeferredRegister<Block> REGISTER = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
public static final class Bricks {
public static final DecorBlockEntry MOSSY_BRICKS = new DecorBlockEntry("mossy_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_BRICKS = new DecorBlockEntry("cracked_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_BRICKS = new BlockEntry<>("chiseled_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_NETHER_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_NETHER_BRICKS, SFBlocks::toItem);
private Bricks() {
}
private static void init() {
}
}
public static final class Igneous {
public static final DecorBlockEntry ANDESITE_BRICKS = new DecorBlockEntry("andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_ANDESITE_BRICKS = new DecorBlockEntry("mossy_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_ANDESITE_BRICKS = new BlockEntry<>("chiseled_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_ANDESITE_BRICKS = new DecorBlockEntry("cracked_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry DIORITE_BRICKS = new DecorBlockEntry("diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_DIORITE_BRICKS = new DecorBlockEntry("mossy_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_DIORITE_BRICKS = new BlockEntry<>("chiseled_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DIORITE_BRICKS = new DecorBlockEntry("cracked_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry GRANITE_BRICKS = new DecorBlockEntry("granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_GRANITE_BRICKS = new DecorBlockEntry("mossy_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_GRANITE_BRICKS = new BlockEntry<>("chiseled_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_GRANITE_BRICKS = new DecorBlockEntry("cracked_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
private Igneous() {
}
private static void init() {
}
}
public static final class Stone {
//vanilla
public static final DecorBlockEntry CRACKED_STONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_STONE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry DEEPSLATE = DecorBlockEntry.createFromFull(Blocks.DEEPSLATE, SFBlocks::toItem);
public static final BlockEntry<ButtonBlock> DEEPSLATE_BUTTON = new BlockEntry<>("deepslate_button", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BUTTON), props -> new ButtonBlock(props, SFBlockSetTypes.DEEPSLATE, 20, false), SFBlocks::toItem);
public static final BlockEntry<PressurePlateBlock> DEEPSLATE_PRESSURE_PLATE = new BlockEntry<>("deepslate_pressure_plate", () -> BlockBehaviour.Properties.copy(Blocks.STONE_PRESSURE_PLATE), props -> new PressurePlateBlock(PressurePlateBlock.Sensitivity.MOBS, props, SFBlockSetTypes.DEEPSLATE), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_TILES = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_TILES, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_POLISHED_BLACKSTONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS, SFBlocks::toItem);
//blackstone
public static final DecorBlockEntry COBBLED_BLACKSTONE = new DecorBlockEntry("cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_COBBLED_BLACKSTONE = new DecorBlockEntry("mossy_cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry SMOOTH_BLACKSTONE = new DecorBlockEntry("smooth_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); | package com.hexagram2021.stellarforge.common.register;
public final class SFBlocks {
public static final DeferredRegister<Block> REGISTER = DeferredRegister.create(ForgeRegistries.BLOCKS, MODID);
public static final class Bricks {
public static final DecorBlockEntry MOSSY_BRICKS = new DecorBlockEntry("mossy_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_BRICKS = new DecorBlockEntry("cracked_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_BRICKS = new BlockEntry<>("chiseled_bricks", () -> BlockBehaviour.Properties.copy(Blocks.BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_NETHER_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_NETHER_BRICKS, SFBlocks::toItem);
private Bricks() {
}
private static void init() {
}
}
public static final class Igneous {
public static final DecorBlockEntry ANDESITE_BRICKS = new DecorBlockEntry("andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_ANDESITE_BRICKS = new DecorBlockEntry("mossy_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_ANDESITE_BRICKS = new BlockEntry<>("chiseled_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_ANDESITE_BRICKS = new DecorBlockEntry("cracked_andesite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry DIORITE_BRICKS = new DecorBlockEntry("diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_DIORITE_BRICKS = new DecorBlockEntry("mossy_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_DIORITE_BRICKS = new BlockEntry<>("chiseled_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DIORITE_BRICKS = new DecorBlockEntry("cracked_diorite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry GRANITE_BRICKS = new DecorBlockEntry("granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BRICKS), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_GRANITE_BRICKS = new DecorBlockEntry("mossy_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.MOSSY_STONE_BRICKS), SFBlocks::toItem);
public static final BlockEntry<Block> CHISELED_GRANITE_BRICKS = new BlockEntry<>("chiseled_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CHISELED_STONE_BRICKS), Block::new, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_GRANITE_BRICKS = new DecorBlockEntry("cracked_granite_bricks", () -> BlockBehaviour.Properties.copy(Blocks.CRACKED_STONE_BRICKS), SFBlocks::toItem);
private Igneous() {
}
private static void init() {
}
}
public static final class Stone {
//vanilla
public static final DecorBlockEntry CRACKED_STONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_STONE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry DEEPSLATE = DecorBlockEntry.createFromFull(Blocks.DEEPSLATE, SFBlocks::toItem);
public static final BlockEntry<ButtonBlock> DEEPSLATE_BUTTON = new BlockEntry<>("deepslate_button", () -> BlockBehaviour.Properties.copy(Blocks.STONE_BUTTON), props -> new ButtonBlock(props, SFBlockSetTypes.DEEPSLATE, 20, false), SFBlocks::toItem);
public static final BlockEntry<PressurePlateBlock> DEEPSLATE_PRESSURE_PLATE = new BlockEntry<>("deepslate_pressure_plate", () -> BlockBehaviour.Properties.copy(Blocks.STONE_PRESSURE_PLATE), props -> new PressurePlateBlock(PressurePlateBlock.Sensitivity.MOBS, props, SFBlockSetTypes.DEEPSLATE), SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_BRICKS, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_DEEPSLATE_TILES = DecorBlockEntry.createFromFull(Blocks.CRACKED_DEEPSLATE_TILES, SFBlocks::toItem);
public static final DecorBlockEntry CRACKED_POLISHED_BLACKSTONE_BRICKS = DecorBlockEntry.createFromFull(Blocks.CRACKED_POLISHED_BLACKSTONE_BRICKS, SFBlocks::toItem);
//blackstone
public static final DecorBlockEntry COBBLED_BLACKSTONE = new DecorBlockEntry("cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry MOSSY_COBBLED_BLACKSTONE = new DecorBlockEntry("mossy_cobbled_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem);
public static final DecorBlockEntry SMOOTH_BLACKSTONE = new DecorBlockEntry("smooth_blackstone", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), SFBlocks::toItem); | public static final BlockEntry<PillarBlock> POLISHED_BLACKSTONE_PILLAR = new BlockEntry<>("polished_blackstone_pillar", () -> BlockBehaviour.Properties.copy(Blocks.BLACKSTONE), PillarBlock::new, SFBlocks::toItem); | 0 | 2023-12-10 07:20:43+00:00 | 4k |
deepcloudlabs/dcl350-2023-dec-04 | hr-core-subdomain/src/com/example/hr/application/business/StandardHrApplication.java | [
{
"identifier": "HrApplication",
"path": "hr-core-subdomain/src/com/example/hr/application/HrApplication.java",
"snippet": "@Port(PortType.DRIVING)\npublic interface HrApplication {\n\tOptional<Employee> getEmployee(TcKimlikNo identity);\n\tEmployee hireEmployee(Employee employee);\n\tEmployee fireEmplo... | import java.util.Optional;
import com.example.ddd.Application;
import com.example.hr.application.HrApplication;
import com.example.hr.application.business.event.EmployeeFiredEvent;
import com.example.hr.application.business.event.EmployeeHiredEvent;
import com.example.hr.application.business.event.HrEvent;
import com.example.hr.application.business.exception.EmployeeNotFoundException;
import com.example.hr.application.business.exception.ExistingEmployeeException;
import com.example.hr.domain.Employee;
import com.example.hr.domain.TcKimlikNo;
import com.example.hr.infrastructure.EventPublisher;
import com.example.hr.repository.EmployeeRepository; | 3,066 | package com.example.hr.application.business;
@Application(port=HrApplication.class)
public class StandardHrApplication implements HrApplication {
private final EmployeeRepository employeeRepository;
private final EventPublisher<HrEvent> eventPublisher;
public StandardHrApplication(EmployeeRepository employeeRepository, EventPublisher<HrEvent> eventPublisher) {
this.employeeRepository = employeeRepository;
this.eventPublisher = eventPublisher;
}
@Override
public Optional<Employee> getEmployee(TcKimlikNo identity) {
return employeeRepository.findEmployeeByIdentity(identity);
}
@Override
public Employee hireEmployee(Employee employee) {
var identity = employee.getIdentity();
if(employeeRepository.existsByIdentity(identity)) | package com.example.hr.application.business;
@Application(port=HrApplication.class)
public class StandardHrApplication implements HrApplication {
private final EmployeeRepository employeeRepository;
private final EventPublisher<HrEvent> eventPublisher;
public StandardHrApplication(EmployeeRepository employeeRepository, EventPublisher<HrEvent> eventPublisher) {
this.employeeRepository = employeeRepository;
this.eventPublisher = eventPublisher;
}
@Override
public Optional<Employee> getEmployee(TcKimlikNo identity) {
return employeeRepository.findEmployeeByIdentity(identity);
}
@Override
public Employee hireEmployee(Employee employee) {
var identity = employee.getIdentity();
if(employeeRepository.existsByIdentity(identity)) | throw new ExistingEmployeeException("Employee already exists",identity); | 5 | 2023-12-05 09:46:09+00:00 | 4k |
nilsgenge/finite-state-machine-visualizer | src/gui/GuiHandler.java | [
{
"identifier": "MouseInputs",
"path": "src/inputs/MouseInputs.java",
"snippet": "public class MouseInputs implements MouseListener {\n\n\tprivate Boolean m1Pressed = false; // left mouse button\n\tprivate Boolean m2Pressed = false; // right mouse button\n\tprivate Boolean m3Pressed = false; // middle m... | import java.awt.Font;
import java.awt.Graphics2D;
import inputs.MouseInputs;
import main.*;
import utilz.colortable;
import workspace.ToolHandler; | 2,381 | package gui;
public class GuiHandler {
private Main main;
public Toolbar tb;
public Sidebar sb;
private MouseInputs m;
private ToolHandler th;
private int screenWidth;
private int screenHeight;
public GuiHandler(Main main, MouseInputs m, ToolHandler th) {
this.main = main;
this.m = m;
this.th = th;
tb = new Toolbar(this, m, th);
sb = new Sidebar(this);
screenWidth = main.s.getScreenWidth();
screenHeight = main.s.getScreenHeight();
}
public void renderGui(Graphics2D g2) {
sb.render(g2);
tb.render(g2);
g2.setFont(new Font("Monospaced", Font.PLAIN, 12)); | package gui;
public class GuiHandler {
private Main main;
public Toolbar tb;
public Sidebar sb;
private MouseInputs m;
private ToolHandler th;
private int screenWidth;
private int screenHeight;
public GuiHandler(Main main, MouseInputs m, ToolHandler th) {
this.main = main;
this.m = m;
this.th = th;
tb = new Toolbar(this, m, th);
sb = new Sidebar(this);
screenWidth = main.s.getScreenWidth();
screenHeight = main.s.getScreenHeight();
}
public void renderGui(Graphics2D g2) {
sb.render(g2);
tb.render(g2);
g2.setFont(new Font("Monospaced", Font.PLAIN, 12)); | g2.setColor(colortable.TEXT); | 1 | 2023-12-12 20:43:41+00:00 | 4k |
gaetanBloch/jhlite-gateway | src/test/java/com/mycompany/myapp/shared/pagination/infrastructure/secondary/JhipsterSampleApplicationPagesTest.java | [
{
"identifier": "MissingMandatoryValueException",
"path": "src/main/java/com/mycompany/myapp/shared/error/domain/MissingMandatoryValueException.java",
"snippet": "public class MissingMandatoryValueException extends AssertionException {\n\n private MissingMandatoryValueException(String field, String mes... | import static org.assertj.core.api.Assertions.*;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import com.mycompany.myapp.UnitTest;
import com.mycompany.myapp.shared.error.domain.MissingMandatoryValueException;
import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPage;
import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPageable; | 2,141 | package com.mycompany.myapp.shared.pagination.infrastructure.secondary;
@UnitTest
class JhipsterSampleApplicationPagesTest {
@Test
void shouldNotBuildPageableFromNullJhipsterSampleApplicationPageable() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("pagination");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageable() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination());
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.unsorted());
}
@Test
void shouldNotBuildWithoutSort() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(pagination(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("sort");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageableAndSort() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination(), Sort.by("dummy"));
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.by("dummy"));
}
private JhipsterSampleApplicationPageable pagination() {
return new JhipsterSampleApplicationPageable(2, 15);
}
@Test
void shouldNotConvertFromSpringPageWithoutSpringPage() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null, source -> source))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("springPage");
}
@Test
void shouldNotConvertFromSpringPageWithoutMapper() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(springPage(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("mapper");
}
@Test
void shouldConvertFromSpringPage() { | package com.mycompany.myapp.shared.pagination.infrastructure.secondary;
@UnitTest
class JhipsterSampleApplicationPagesTest {
@Test
void shouldNotBuildPageableFromNullJhipsterSampleApplicationPageable() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("pagination");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageable() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination());
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.unsorted());
}
@Test
void shouldNotBuildWithoutSort() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(pagination(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("sort");
}
@Test
void shouldBuildPageableFromJhipsterSampleApplicationPageableAndSort() {
Pageable pagination = JhipsterSampleApplicationPages.from(pagination(), Sort.by("dummy"));
assertThat(pagination.getPageNumber()).isEqualTo(2);
assertThat(pagination.getPageSize()).isEqualTo(15);
assertThat(pagination.getSort()).isEqualTo(Sort.by("dummy"));
}
private JhipsterSampleApplicationPageable pagination() {
return new JhipsterSampleApplicationPageable(2, 15);
}
@Test
void shouldNotConvertFromSpringPageWithoutSpringPage() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(null, source -> source))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("springPage");
}
@Test
void shouldNotConvertFromSpringPageWithoutMapper() {
assertThatThrownBy(() -> JhipsterSampleApplicationPages.from(springPage(), null))
.isExactlyInstanceOf(MissingMandatoryValueException.class)
.hasMessageContaining("mapper");
}
@Test
void shouldConvertFromSpringPage() { | JhipsterSampleApplicationPage<String> page = JhipsterSampleApplicationPages.from(springPage(), Function.identity()); | 1 | 2023-12-10 06:39:18+00:00 | 4k |
zerodevstuff/ExploitFixerv2 | src/main/java/dev/_2lstudios/exploitfixer/ExploitFixer.java | [
{
"identifier": "ExploitFixerCommand",
"path": "src/main/java/dev/_2lstudios/exploitfixer/commands/ExploitFixerCommand.java",
"snippet": "public class ExploitFixerCommand implements CommandExecutor {\n\tprivate ExploitFixer exploitFixer;\n\tprivate MessagesModule messagesModule;\n\tprivate Notifications... | import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import org.bukkit.Server;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.UnknownDependencyException;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import dev._2lstudios.exploitfixer.commands.ExploitFixerCommand;
import dev._2lstudios.exploitfixer.configuration.IConfiguration;
import dev._2lstudios.exploitfixer.listener.ListenerInitializer;
import dev._2lstudios.exploitfixer.managers.ModuleManager;
import dev._2lstudios.exploitfixer.tasks.ExploitFixerRepeatingTask;
import dev._2lstudios.exploitfixer.utils.ConfigUtil;
import dev._2lstudios.exploitfixer.utils.PluginDownloader; | 3,217 | package dev._2lstudios.exploitfixer;
public class ExploitFixer extends JavaPlugin {
private static ExploitFixer instance;
private ConfigUtil configUtil; | package dev._2lstudios.exploitfixer;
public class ExploitFixer extends JavaPlugin {
private static ExploitFixer instance;
private ConfigUtil configUtil; | private ModuleManager moduleManager; | 3 | 2023-12-13 21:49:27+00:00 | 4k |
12manel123/mcc-tsys-ex2-c4-051223 | Ex02/src/main/java/com/ex02/controller/MensajeController.java | [
{
"identifier": "Mensaje",
"path": "Ex02/src/main/java/com/ex02/dto/Mensaje.java",
"snippet": "@Entity\r\npublic class Mensaje {\r\n\t@Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n private Long id;\r\n private String contenido;\r\n private String nombreUsuarioCreador;\r\n ... | import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ex02.dto.Mensaje;
import com.ex02.dto.Partida;
import com.ex02.service.MensajeService;
import com.ex02.service.PartidaService;
import jakarta.transaction.Transactional;
| 1,768 | package com.ex02.controller;
@RestController
@RequestMapping("ex2/mensaje")
public class MensajeController {
private final MensajeService mensajeService;
public MensajeController(MensajeService mensajeService) {
this.mensajeService = mensajeService;
}
@PostMapping("/crear")
public ResponseEntity<String> crearMensaje(@RequestBody Mensaje mensaje) {
mensajeService.crearMensaje(mensaje);
return new ResponseEntity<>("Mensaje creado exitosamente", HttpStatus.CREATED);
}
@DeleteMapping("/eliminar/{idMensaje}")
public ResponseEntity<String> eliminarMensaje(@PathVariable Long idMensaje) {
mensajeService.eliminarMensaje(idMensaje);
return ResponseEntity.ok("Mensaje eliminado exitosamente");
}
@GetMapping("/verTodosEnSala/{nombreSala}")
public ResponseEntity<List<Mensaje>> verTodosLosMensajesEnSala(@PathVariable String nombreSala) {
List<Mensaje> mensajes = mensajeService.verTodosLosMensajes(nombreSala);
List<Mensaje> mensajesEnSala = new ArrayList<>();
for (Mensaje mensaje : mensajes) {
| package com.ex02.controller;
@RestController
@RequestMapping("ex2/mensaje")
public class MensajeController {
private final MensajeService mensajeService;
public MensajeController(MensajeService mensajeService) {
this.mensajeService = mensajeService;
}
@PostMapping("/crear")
public ResponseEntity<String> crearMensaje(@RequestBody Mensaje mensaje) {
mensajeService.crearMensaje(mensaje);
return new ResponseEntity<>("Mensaje creado exitosamente", HttpStatus.CREATED);
}
@DeleteMapping("/eliminar/{idMensaje}")
public ResponseEntity<String> eliminarMensaje(@PathVariable Long idMensaje) {
mensajeService.eliminarMensaje(idMensaje);
return ResponseEntity.ok("Mensaje eliminado exitosamente");
}
@GetMapping("/verTodosEnSala/{nombreSala}")
public ResponseEntity<List<Mensaje>> verTodosLosMensajesEnSala(@PathVariable String nombreSala) {
List<Mensaje> mensajes = mensajeService.verTodosLosMensajes(nombreSala);
List<Mensaje> mensajesEnSala = new ArrayList<>();
for (Mensaje mensaje : mensajes) {
| Partida partida = mensaje.getPartida();
| 1 | 2023-12-05 15:39:34+00:00 | 4k |
xIdentified/TavernBard | src/main/java/me/xidentified/tavernbard/managers/SongManager.java | [
{
"identifier": "BardTrait",
"path": "src/main/java/me/xidentified/tavernbard/BardTrait.java",
"snippet": "@TraitName(\"bard\")\npublic class BardTrait extends Trait {\n\n @Persist private boolean isBard = true;\n\n public BardTrait() {\n super(\"bard\");\n }\n\n // Keeping load and s... | import io.lumine.mythic.bukkit.MythicBukkit;
import io.lumine.mythic.core.mobs.ActiveMob;
import me.xidentified.tavernbard.*;
import me.xidentified.tavernbard.BardTrait;
import me.xidentified.tavernbard.util.MessageUtil;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.title.Title;
import org.bukkit.*;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap; | 3,153 | Component subtitle = Component.text("Now playing: ", NamedTextColor.YELLOW)
.append(parsedDisplayNameComponent);
Title title = Title.title(mainTitle, subtitle);
nearbyPlayer.showTitle(title);
} else {
// If Spigot, use the universally formatted string directly
nearbyPlayer.sendTitle("", "Now playing: " + universalFormattedString, 10, 70, 20);
}
}
// Set current song
currentSong.put(npcId, new Song(selectedSong.getNamespace(), selectedSong.getName(), selectedSong.getDisplayName(), selectedSong.getArtist(), selectedSong.getDuration(), songStarter.get(npcId).getUniqueId()));
// Update now playing info
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
plugin.debugLog("Sound play attempt completed.");
int taskId = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
Entity bardEntity = plugin.getEntityFromUUID(player.getWorld(), npcId);
if (bardEntity != null) {
Location particleLocation = bardEntity.getLocation().add(0, 2.5, 0);
bardEntity.getWorld().spawnParticle(Particle.NOTE, particleLocation, 1);
} else {
plugin.debugLog("Entity with UUID " + npcId + " is null when trying to spawn particles.");
}
}, 0L, 20L).getTaskId();
long songDurationInTicks = selectedSong.getDuration() * 20L;
currentSongTaskId.put(npcId, taskId);
Bukkit.getScheduler().runTaskLater(plugin, () -> {
plugin.debugLog("Song ended. Attempting to play next song in the queue.");
Bukkit.getScheduler().cancelTask(taskId);
setSongPlaying(npcId, false);
playNextSong(npcId, player);
}, songDurationInTicks);
}
// Stops the current song for nearby players
public void stopCurrentSong(UUID npcId) {
if (isSongPlaying(npcId) && currentSongTaskId.containsKey(npcId) && currentSongTaskId.get(npcId) != -1) {
Bukkit.getScheduler().cancelTask(currentSongTaskId.get(npcId));
setSongPlaying(npcId, false);
UUID bardNpc = bardNpcs.get(npcId);
if (bardNpc != null) {
World world = Bukkit.getServer().getWorlds().get(0);
Entity entity = plugin.getEntityFromUUID(world, bardNpc);
if (entity instanceof Player bardPlayer) {
for (Player nearbyPlayer : bardPlayer.getWorld().getPlayers()) {
if (nearbyPlayer.getLocation().distance(bardPlayer.getLocation()) <= songPlayRadius) {
nearbyPlayer.stopAllSounds();
}
}
}
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
currentSong.remove(npcId);
playNextSong(npcId, songStarter.get(npcId));
songStarter.remove(npcId);
}
}
public void playNextSong(UUID npcId, Player songStarter) {
// Attempt to play next song in queue
Song nextSong = queueManager.getNextSongFromQueue(npcId);
if (nextSong != null && npcId != null) {
playSongForNearbyPlayers(songStarter, npcId, nextSong, false);
}
}
public boolean isSongPlaying(UUID npcId) {
return isSongPlaying.getOrDefault(npcId, false);
}
private void setSongPlaying(UUID npcId, boolean status) {
isSongPlaying.put(npcId, status);
}
public List<Song> getSongs() {
return new ArrayList<>(songs);
}
public Song getSongByName(String actualSongName) {
return songs.stream()
.filter(song -> song.getName().equalsIgnoreCase(actualSongName))
.findFirst()
.orElse(null);
}
public Player getSongStarter(UUID playerId) {
return songStarter.get(playerId);
}
public Song getCurrentSong(UUID npcId) {
return currentSong.get(npcId);
}
public UUID getNearestBard(Player player, double searchRadius) {
double closestDistanceSquared = searchRadius * searchRadius;
UUID closestBard = null;
// Get all entities within the search radius
List<Entity> nearbyEntities = player.getNearbyEntities(searchRadius, searchRadius, searchRadius);
for (Entity entity : nearbyEntities) {
// Check for Citizens NPC
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
NPC npc = CitizensAPI.getNPCRegistry().getNPC(entity); | package me.xidentified.tavernbard.managers;
public class SongManager {
private final TavernBard plugin;
private final QueueManager queueManager;
private final EconomyManager economyManager;
private final ItemCostManager itemCostManager;
private final List<Song> songs;
protected final double songPlayRadius;
private final int defaultSongDuration;
public final Map<UUID, Player> songStarter = new ConcurrentHashMap<>();
private final Map<UUID, Boolean> isSongPlaying = new ConcurrentHashMap<>();
private final Map<UUID, Song> currentSong = new ConcurrentHashMap<>();
private final Map<UUID, Integer> currentSongTaskId = new ConcurrentHashMap<>();
public final Map<UUID, UUID> bardNpcs = new ConcurrentHashMap<>();
public SongManager(TavernBard plugin) {
this.plugin = plugin;
this.queueManager = new QueueManager(this.plugin, this, plugin.getCooldownManager());
this.economyManager = new EconomyManager(this.plugin);
this.songs = loadSongsFromConfig();
this.songPlayRadius = plugin.getConfig().getDouble("song-play-radius", 20.0);
this.defaultSongDuration = plugin.getConfig().getInt("default-song-duration", 180);
this.itemCostManager = new ItemCostManager(
plugin.getConfig().getString("item-cost.item", "GOLD_NUGGET"),
plugin.getConfig().getInt("item-cost.amount", 3),
plugin.getConfig().getBoolean("item-cost.enabled", false),
plugin
);
}
public SongSelectionGUI getSongSelectionGUIForNPC(UUID npcId) {
UUID bardNpc = bardNpcs.get(npcId);
if (bardNpc == null) {
return null;
}
return new SongSelectionGUI(plugin, plugin.getSongManager(), bardNpc);
}
// Reload songs from config
public void reloadSongs() {
plugin.reloadConfig();
songs.clear();
songs.addAll(loadSongsFromConfig());
}
// Load songs from config
private List<Song> loadSongsFromConfig() {
List<Song> loadedSongs = new ArrayList<>();
FileConfiguration config = plugin.getConfig();
if (config.isConfigurationSection("songs")) {
ConfigurationSection songsSection = config.getConfigurationSection("songs");
assert songsSection != null;
for (String key : songsSection.getKeys(false)) {
String namespace = songsSection.getString(key + ".namespace");
String songName = songsSection.getString(key + ".name", key);
String displayName = songsSection.getString(key + ".displayName", songName);
String artist = songsSection.getString(key + ".artist", "Unknown Artist");
int duration = songsSection.getInt(key + ".duration", defaultSongDuration);
loadedSongs.add(new Song(namespace, songName, displayName, artist, duration));
}
} else {
plugin.debugLog("The 'songs' section is missing or misconfigured in config.yml!");
}
return loadedSongs;
}
public void playSongForNearbyPlayers(@NotNull Player player, @NotNull UUID npcId, @NotNull Song selectedSong, boolean chargePlayer) {
MessageUtil messageUtil = this.plugin.getMessageUtil();
CooldownManager cooldownManager = this.plugin.getCooldownManager();
UUID bardNpc = bardNpcs.get(npcId);
Object message = selectedSong.getDisplayName();
if (bardNpc == null) {
plugin.getLogger().severe("Could not retrieve NPC for ID: " + npcId);
return;
}
plugin.debugLog("Attempting to play song: " + message + " for " + songStarter.get(player.getUniqueId()));
// Check if item cost is enabled, return if they can't afford it
if (!cooldownManager.isOnCooldown(player) && chargePlayer && itemCostManager.isEnabled() && !itemCostManager.canAfford(player)) {
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<red>You need " + itemCostManager.getCostAmount() + " " + itemCostManager.formatEnumName(itemCostManager.getCostItem().name()) + "(s) to play a song!"));
return;
}
// Check if economy is enabled
if(!cooldownManager.isOnCooldown(player) && chargePlayer && plugin.getConfig().getBoolean("economy.enabled")) {
double costPerSong = plugin.getConfig().getDouble("economy.cost-per-song");
// Check and charge the player
if(!economyManager.chargePlayer(player, costPerSong)) {
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<red>You need " + costPerSong + " coins to play a song!"));
return;
} else {
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<green>Paid " + costPerSong + " coins to play a song!"));
}
}
if (!cooldownManager.isOnCooldown(player) && chargePlayer && itemCostManager.isEnabled()) {
itemCostManager.deductCost(player);
player.sendMessage(plugin.getMessageUtil().convertToUniversalFormat("<green>Charged " + itemCostManager.getCostAmount() + " " + itemCostManager.formatEnumName(itemCostManager.getCostItem().name()) + "(s) to play a song!"));
}
// If something is already playing, add song to queue
if (isSongPlaying(npcId)) {
queueManager.addSongToQueue(npcId, selectedSong, player);
return;
}
setSongPlaying(npcId, true);
Location bardLocation = Objects.requireNonNull(plugin.getEntityFromUUID(player.getWorld(), bardNpc)).getLocation();
plugin.debugLog("Playing sound reference: " + selectedSong.getSoundReference());
// Play song and show title to players within bard's radius
for (Player nearbyPlayer : bardLocation.getWorld().getPlayers()) {
if (nearbyPlayer.getLocation().distance(bardLocation) <= songPlayRadius) {
nearbyPlayer.playSound(bardLocation, selectedSong.getSoundReference(), 1.0F, 1.0F);
// Convert display name to a universally formatted string
String universalFormattedString = messageUtil.convertToUniversalFormat(selectedSong.getDisplayName());
if (messageUtil.isPaper()) {
// If Paper, parse the string back to a Component for displaying
Component parsedDisplayNameComponent = messageUtil.parse(universalFormattedString);
Component mainTitle = Component.text("");
Component subtitle = Component.text("Now playing: ", NamedTextColor.YELLOW)
.append(parsedDisplayNameComponent);
Title title = Title.title(mainTitle, subtitle);
nearbyPlayer.showTitle(title);
} else {
// If Spigot, use the universally formatted string directly
nearbyPlayer.sendTitle("", "Now playing: " + universalFormattedString, 10, 70, 20);
}
}
// Set current song
currentSong.put(npcId, new Song(selectedSong.getNamespace(), selectedSong.getName(), selectedSong.getDisplayName(), selectedSong.getArtist(), selectedSong.getDuration(), songStarter.get(npcId).getUniqueId()));
// Update now playing info
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
plugin.debugLog("Sound play attempt completed.");
int taskId = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
Entity bardEntity = plugin.getEntityFromUUID(player.getWorld(), npcId);
if (bardEntity != null) {
Location particleLocation = bardEntity.getLocation().add(0, 2.5, 0);
bardEntity.getWorld().spawnParticle(Particle.NOTE, particleLocation, 1);
} else {
plugin.debugLog("Entity with UUID " + npcId + " is null when trying to spawn particles.");
}
}, 0L, 20L).getTaskId();
long songDurationInTicks = selectedSong.getDuration() * 20L;
currentSongTaskId.put(npcId, taskId);
Bukkit.getScheduler().runTaskLater(plugin, () -> {
plugin.debugLog("Song ended. Attempting to play next song in the queue.");
Bukkit.getScheduler().cancelTask(taskId);
setSongPlaying(npcId, false);
playNextSong(npcId, player);
}, songDurationInTicks);
}
// Stops the current song for nearby players
public void stopCurrentSong(UUID npcId) {
if (isSongPlaying(npcId) && currentSongTaskId.containsKey(npcId) && currentSongTaskId.get(npcId) != -1) {
Bukkit.getScheduler().cancelTask(currentSongTaskId.get(npcId));
setSongPlaying(npcId, false);
UUID bardNpc = bardNpcs.get(npcId);
if (bardNpc != null) {
World world = Bukkit.getServer().getWorlds().get(0);
Entity entity = plugin.getEntityFromUUID(world, bardNpc);
if (entity instanceof Player bardPlayer) {
for (Player nearbyPlayer : bardPlayer.getWorld().getPlayers()) {
if (nearbyPlayer.getLocation().distance(bardPlayer.getLocation()) <= songPlayRadius) {
nearbyPlayer.stopAllSounds();
}
}
}
SongSelectionGUI gui = getSongSelectionGUIForNPC(npcId);
if (gui != null) {
gui.updateNowPlayingInfo();
}
}
currentSong.remove(npcId);
playNextSong(npcId, songStarter.get(npcId));
songStarter.remove(npcId);
}
}
public void playNextSong(UUID npcId, Player songStarter) {
// Attempt to play next song in queue
Song nextSong = queueManager.getNextSongFromQueue(npcId);
if (nextSong != null && npcId != null) {
playSongForNearbyPlayers(songStarter, npcId, nextSong, false);
}
}
public boolean isSongPlaying(UUID npcId) {
return isSongPlaying.getOrDefault(npcId, false);
}
private void setSongPlaying(UUID npcId, boolean status) {
isSongPlaying.put(npcId, status);
}
public List<Song> getSongs() {
return new ArrayList<>(songs);
}
public Song getSongByName(String actualSongName) {
return songs.stream()
.filter(song -> song.getName().equalsIgnoreCase(actualSongName))
.findFirst()
.orElse(null);
}
public Player getSongStarter(UUID playerId) {
return songStarter.get(playerId);
}
public Song getCurrentSong(UUID npcId) {
return currentSong.get(npcId);
}
public UUID getNearestBard(Player player, double searchRadius) {
double closestDistanceSquared = searchRadius * searchRadius;
UUID closestBard = null;
// Get all entities within the search radius
List<Entity> nearbyEntities = player.getNearbyEntities(searchRadius, searchRadius, searchRadius);
for (Entity entity : nearbyEntities) {
// Check for Citizens NPC
if (CitizensAPI.getNPCRegistry().isNPC(entity)) {
NPC npc = CitizensAPI.getNPCRegistry().getNPC(entity); | if (!npc.hasTrait(BardTrait.class)) { | 0 | 2023-12-06 06:00:57+00:00 | 4k |
thekocanlhk/TawBrowser-Developed | app/src/main/java/com/thekocanl/tawbrowser/WebActivity.java | [
{
"identifier": "AdBlockerActivity",
"path": "app/src/main/java/com/thekocanl/tawbrowser/AdBlockerActivity.java",
"snippet": "public class AdBlockerActivity {\n\n static Map < String, Boolean > loadedUrls = new HashMap < >();\n\n public static boolean blockAds(WebView view, String url) {\n ... | import com.thekocanl.tawbrowser.AdBlockerActivity;
import com.thekocanl.tawbrowser.util.AdBlocker;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.widget.*;
import android.graphics.*;
import android.webkit.SslErrorHandler;
import android.net.http.SslError;
import android.view.ViewTreeObserver;
import android.support.v7.app.AlertDialog;
import android.content.DialogInterface;
import android.print.PrintManager;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.view.View.*;
import java.lang.reflect.Method;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.os.Handler;
import android.os.Looper;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.webkit.GeolocationPermissions;
import android.webkit.WebResourceResponse;
import android.net.http.SslCertificate;
import java.util.Date;
import android.content.pm.ActivityInfo;
import android.speech.RecognizerIntent;
import android.content.ActivityNotFoundException;
import java.util.ArrayList;
import android.text.TextUtils;
import android.content.*; | 2,922 | }
else {
//
}
break;
}
}
});
// bazı eylemler yapmak için hayır düğmesini ayarlayın
builder.setNegativeButton("Hayır", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
}
});
// bazı eylemler yapmak için evet düğmesini ayarlayın
builder.setPositiveButton("Evet", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
// uyarı iletişim kutusunu göster
AlertDialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
}
/**
* Web Site Sertifika Bilgisi
*/
private void certificateControl() {
SslCertificate certificate = webView.getCertificate();
if (certificate == null) {
//
initView();
webCertificate.setImageResource(R.drawable.unreliable_certificate);
cuhideshowControl();
initView();
}
else
{
//
initView();
webCertificate.setImageResource(R.drawable.reliable_certificate);
cuhideshowControl();
initView();
}
}
/**
* Web Site S CUHideShowControl
*/
private void cuhideshowControl() {
String cuUrl = getResources().getString(R.string.home_url);
if (webView.getUrl() != null && !webView.getUrl().equals(cuUrl))
{
initView();
webIcon.setVisibility(View.GONE);
webCertificate.setVisibility(View.VISIBLE);
initView();
}
else
{
initView();
webCertificate.setVisibility(View.GONE);
webIcon.setVisibility(View.VISIBLE);
initView();
}
}
/**
* Light Theme
*/
private void lightTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#cccccc"));
getWindow().setNavigationBarColor(Color.parseColor("#cccccc"));
}
/**
* Dark Theme
*/
private void darkTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#0f0f0f"));
getWindow().setNavigationBarColor(Color.parseColor("#0f0f0f"));
}
/**
* Main Menu Printer
*/
private void createWebPrintJob(WebView webView) {
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
String jobName = getString(R.string.app_name) + " Print Test";
printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
}
/**
* Yeniden Yazmak WebViewClient
*/
private class TawWebViewClient extends WebViewClient {
// Ad Blocker
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (adblockeronoff == 1) { | package com.thekocanl.tawbrowser;
public class WebActivity extends AppCompatActivity implements View.OnClickListener {
private WebView webView;
private ProgressBar progressBar;
private EditText textUrl, findBox;
private TextView homePageSearch, urltitle, urlfull;
private ImageView webIcon, webCertificate, goBack, goForward, navSet, goHome, speakGo, btnStart, btnSearchEngine, textUrlClean, textUrlEdit, floatButton, homePageSpeakGo, imageLabeldownload, imageLabelhistory, imageLabelsavedpage, imageLabeladdpage, imageLabelshare, imageLabeldarktheme, imageLabeladblocker, imageLabelfindpage, imageLabeldesktopsite, imageLabeltextsize, imageLabelzoomin, imageLabelprint, imageLabelsecurity, imageLabelsettings, imageLabeltranslation, imageLabelotorotate, imageLabelfullscreen, imageLabelwidefullscreen, imageLabelswiperefresh, imageLabelnojavascript, imageLabelnopicture, imageLabelcleandata, imageLabelsafebrowser, imageLabelexitapp;
private SwipeRefreshLayout swipeRefreshLayout;
// Tam Ekran Kullanımı
private LinearLayout toplinearLayout, sublinearLayout, layoutSearch, layoutSearchUrlInfo;
// Search
private ImageButton closeButton, nextButton, backButton;
// Ayarlar
private FrameLayout navsetLayout, homePageLayout;
private long exitTime = 0;
// Tam Ekran Kullanımı
private int floatbutton = 0;
// Main Menu Fullscreen
private int floatbuttonhideshow = 0;
// Main Menu Wide Fullscreen
private int widefullscreen = 0;
// Main Menu Wide Fullscreen On Off
private int widefullscreen_on_off = 0;
// Main Menu Dark Theme
private int darktheme = 0;
// Main Menu Swipe Refresh
private int swiperefresh = 0;
// Main Menu No Javascript
private int nojavascript = 0;
// Main Menu No Picture
private int nopicture = 0;
// Main Menu Desktop Site
private int desktopsite = 0;
// Main Menu Oto Rotate
private int otorotate = 0;
// Ayarlar
private int navset = 0;
// Ad Blocker
private int adblocker = 0;
// Ad Blocker On Off
private int adblockeronoff = 0;
// Search
private int findpage = 0;
// Clean Data
private int gt = 1;
private int agt = 1;
private int wot = 0;
private int uot = 0;
private int fvt = 1;
private int wct = 1;
private boolean bol0 = true;
private boolean bol1 = true;
private boolean bol2 = false;
private boolean bol3 = false;
private boolean bol4 = true;
private boolean bol5 = true;
//Search Engine
private boolean sebol0 = true;
private boolean sebol1 = false;
private boolean sebol2 = false;
private boolean sebol3 = false;
private boolean sebol4 = false;
private boolean sebol5 = false;
private boolean sebol6 = false;
private boolean sebol7 = false;
private String searchengineurlinput = "https://www.google.com/search?q=";
// Arama Çubuğu Göster Gizle
private float startY;
private int autohidesearchbar = 0;
private int homepagesearch = 0;
private int homepagespeakgo = 0;
private Context mContext;
private InputMethodManager manager;
private static final int RESULT_SPEECH = 1;
private static final String HTTP = "http://";
private static final String HTTPS = "https://";
private static final int PRESS_BACK_EXIT_GAP = 2000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Alt Düğmenin Yukarı Hareket Etmesini Engelle
getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
setContentView(R.layout.activity_web);
mContext = WebActivity.this;
manager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
// Ad Blocker
new AdBlockerActivity.init(this);
// Bağlama Kontrolleri
initView();
// Web Görünümünü Başlat
initWeb();
// Swipe Refresh
swipeRefresh();
// Arama Çubuğu Göster Gizle
autohideSearchBar();
}
/**
* Bağlama Kontrolleri
*/
private void initView() {
webView = findViewById(R.id.webView);
progressBar = findViewById(R.id.progressBar);
textUrl = findViewById(R.id.textUrl);
webIcon = findViewById(R.id.webIcon);
webCertificate = findViewById(R.id.webCertificate);
btnStart = findViewById(R.id.btnStart);
goBack = findViewById(R.id.goBack);
goForward = findViewById(R.id.goForward);
navSet = findViewById(R.id.navSet);
goHome = findViewById(R.id.goHome);
// Main Menu Bağlama Kontrolleri
imageLabeldownload = findViewById(R.id.imageLabeldownload);
imageLabelhistory = findViewById(R.id.imageLabelhistory);
imageLabelsavedpage = findViewById(R.id.imageLabelsavedpage);
imageLabeladdpage = findViewById(R.id.imageLabeladdpage);
imageLabelshare = findViewById(R.id.imageLabelshare);
imageLabeldarktheme = findViewById(R.id.imageLabeldarktheme);
imageLabeladblocker = findViewById(R.id.imageLabeladblocker);
imageLabelfindpage = findViewById(R.id.imageLabelfindpage);
imageLabeldesktopsite = findViewById(R.id.imageLabeldesktopsite);
imageLabeltextsize = findViewById(R.id.imageLabeltextsize);
imageLabelzoomin = findViewById(R.id.imageLabelzoomin);
imageLabelprint = findViewById(R.id.imageLabelprint);
imageLabelsecurity = findViewById(R.id.imageLabelsecurity);
imageLabelsettings = findViewById(R.id.imageLabelsettings);
imageLabeltranslation = findViewById(R.id.imageLabeltranslation);
imageLabelotorotate = findViewById(R.id.imageLabelotorotate);
imageLabelfullscreen = findViewById(R.id.imageLabelfullscreen);
imageLabelwidefullscreen = findViewById(R.id.imageLabelwidefullscreen);
imageLabelswiperefresh = findViewById(R.id.imageLabelswiperefresh);
imageLabelnojavascript = findViewById(R.id.imageLabelnojavascript);
imageLabelnopicture = findViewById(R.id.imageLabelnopicture);
imageLabelcleandata = findViewById(R.id.imageLabelcleandata);
imageLabelsafebrowser = findViewById(R.id.imageLabelsafebrowser);
imageLabelexitapp = findViewById(R.id.imageLabelexitapp);
//Tam Ekran Kullanımı
toplinearLayout = findViewById(R.id.toplinearLayout);
sublinearLayout = findViewById(R.id.sublinearLayout);
// Search
findBox = findViewById(R.id.findBox);
nextButton = findViewById(R.id.nextButton);
backButton = findViewById(R.id.backButton);
closeButton = findViewById(R.id.closeButton);
layoutSearch = findViewById(R.id.layoutSearch);
// Layout Search Url Info
layoutSearchUrlInfo = findViewById(R.id.layoutSearchUrlInfo);
urltitle = findViewById(R.id.urltitle);
urlfull = findViewById(R.id.urlfull);
// Search Engine
btnSearchEngine = findViewById(R.id.btnSearchEngine);
// Speak Go
speakGo = findViewById(R.id.speakGo);
// Ayarlar
navsetLayout = findViewById(R.id.navsetLayout);
// Anasayfa Layout
homePageLayout = findViewById(R.id.homePageLayout);
homePageSearch = findViewById(R.id.homePageSearch);
homePageSpeakGo = findViewById(R.id.homePageSpeakGo);
// Adresi Silme
textUrlClean = findViewById(R.id.textUrlClean);
// Adresi Düzenleme
textUrlEdit = findViewById(R.id.textUrlEdit);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setColorSchemeColors(Color.BLACK,Color.BLACK,Color.BLACK);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (swiperefresh == 1) {
webView.reload();
swipeRefreshLayout.setRefreshing(false);
}
else if (swiperefresh == 0) {
swipeRefreshLayout.setRefreshing(false);
}
}
});
// Web Site Sertifika Bilgisi
webCertificate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = "URL: " + webView.getUrl() + "\n";
s += "Başlık: " + webView.getTitle() + "\n\n";
SslCertificate certificate = webView.getCertificate();
s += certificate == null ? "Güvenli değil" : "Sertifika: Güvenli\n" + certificateToStr(certificate);
AlertDialog.Builder certificateDialog = new AlertDialog.Builder(WebActivity.this)
.setTitle("Sertifika bilgisi")
.setMessage(s)
.setPositiveButton("Kapat", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
//
}
});
certificateDialog.show();
}
});
// SwipeRefreshLayout sayfa üstünde yenileme ayarı
webView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (swiperefresh == 1) {
if (webView.getScrollY()==0) {
swipeRefreshLayout.setEnabled(true);
}else {
swipeRefreshLayout.setEnabled(false);
}
}
}
});
// Anasayfa Arama odaklanma
homePageSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
if(homepagesearch == 0) {
textUrl.requestFocus();
//InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//inputMethodManager.showSoftInput(textUrl, InputMethodManager.SHOW_IMPLICIT);
showKeyboard(textUrl);
navsetLayout.setVisibility(View.GONE);
navset = 0;
//
// Gösterme Animasyonu
toplinearLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
//
// Gösterme Süresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.VISIBLE);
}
}, 1);
//
}
}
});
// Anasayfa Speak Go
homePageSpeakGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
if(homepagespeakgo == 0) {
speakGo();
navsetLayout.setVisibility(View.GONE);
navset = 0;
//
// Gösterme Animasyonu
toplinearLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
//
// Gösterme Süresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.VISIBLE);
}
}, 1);
//
}
}
});
// Speak Go
speakGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
speakGo();
//
}
});
// Adresi Silme
textUrlClean.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textUrl.setText(webView.getUrl());
textUrl.setSelection(textUrl.getText().length());
textUrl.getText().clear();
}
});
// Adresi Silme
textUrlEdit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textUrl.setText(webView.getUrl());
textUrl.setSelection(textUrl.getText().length());
}
});
//Tam Ekran Kullanımı
floatButton = findViewById(R.id.floatButton);
// Tam Ekran Düğmesi Kullanımı
floatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if (floatbutton == 0)
{
initView();
toplinearLayout.setVisibility(View.GONE);
Toast.makeText(mContext, "Tam Ekran açıldı çıkmak için tekrar basın", Toast.LENGTH_SHORT).show();
floatButton.setImageResource(R.drawable.icfullscreenexit24dp);
sublinearLayout.setVisibility(View.GONE);
autohidesearchbar = 1;
floatbutton = 1;
initView();
}
else if (floatbutton == 1)
{
initView();
toplinearLayout.setVisibility(View.VISIBLE);
toplinearLayout.setAlpha(1.0f);
Toast.makeText(mContext, "Tam Ekrandan çıkıldı açmak için tekrar basın", Toast.LENGTH_SHORT).show();
floatButton.setImageResource(R.drawable.icfullscreen24dp);
sublinearLayout.setVisibility(View.VISIBLE);
autohidesearchbar = 0;
floatbutton = 0;
initView();
}
if (findpage == 1)
{
initView();
toplinearLayout.setVisibility(View.GONE);
layoutSearch.setVisibility(View.VISIBLE);
autohidesearchbar = 1;
initView();
}
}
});
// Bağlama Düğmesi Tıklama Olayı
btnStart.setOnClickListener(this);
goBack.setOnClickListener(this);
goForward.setOnClickListener(this);
navSet.setOnClickListener(this);
goHome.setOnClickListener(this);
// Main Menu Bağlama Kontrolleri
imageLabeldownload.setOnClickListener(this);
imageLabelhistory.setOnClickListener(this);
imageLabelsavedpage.setOnClickListener(this);
imageLabeladdpage.setOnClickListener(this);
imageLabelshare.setOnClickListener(this);
imageLabeldarktheme.setOnClickListener(this);
imageLabeladblocker.setOnClickListener(this);
imageLabelfindpage.setOnClickListener(this);
imageLabeldesktopsite.setOnClickListener(this);
imageLabeltextsize.setOnClickListener(this);
imageLabelzoomin.setOnClickListener(this);
imageLabelprint.setOnClickListener(this);
imageLabelsecurity.setOnClickListener(this);
imageLabelsettings.setOnClickListener(this);
imageLabeltranslation.setOnClickListener(this);
imageLabelotorotate.setOnClickListener(this);
imageLabelfullscreen.setOnClickListener(this);
imageLabelwidefullscreen.setOnClickListener(this);
imageLabelswiperefresh.setOnClickListener(this);
imageLabelnojavascript.setOnClickListener(this);
imageLabelnopicture.setOnClickListener(this);
imageLabelcleandata.setOnClickListener(this);
imageLabelsafebrowser.setOnClickListener(this);
imageLabelexitapp.setOnClickListener(this);
// Search
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
closeButton.setOnClickListener(this);
//Search Engine
btnSearchEngine.setOnClickListener(this);
// Adresi Silme
textUrlClean.setVisibility(View.GONE);
// Adresi Düzenleme
textUrlEdit.setVisibility(View.GONE);
// Speak Go
speakGo.setVisibility(View.GONE);
// Adres Giriş Alanı Odağı Alır Ve Kaybeder
textUrl.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
// Geçerli URL Bağlantısını Göster TODO:Arama Terimlerini Gösteren Arama Sayfası
textUrl.setText(webView.getUrl());
// Sonunda İmleç
textUrl.setSelection(textUrl.getText().length());
// Adresi Silme
textUrl.getText().clear();
// İnternet Simgesini Göster
webIcon.setImageResource(R.drawable.internet);
// Atlama düğmelerini göster
btnStart.setImageResource(R.drawable.go);
// Adresi Silme
textUrlClean.setVisibility(View.VISIBLE);
// Adresi Düzenleme
textUrlEdit.setVisibility(View.VISIBLE);
// Web Site Sertifika Bilgisi
webCertificate.setVisibility(View.GONE);
webIcon.setVisibility(View.VISIBLE);
// Speak Go
speakGo.setVisibility(View.VISIBLE);
// Layout Search Url Info
urltitle.setText(webView.getTitle());
urltitle.setEms(14);
urlfull.setText(webView.getUrl());
urlfull.setEms(18);
layoutSearchUrlInfo.setVisibility(View.VISIBLE);
}
else {
// Web Sitesi Adını Göster
textUrl.setText(webView.getTitle());
// Favicon'u Göster
webIcon.setImageBitmap(webView.getFavicon());
// Yenile Düğmesini Göster
btnStart.setImageResource(R.drawable.refresh);
// Adresi Silme
textUrlClean.setVisibility(View.INVISIBLE);
// Adresi Düzenleme
textUrlEdit.setVisibility(View.INVISIBLE);
// Web Site S CUHideShowControl
cuhideshowControl();
// Speak Go
speakGo.setVisibility(View.GONE);
// Layout Search Url Info
layoutSearchUrlInfo.setVisibility(View.GONE);
// Görünümü Tekrar Başlat
initView();
}
}
});
// Search
findBox.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (((findpage == 1)) && ((event.getAction() == KeyEvent.ACTION_DOWN)) && ((keyCode == KeyEvent.KEYCODE_ENTER)))
{
webView.findAllAsync(findBox.getText().toString());
try
{
for (Method m : WebView.class.getDeclaredMethods())
{
if (m.getName().equals("setFindIsUp"))
{
m.setAccessible(true);
m.invoke(webView, true);
break;
}
}
}
catch (Exception ignored)
{
}
finally
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
View vv = getCurrentFocus();
if (vv != null)
{
inputManager.hideSoftInputFromWindow(v.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
return false;
}
});
// Monitör Klavyesi Aramaya Gir
textUrl.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
// Arama Yap
btnStart.callOnClick();
textUrl.clearFocus();
}
return false;
}
});
}
/**
* Web'i Başlat
*/
@SuppressLint("SetJavaScriptEnabled")
private void initWeb() {
// Yeniden Yazmak WebViewClient
webView.setWebViewClient(new TawWebViewClient());
// Yeniden Yazmak WebChromeClient
webView.setWebChromeClient(new TawWebChromeClient());
WebSettings settings = webView.getSettings();
// JS İşlevini Etkinleştir
settings.setJavaScriptEnabled(true);
// Tarayıcıyı Kullanıcı Aracısı Olarak Ayarla
settings.setUserAgentString(settings.getUserAgentString() + " TawBrowser/" + getVerName(mContext));
// Resmi Web Görünümüne Sığdırmak İçin Yeniden Boyutlandırın
settings.setUseWideViewPort(true);
// Ekranın Boyutuna Yakınlaştırın
settings.setLoadWithOverviewMode(true);
// Ölçeklendirmeyi Destekler, Varsayılanlar true'dur. Aşağıdakilerin Öncülüdür.
settings.setSupportZoom(true);
// Yerleşik Yakınlaştırma Kontrollerini Ayarlar. false'yse, WebView Yakınlaştırılamaz
settings.setBuiltInZoomControls(true);
// Yerel Yakınlaştırma Denetimlerini Gizle
settings.setDisplayZoomControls(false);
// Çoklu Pencereleri Destekleme
settings.setSupportMultipleWindows(true);
// WebView Background Color
webView.setBackgroundColor(Color.WHITE);
// Önbellek
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
// Dosya Erişimini Ayarla
settings.setAllowFileAccess(true);
// JS Aracılığıyla Yeni Pencerelerin Açılmasını Destekleyin
settings.setJavaScriptCanOpenWindowsAutomatically(true);
// Resimlerin Otomatik Yüklenmesini Destekleyin
settings.setLoadsImagesAutomatically(true);
// Varsayılan Kodlama Biçimini Ayarlayın
settings.setDefaultTextEncodingName("utf-8");
// Yerel Depolama
settings.setDomStorageEnabled(true);
settings.setPluginState(WebSettings.PluginState.ON);
// Geolocation Path
settings.setGeolocationEnabled(true);
settings.setGeolocationDatabasePath(String.valueOf(mContext.getFilesDir().getAbsolutePath()) + "/location");
// AppCache Path
settings.setAppCacheEnabled(true);
settings.setAppCachePath(String.valueOf(mContext.getFilesDir().getAbsolutePath()) + "/cache");
// Database Path
settings.setDatabaseEnabled(true);
settings.setDatabasePath(String.valueOf(mContext.getFilesDir().getAbsolutePath()) + "/databases");
// WebView Metin Boyutu
settings.setTextZoom(100);
// Kaynak Karışımı Modu
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
// Ana Sayfayı Yükle
SharedPreferences sp = getSharedPreferences("PREFS", MODE_PRIVATE);
SharedPreferences.Editor spe = sp.edit();
//
if (sp.getInt("HOMEPAGEURLCHANGE", 0) == 1) {
//
webView.loadUrl(""+sp.getString("HOMEPAGEURL", ""));
}
else {
//
webView.loadUrl(getResources().getString(R.string.home_url));
}
}
/**
* Swipe Refresh
*/
private void swipeRefresh() {
swipeRefreshLayout.setEnabled(false);
}
/**
* WebView Back Forward Control
*/
private void goBackForwardControl() {
//
goBack.setColorFilter(Color.parseColor("#c8c8c8"));
goForward.setColorFilter(Color.parseColor("#c8c8c8"));
//
if(webView.canGoBack()) {
//
goBack.setColorFilter(Color.parseColor("#4d4d4d"));
}
//
if(webView.canGoForward()) {
//
goForward.setColorFilter(Color.parseColor("#4d4d4d"));
}
//
}
/**
* WebView Share Url Control
*/
private void webviewShareUrlControl() {
//
imageLabelshare.setColorFilter(Color.parseColor("#c8c8c8"));
imageLabelprint.setColorFilter(Color.parseColor("#c8c8c8"));
imageLabeltranslation.setColorFilter(Color.parseColor("#c8c8c8"));
//
String cuUrl = getResources().getString(R.string.home_url);
if(webView.getUrl() != null && !webView.getUrl().equals(cuUrl)) {
//
imageLabelshare.setColorFilter(Color.parseColor("#000000"));
imageLabelprint.setColorFilter(Color.parseColor("#000000"));
imageLabeltranslation.setColorFilter(Color.parseColor("#000000"));
}
//
}
/**
* Speak Go
*/
private void speakGo() {
//
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Konuşmadan Niyet Kullanarak Değeri Alın
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "tr-TR");
try {
startActivityForResult(intent, RESULT_SPEECH);
// Metni Boş Olarak Ayarla
textUrl.setText("");
}
catch (ActivityNotFoundException a) {
// Cihaz Desteklenmiyorsa Bir Tost Göster
Toast.makeText(getApplicationContext(), "Üzgünüm cihazınız Speech to Text'i desteklemiyor", Toast.LENGTH_SHORT)
.show();
}
//
}
/**
* Hide Keyboard
*/
private void hideKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* Show Keyboard
*/
private void showKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
/**
* Anasayfa Kontrol - Show Hide
*/
private void homePageControl() {
String cuUrl = getResources().getString(R.string.home_url);
if (webView.getUrl() != null && !webView.getUrl().equals(cuUrl))
{
initView();
// Gizleme Süresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
// Gizleme Animasyonu
homePageLayout.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
}
}, 500);
//
homepagesearch = 1;
homepagespeakgo = 1;
initView();
}
else
{
initView();
// Gösterme Süresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
// Gösterme Animasyonu
homePageLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
webView.setVisibility(View.GONE);
}
}, 1);
//
Handler handler2 = new Handler(Looper.getMainLooper());
handler2.postDelayed(new Runnable() {
public void run() {
webView.setVisibility(View.VISIBLE);
}
}, 500);
//
homepagesearch = 0;
homepagespeakgo = 0;
initView();
}
}
/**
* Arama Çubuğu Göster Gizle
*/
private void autohideSearchBar() {
this.webView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
// NavSetLayout Touch Hide
navsetLayout.setVisibility(View.GONE);
navset = 0;
// Hide Keyboard
hideKeyboard(textUrl);
//
// Açık = Kapalı
if (WebActivity.this.autohidesearchbar == 1) {
return false;
}
//
// 1
if (event.getAction() == 0) {
WebActivity.this.startY = event.getY();
}
//
// 2
if (event.getAction() == 2 || Math.abs(WebActivity.this.startY - event.getY()) <= ((float) (new ViewConfiguration().getScaledTouchSlop() * 5))) {
return false;
}
//
// Göster
if (WebActivity.this.startY < event.getY()) {
// Gösterme Animasyonu
toplinearLayout.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.VISIBLE);
}
});
//
// Gösterme Süresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.VISIBLE);
}
}, 1);
//
return false;
}
//
// Gizle
// Gizleme Animasyonu
toplinearLayout.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator animation, View view) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
});
//
// Gizleme Süresi
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
public void run() {
WebActivity.this.toplinearLayout.setVisibility(View.GONE);
}
}, 1);
//
return false;
//
}
});
}
/**
* Search Engine
*/
private void searchEngineChange() {
//
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Arama motoru seçin");
String[] items = {"Google", "Bing", "Yandex", "DuckDuckGo", "Startpage", "Yahoo", "Ask", "Wow"};
boolean[] checkedItems = {sebol0, sebol1, sebol2, sebol3, sebol4, sebol5, sebol6, sebol7};
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
switch (which) {
//
case 0:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_google);
sebol0 = true;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://www.google.com/search?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol0 = true;
dialog.cancel();
initView();
}
break;
//
case 1:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_bing);
sebol0 = false;
sebol1 = true;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://www.bing.com/search?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol1 = true;
dialog.cancel();
initView();
}
break;
//
case 2:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_yandex);
sebol0 = false;
sebol1 = false;
sebol2 = true;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://yandex.com/search/touch/?text=";
dialog.cancel();
initView();
} else {
//
initView();
sebol2 = true;
dialog.cancel();
initView();
}
break;
//
case 3:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_duckduckgo);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = true;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://duckduckgo.com/?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol3 = true;
dialog.cancel();
initView();
}
break;
//
case 4:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_startpage);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = true;
sebol5 = false;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://www.startpage.com/do/search?query=";
dialog.cancel();
initView();
} else {
//
initView();
sebol4 = true;
dialog.cancel();
initView();
}
break;
//
case 5:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_yahoo);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = true;
sebol6 = false;
sebol7 = false;
searchengineurlinput = "https://search.yahoo.com/search?p=";
dialog.cancel();
initView();
} else {
//
initView();
sebol5 = true;
dialog.cancel();
initView();
}
break;
//
case 6:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_ask);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = true;
sebol7 = false;
searchengineurlinput = "https://www.ask.com/web?q=";
dialog.cancel();
initView();
} else {
//
initView();
sebol6 = true;
dialog.cancel();
initView();
}
break;
case 7:
if (isChecked) {
//
initView();
btnSearchEngine.setImageResource(R.drawable.se_wow);
sebol0 = false;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = true;
searchengineurlinput = "https://www.wow.com/search?p=";
dialog.cancel();
initView();
} else {
//
initView();
sebol7 = true;
dialog.cancel();
initView();
}
break;
}
}
});
builder.setNeutralButton("Varsayılan", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int which) {
initView();
btnSearchEngine.setImageResource(R.drawable.se_google);
sebol0 = true;
sebol1 = false;
sebol2 = false;
sebol3 = false;
sebol4 = false;
sebol5 = false;
sebol6 = false;
sebol7 = false;
Toast.makeText(WebActivity.this, "Varsayılan arama motoru seçildi", Toast.LENGTH_SHORT)
.show();
initView();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
/**
* Clean Data D
*/
private void cleanAllData() {
//
AlertDialog.Builder alertDialog = new AlertDialog.Builder(WebActivity.this);
alertDialog.setTitle("");
String[] items = {"Geçmişi temizle", "Arama geçmişini temizle", "Web önbelleğini temizle", "Uygulama önbelleğini temizle", "Form verilerini temizle ", "Web çerezlerini temizle"};
boolean[] checkedItems = {bol0, bol1, bol2, bol3, bol4, bol5};
alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
switch (which) {
case 0:
if(isChecked) {
gt = 1;
bol0 = true;
}
else {
gt = 0;
bol0 = false;
}
break;
case 1:
if(isChecked) {
agt = 1;
bol1 = true;
}
else {
agt = 0;
bol1 = false;
}
break;
case 2:
if(isChecked) {
wot = 1;
bol2 = true;
}
else {
wot = 0;
bol2 = false;
}
break;
case 3:
if(isChecked) {
uot = 1;
bol3 = true;
}
else {
uot = 0;
bol3 =false;
}
break;
case 4:
if(isChecked) {
fvt = 1;
bol4 = true;
}
else {
fvt = 0;
bol4 = false;
}
break;
case 5:
if(isChecked) {
wct = 1;
bol5 = true;
}
else {
wct = 0;
bol5 = false;
}
break;
}
}
});
alertDialog.setNeutralButton("Varsayılan", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
initView();
cleanAllDataDefault();
Toast.makeText(WebActivity.this, "Varsayılan ayarlara sıfırlandı", Toast.LENGTH_SHORT).show();
cleanAllData();
initView();
}
});
alertDialog.setNegativeButton("İptal", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(WebActivity.this, "İptal edildi", Toast.LENGTH_SHORT).show();
}
});
alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
if(gt == 1 || agt == 1 || wot == 1 || uot == 1 || fvt == 1 || wct ==1) {
//
// Geçmişi temizle
if(gt == 1) {
//
webView.clearHistory();
}
else if(gt == 0) {
//
}
//
// Arama geçmişini temizle
if(agt == 1) {
//
webView.clearMatches();
}
else if(agt == 0) {
//
}
//
// Web önbelleğini temizle
if(wot == 1) {
//
}
else if (wot == 0) {
//
}
//
// Uygulama önbelleğini temizle
if(uot == 1) {
//
}
else if(uot == 0) {
//
}
//
// Form verilerini temizle
if(fvt == 1) {
//
webView.clearFormData();
}
else if(fvt == 0) {
//
}
//
// Web çerezlerini temizle
if(wct == 1) {
//
webView.clearHistory();
webView.clearFormData();
webView.clearCache(true);
}
else if(wct == 0) {
//
}
//
if (gt == 1 || agt == 1 || wot == 1 || uot == 1 || fvt == 1 || wct ==1) {
if (gt == 1 && agt == 1 && wot == 1 && uot == 1 && fvt == 1 && wct ==1) {
Toast.makeText(WebActivity.this, "Tümü temizleniyor...", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(WebActivity.this, "Seçilenler temizleniyor...", Toast.LENGTH_SHORT).show();
}
Toast.makeText(WebActivity.this, "Temizlendi", Toast.LENGTH_SHORT).show();
}
}
else if(gt == 0 && agt == 0 && wot == 0 && uot == 0 && fvt == 0 && wct == 0) {
initView();
cleanAllData();
Toast.makeText(WebActivity.this, "Hıçbir öğe seçilmedi tekrar seçim yapın ve tamam tuşuna basın veya çıkmak için iptal tuşuna basınız", Toast.LENGTH_SHORT).show();
initView();
}
}
});
AlertDialog alert = alertDialog.create();
alert.setCanceledOnTouchOutside(false);
alert.show();
//
}
/**
* Clean Data D Reset Value
*/
private void cleanAllDataReset() {
gt = 0;
agt = 0;
wot = 0;
uot = 0;
fvt = 0;
wct = 0;
bol0 = false;
bol1 = false;
bol2 = false;
bol3 = false;
bol4 = false;
bol5 = false;
}
/**
* Clean Data D Default Value
*/
private void cleanAllDataDefault() {
gt = 1;
agt = 1;
wot = 0;
uot = 0;
fvt = 1;
wct = 1;
bol0 = true;
bol1 = true;
bol2 = false;
bol3 = false;
bol4 = true;
bol5 = true;
}
/**
* Exit App
*/
private void confirmExitApp() {
// uyarı iletişim kutusu
AlertDialog.Builder builder = new AlertDialog.Builder(WebActivity.this);
builder.setIcon(R.drawable.splash);
builder.setTitle("TawBrowser'dan çıkış yapmak istediğinize emin misiniz?");
//
String[] items = {"Web önbelleğini temizle", "Geçmişi temizle", "Her seferinde bana sor"};
boolean[] checkedItems = {false, false, true};
builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
switch (which) {
//
case 0:
if(isChecked) {
//
}
else {
//
}
break;
//
case 1:
if(isChecked) {
//
webView.clearHistory();
}
else {
//
}
break;
//
case 2:
if(isChecked) {
//
}
else {
//
}
break;
}
}
});
// bazı eylemler yapmak için hayır düğmesini ayarlayın
builder.setNegativeButton("Hayır", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
}
});
// bazı eylemler yapmak için evet düğmesini ayarlayın
builder.setPositiveButton("Evet", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
initView();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
// uyarı iletişim kutusunu göster
AlertDialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
}
/**
* Web Site Sertifika Bilgisi
*/
private void certificateControl() {
SslCertificate certificate = webView.getCertificate();
if (certificate == null) {
//
initView();
webCertificate.setImageResource(R.drawable.unreliable_certificate);
cuhideshowControl();
initView();
}
else
{
//
initView();
webCertificate.setImageResource(R.drawable.reliable_certificate);
cuhideshowControl();
initView();
}
}
/**
* Web Site S CUHideShowControl
*/
private void cuhideshowControl() {
String cuUrl = getResources().getString(R.string.home_url);
if (webView.getUrl() != null && !webView.getUrl().equals(cuUrl))
{
initView();
webIcon.setVisibility(View.GONE);
webCertificate.setVisibility(View.VISIBLE);
initView();
}
else
{
initView();
webCertificate.setVisibility(View.GONE);
webIcon.setVisibility(View.VISIBLE);
initView();
}
}
/**
* Light Theme
*/
private void lightTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#cccccc"));
getWindow().setNavigationBarColor(Color.parseColor("#cccccc"));
}
/**
* Dark Theme
*/
private void darkTheme() {
//
getWindow().setStatusBarColor(Color.parseColor("#0f0f0f"));
getWindow().setNavigationBarColor(Color.parseColor("#0f0f0f"));
}
/**
* Main Menu Printer
*/
private void createWebPrintJob(WebView webView) {
PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
String jobName = getString(R.string.app_name) + " Print Test";
printManager.print(jobName, printAdapter, new PrintAttributes.Builder().build());
}
/**
* Yeniden Yazmak WebViewClient
*/
private class TawWebViewClient extends WebViewClient {
// Ad Blocker
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (adblockeronoff == 1) { | return AdBlockerActivity.blockAds(view, url) ? AdBlocker.createEmptyResource() : super.shouldInterceptRequest(view, url); | 1 | 2023-12-09 12:57:19+00:00 | 4k |
connect-ankit/contact-directory | contact-app/src/test/java/com/inn/assignment/PersonControllerTest.java | [
{
"identifier": "AppRunner",
"path": "contact-app/src/main/java/com/inn/assignment/task2/appconfiguration/AppRunner.java",
"snippet": "@SpringBootApplication\n@ComponentScan(basePackages = { \"com.inn\" })\n@EnableAutoConfiguration\n@EnableAspectJAutoProxy\n@EnableFeignClients(basePackages = { \"com.inn... | import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.inn.assignment.task2.appconfiguration.AppRunner;
import com.inn.assignment.task2.controller.IPersonController;
import com.inn.assignment.task2.core.Constant;
import com.inn.assignment.task2.model.Contact;
import com.inn.assignment.task2.model.Person; | 1,841 | package com.inn.assignment;
@SpringBootTest(classes = AppRunner.class)
@ExtendWith(SpringExtension.class)
class PersonControllerTest {
@MockBean | package com.inn.assignment;
@SpringBootTest(classes = AppRunner.class)
@ExtendWith(SpringExtension.class)
class PersonControllerTest {
@MockBean | private IPersonController personController; | 1 | 2023-12-14 20:15:48+00:00 | 4k |
Crydsch/the-one | src/movement/DefaultMovementEngine.java | [
{
"identifier": "ConnectivityGrid",
"path": "src/interfaces/ConnectivityGrid.java",
"snippet": "public class ConnectivityGrid extends ConnectivityOptimizer {\n\n\t/**\n\t * Cell based optimization cell size multiplier -setting id ({@value}).\n\t * Used in {@link World#OPTIMIZATION_SETTINGS_NS} name spac... | import core.*;
import interfaces.ConnectivityGrid;
import interfaces.ConnectivityOptimizer;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.*; | 2,906 | package movement;
/**
* Provides a default implementation to move hosts in the world according to their MovementModel
*/
public class DefaultMovementEngine extends MovementEngine {
/** movement engines -setting id ({@value})*/
public static final String NAME = "DefaultMovementEngine";
private final Coord ORIGIN = new Coord(0.0, 0.0);
/**
* Creates a new MovementEngine based on a Settings object's settings.
* @param settings The Settings object where the settings are read from
*/
public DefaultMovementEngine(Settings settings) {
super(settings);
}
/**
* Initializes the movement engine
* @param hosts to be moved
*/
@Override
public void init(List<DTNHost> hosts, int worldSizeX, int worldSizeY) {
super.init(hosts, worldSizeX, worldSizeY);
// Initialize optimizer
Map<String, List<NetworkInterface>> interface_map = new HashMap<>();
for (DTNHost host : hosts) {
for (NetworkInterface ni : host.getInterfaces()) {
if (ni.getTransmitRange() > 0) {
interface_map.computeIfAbsent(ni.getInterfaceType(), k -> new ArrayList<>()).add(ni);
}
}
}
for (List<NetworkInterface> interfaces : interface_map.values()) { | package movement;
/**
* Provides a default implementation to move hosts in the world according to their MovementModel
*/
public class DefaultMovementEngine extends MovementEngine {
/** movement engines -setting id ({@value})*/
public static final String NAME = "DefaultMovementEngine";
private final Coord ORIGIN = new Coord(0.0, 0.0);
/**
* Creates a new MovementEngine based on a Settings object's settings.
* @param settings The Settings object where the settings are read from
*/
public DefaultMovementEngine(Settings settings) {
super(settings);
}
/**
* Initializes the movement engine
* @param hosts to be moved
*/
@Override
public void init(List<DTNHost> hosts, int worldSizeX, int worldSizeY) {
super.init(hosts, worldSizeX, worldSizeY);
// Initialize optimizer
Map<String, List<NetworkInterface>> interface_map = new HashMap<>();
for (DTNHost host : hosts) {
for (NetworkInterface ni : host.getInterfaces()) {
if (ni.getTransmitRange() > 0) {
interface_map.computeIfAbsent(ni.getInterfaceType(), k -> new ArrayList<>()).add(ni);
}
}
}
for (List<NetworkInterface> interfaces : interface_map.values()) { | optimizer.add(new ConnectivityGrid(interfaces)); | 0 | 2023-12-10 15:51:41+00:00 | 4k |
BarriBarri20/flink-tuto | docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/ClickEventCount.java | [
{
"identifier": "BackpressureMap",
"path": "docker/ops-playground-image/java/flink-playground-clickcountjob/src/main/java/org/apache/flink/playgrounds/ops/clickcount/functions/BackpressureMap.java",
"snippet": "public class BackpressureMap implements MapFunction<ClickEvent, ClickEvent> {\n\n\tprivate bo... | import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.playgrounds.ops.clickcount.functions.BackpressureMap;
import org.apache.flink.playgrounds.ops.clickcount.functions.ClickEventStatisticsCollector;
import org.apache.flink.playgrounds.ops.clickcount.functions.CountingAggregator;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEvent;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEventDeserializationSchema;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEventStatistics;
import org.apache.flink.playgrounds.ops.clickcount.records.ClickEventStatisticsSerializationSchema;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.WindowAssigner;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import java.time.Duration;
import java.util.Properties;
import java.util.concurrent.TimeUnit; | 3,093 | /*
* 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 org.apache.flink.playgrounds.ops.clickcount;
/**
* A simple streaming job reading {@link ClickEvent}s from Kafka, counting events per 15 seconds and
* writing the resulting {@link ClickEventStatistics} back to Kafka.
*
* <p> It can be run with or without checkpointing and with event time or processing time semantics.
* </p>
*
* <p>The Job can be configured via the command line:</p>
* * "--checkpointing": enables checkpointing
* * "--event-time": use an event time window assigner
* * "--backpressure": insert an operator that causes periodic backpressure
* * "--input-topic": the name of the Kafka Topic to consume {@link ClickEvent}s from
* * "--output-topic": the name of the Kafka Topic to produce {@link ClickEventStatistics} to
* * "--bootstrap.servers": comma-separated list of Kafka brokers
*
*/
public class ClickEventCount {
public static final String CHECKPOINTING_OPTION = "checkpointing";
public static final String EVENT_TIME_OPTION = "event-time";
public static final String BACKPRESSURE_OPTION = "backpressure";
public static final String OPERATOR_CHAINING_OPTION = "chaining";
public static final Time WINDOW_SIZE = Time.of(15, TimeUnit.SECONDS);
public static void main(String[] args) throws Exception {
final ParameterTool params = ParameterTool.fromArgs(args);
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
configureEnvironment(params, env);
boolean inflictBackpressure = params.has(BACKPRESSURE_OPTION);
String inputTopic = params.get("input-topic", "input");
String outputTopic = params.get("output-topic", "output");
String brokers = params.get("bootstrap.servers", "localhost:9092");
Properties kafkaProps = new Properties();
kafkaProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
kafkaProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "click-event-count");
KafkaSource<ClickEvent> source = KafkaSource.<ClickEvent>builder()
.setTopics(inputTopic)
.setValueOnlyDeserializer(new ClickEventDeserializationSchema())
.setProperties(kafkaProps)
.build();
WatermarkStrategy<ClickEvent> watermarkStrategy = WatermarkStrategy
.<ClickEvent>forBoundedOutOfOrderness(Duration.ofMillis(200))
.withIdleness(Duration.ofSeconds(5))
.withTimestampAssigner((clickEvent, l) -> clickEvent.getTimestamp().getTime());
DataStream<ClickEvent> clicks = env.fromSource(source, watermarkStrategy, "ClickEvent Source");
if (inflictBackpressure) {
// Force a network shuffle so that the backpressure will affect the buffer pools
clicks = clicks
.keyBy(ClickEvent::getPage)
.map(new BackpressureMap())
.name("Backpressure");
}
WindowAssigner<Object, TimeWindow> assigner = params.has(EVENT_TIME_OPTION) ?
TumblingEventTimeWindows.of(WINDOW_SIZE) :
TumblingProcessingTimeWindows.of(WINDOW_SIZE);
DataStream<ClickEventStatistics> statistics = clicks
.keyBy(ClickEvent::getPage)
.window(assigner) | /*
* 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 org.apache.flink.playgrounds.ops.clickcount;
/**
* A simple streaming job reading {@link ClickEvent}s from Kafka, counting events per 15 seconds and
* writing the resulting {@link ClickEventStatistics} back to Kafka.
*
* <p> It can be run with or without checkpointing and with event time or processing time semantics.
* </p>
*
* <p>The Job can be configured via the command line:</p>
* * "--checkpointing": enables checkpointing
* * "--event-time": use an event time window assigner
* * "--backpressure": insert an operator that causes periodic backpressure
* * "--input-topic": the name of the Kafka Topic to consume {@link ClickEvent}s from
* * "--output-topic": the name of the Kafka Topic to produce {@link ClickEventStatistics} to
* * "--bootstrap.servers": comma-separated list of Kafka brokers
*
*/
public class ClickEventCount {
public static final String CHECKPOINTING_OPTION = "checkpointing";
public static final String EVENT_TIME_OPTION = "event-time";
public static final String BACKPRESSURE_OPTION = "backpressure";
public static final String OPERATOR_CHAINING_OPTION = "chaining";
public static final Time WINDOW_SIZE = Time.of(15, TimeUnit.SECONDS);
public static void main(String[] args) throws Exception {
final ParameterTool params = ParameterTool.fromArgs(args);
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
configureEnvironment(params, env);
boolean inflictBackpressure = params.has(BACKPRESSURE_OPTION);
String inputTopic = params.get("input-topic", "input");
String outputTopic = params.get("output-topic", "output");
String brokers = params.get("bootstrap.servers", "localhost:9092");
Properties kafkaProps = new Properties();
kafkaProps.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
kafkaProps.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "click-event-count");
KafkaSource<ClickEvent> source = KafkaSource.<ClickEvent>builder()
.setTopics(inputTopic)
.setValueOnlyDeserializer(new ClickEventDeserializationSchema())
.setProperties(kafkaProps)
.build();
WatermarkStrategy<ClickEvent> watermarkStrategy = WatermarkStrategy
.<ClickEvent>forBoundedOutOfOrderness(Duration.ofMillis(200))
.withIdleness(Duration.ofSeconds(5))
.withTimestampAssigner((clickEvent, l) -> clickEvent.getTimestamp().getTime());
DataStream<ClickEvent> clicks = env.fromSource(source, watermarkStrategy, "ClickEvent Source");
if (inflictBackpressure) {
// Force a network shuffle so that the backpressure will affect the buffer pools
clicks = clicks
.keyBy(ClickEvent::getPage)
.map(new BackpressureMap())
.name("Backpressure");
}
WindowAssigner<Object, TimeWindow> assigner = params.has(EVENT_TIME_OPTION) ?
TumblingEventTimeWindows.of(WINDOW_SIZE) :
TumblingProcessingTimeWindows.of(WINDOW_SIZE);
DataStream<ClickEventStatistics> statistics = clicks
.keyBy(ClickEvent::getPage)
.window(assigner) | .aggregate(new CountingAggregator(), | 2 | 2023-12-10 14:25:58+00:00 | 4k |
bggRGjQaUbCoE/c001apk | app/src/main/java/com/example/c001apk/view/vertical/VerticalTabLayout.java | [
{
"identifier": "TabAdapter",
"path": "app/src/main/java/com/example/c001apk/view/vertical/adapter/TabAdapter.java",
"snippet": "public interface TabAdapter {\n int getCount();\n\n TabView.TabBadge getBadge(int position);\n\n TabView.TabIcon getIcon(int position);\n\n TabView.TabTitle getTit... | import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_IDLE;
import static androidx.viewpager.widget.ViewPager.SCROLL_STATE_SETTLING;
import android.animation.AnimatorSet;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.c001apk.R;
import com.example.c001apk.view.vertical.adapter.TabAdapter;
import com.example.c001apk.view.vertical.util.DisplayUtil;
import com.example.c001apk.view.vertical.util.TabFragmentManager;
import com.example.c001apk.view.vertical.widget.QTabView;
import com.example.c001apk.view.vertical.widget.TabView;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List; | 2,698 | package com.example.c001apk.view.vertical;
/**
* @author chqiu
* Email:qstumn@163.com
*/
public class VerticalTabLayout extends ScrollView {
private final Context mContext;
private TabStrip mTabStrip;
private int mColorIndicator; | package com.example.c001apk.view.vertical;
/**
* @author chqiu
* Email:qstumn@163.com
*/
public class VerticalTabLayout extends ScrollView {
private final Context mContext;
private TabStrip mTabStrip;
private int mColorIndicator; | private TabView mSelectedTab; | 2 | 2023-12-18 15:02:49+00:00 | 4k |
rcaneppele/simple-openai-client | src/test/java/br/com/rcaneppele/openai/endpoints/chatcompletion/request/stream/ChatCompletionStreamRequestSenderTest.java | [
{
"identifier": "OpenAIModel",
"path": "src/main/java/br/com/rcaneppele/openai/common/OpenAIModel.java",
"snippet": "public enum OpenAIModel {\n\n GPT_3_5_TURBO_1106(\"gpt-3.5-turbo-1106\"),\n GPT_3_5_TURBO(\"gpt-3.5-turbo\"),\n GPT_3_5_TURBO_16k(\"gpt-3.5-turbo-16k\"),\n GPT_3_5_TURBO_INSTR... | import br.com.rcaneppele.openai.common.OpenAIModel;
import br.com.rcaneppele.openai.common.json.JsonConverter;
import br.com.rcaneppele.openai.common.request.HttpMethod;
import br.com.rcaneppele.openai.endpoints.BaseRequestSenderTest;
import br.com.rcaneppele.openai.endpoints.chatcompletion.request.ChatCompletionRequest;
import br.com.rcaneppele.openai.endpoints.chatcompletion.request.ChatCompletionRequestBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotNull; | 3,108 | package br.com.rcaneppele.openai.endpoints.chatcompletion.request.stream;
class ChatCompletionStreamRequestSenderTest extends BaseRequestSenderTest {
private ChatCompletionStreamRequestSender sender;
private JsonConverter<ChatCompletionRequest> jsonConverter;
private ChatCompletionRequestBuilder builder;
@Override
protected String expectedURI() {
return "chat/completions";
}
@Override
protected String mockJsonResponse() {
return "data: {}";
}
@BeforeEach
void setUp() {
this.sender = new ChatCompletionStreamRequestSender(url, TIMEOUT, API_KEY);
this.jsonConverter = new JsonConverter<>(ChatCompletionRequest.class);
this.builder = new ChatCompletionRequestBuilder();
}
@Test
public void shouldSendRequest() {
var request = builder
.model(OpenAIModel.GPT_4_1106_PREVIEW)
.userMessage("the user message")
.build();
var testObserver = sender.sendStreamRequest(request).test();
testObserver.assertNoErrors();
testObserver.assertNotComplete();
assertNotNull(testObserver.values());
var expectedRequestBody = jsonConverter.convertRequestToJson(request); | package br.com.rcaneppele.openai.endpoints.chatcompletion.request.stream;
class ChatCompletionStreamRequestSenderTest extends BaseRequestSenderTest {
private ChatCompletionStreamRequestSender sender;
private JsonConverter<ChatCompletionRequest> jsonConverter;
private ChatCompletionRequestBuilder builder;
@Override
protected String expectedURI() {
return "chat/completions";
}
@Override
protected String mockJsonResponse() {
return "data: {}";
}
@BeforeEach
void setUp() {
this.sender = new ChatCompletionStreamRequestSender(url, TIMEOUT, API_KEY);
this.jsonConverter = new JsonConverter<>(ChatCompletionRequest.class);
this.builder = new ChatCompletionRequestBuilder();
}
@Test
public void shouldSendRequest() {
var request = builder
.model(OpenAIModel.GPT_4_1106_PREVIEW)
.userMessage("the user message")
.build();
var testObserver = sender.sendStreamRequest(request).test();
testObserver.assertNoErrors();
testObserver.assertNotComplete();
assertNotNull(testObserver.values());
var expectedRequestBody = jsonConverter.convertRequestToJson(request); | executeRequestAssertions(expectedRequestBody, 1, HttpMethod.POST, false); | 2 | 2023-12-21 19:17:56+00:00 | 4k |
373675032/smart-medicine | src/main/java/world/xuewei/service/FeedbackService.java | [
{
"identifier": "FeedbackDao",
"path": "src/main/java/world/xuewei/dao/FeedbackDao.java",
"snippet": "@Repository\npublic interface FeedbackDao extends BaseMapper<Feedback> {\n\n}"
},
{
"identifier": "Feedback",
"path": "src/main/java/world/xuewei/entity/Feedback.java",
"snippet": "@Data... | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import world.xuewei.dao.FeedbackDao;
import world.xuewei.entity.Feedback;
import world.xuewei.utils.Assert;
import world.xuewei.utils.BeanUtil;
import world.xuewei.utils.VariableNameUtils;
import java.io.Serializable;
import java.util.List;
import java.util.Map; | 2,632 | package world.xuewei.service;
/**
* 反馈服务类
*
* @author XUEW
*/
@Service
public class FeedbackService extends BaseService<Feedback> {
@Autowired
protected FeedbackDao userDao;
@Override
public List<Feedback> query(Feedback o) {
QueryWrapper<Feedback> wrapper = new QueryWrapper();
if (Assert.notEmpty(o)) { | package world.xuewei.service;
/**
* 反馈服务类
*
* @author XUEW
*/
@Service
public class FeedbackService extends BaseService<Feedback> {
@Autowired
protected FeedbackDao userDao;
@Override
public List<Feedback> query(Feedback o) {
QueryWrapper<Feedback> wrapper = new QueryWrapper();
if (Assert.notEmpty(o)) { | Map<String, Object> bean2Map = BeanUtil.bean2Map(o); | 3 | 2023-12-16 11:16:11+00:00 | 4k |
C0urante/joplin | src/main/java/io/github/c0urante/joplin/HueEntertainmentClient.java | [
{
"identifier": "DtlsClient",
"path": "src/main/java/io/github/c0urante/joplin/internal/DtlsClient.java",
"snippet": "public class DtlsClient implements AutoCloseable {\n\n private final DTLSTransport transport;\n\n public DtlsClient(String hostnameOrIpAddress, int port, TlsPSKIdentity pskIdentity) th... | import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.c0urante.joplin.internal.DtlsClient;
import io.github.c0urante.joplin.internal.InsecureSslContextFactory;
import io.github.c0urante.joplin.internal.Serialization;
import io.github.c0urante.joplin.internal.Validation;
import org.bouncycastle.tls.BasicTlsPSKIdentity;
import org.bouncycastle.tls.TlsPSKIdentity;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.IntStream; | 2,060 | /*
* Copyright © 2023 Chris Egerton (fearthecellos@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.c0urante.joplin;
/**
* A synchronous client for the
* <a href="https://developers.meethue.com/develop/hue-entertainment/hue-entertainment-api/">
* Philips Hue Entertainment API</a>.
* <p>
* This client can prepare a stream for initialization
*/
public class HueEntertainmentClient implements AutoCloseable {
private static final Duration REST_CONNECT_TIMEOUT = Duration.ofSeconds(5);
private static final int TRIES = 3;
private final TlsPSKIdentity pskIdentity;
private final String host;
private final int port;
private final String username;
private final byte colorSpace;
private final byte[] entertainmentArea;
private final URI baseUri;
private final HttpClient httpClient;
private Thread httpThread; | /*
* Copyright © 2023 Chris Egerton (fearthecellos@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.c0urante.joplin;
/**
* A synchronous client for the
* <a href="https://developers.meethue.com/develop/hue-entertainment/hue-entertainment-api/">
* Philips Hue Entertainment API</a>.
* <p>
* This client can prepare a stream for initialization
*/
public class HueEntertainmentClient implements AutoCloseable {
private static final Duration REST_CONNECT_TIMEOUT = Duration.ofSeconds(5);
private static final int TRIES = 3;
private final TlsPSKIdentity pskIdentity;
private final String host;
private final int port;
private final String username;
private final byte colorSpace;
private final byte[] entertainmentArea;
private final URI baseUri;
private final HttpClient httpClient;
private Thread httpThread; | private DtlsClient dtlsClient = null; | 0 | 2023-12-21 19:01:36+00:00 | 4k |
simasch/vaadin-jooq-template | src/main/java/ch/martinelli/vj/ui/views/user/UserView.java | [
{
"identifier": "Role",
"path": "src/main/java/ch/martinelli/vj/domain/user/Role.java",
"snippet": "public class Role {\n\n public static final String USER = \"USER\";\n public static final String ADMIN = \"ADMIN\";\n\n private Role() {\n }\n}"
},
{
"identifier": "UserService",
"... | import ch.martinelli.vj.domain.user.Role;
import ch.martinelli.vj.domain.user.UserService;
import ch.martinelli.vj.domain.user.UserWithRoles;
import ch.martinelli.vj.ui.components.Notifier;
import ch.martinelli.vj.ui.layout.MainLayout;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.MultiSelectComboBox;
import com.vaadin.flow.component.confirmdialog.ConfirmDialog;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.ColumnTextAlign;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridSortOrder;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.PasswordField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.*;
import io.seventytwo.vaadinjooq.util.VaadinJooqUtil;
import jakarta.annotation.security.RolesAllowed;
import org.jooq.exception.DataAccessException;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Set;
import static ch.martinelli.vj.db.tables.User.USER; | 2,285 | package ch.martinelli.vj.ui.views.user;
@RolesAllowed(Role.ADMIN)
@PageTitle("Users") | package ch.martinelli.vj.ui.views.user;
@RolesAllowed(Role.ADMIN)
@PageTitle("Users") | @Route(value = "users", layout = MainLayout.class) | 4 | 2023-12-20 13:08:17+00:00 | 4k |
373675032/academic-report | src/main/java/world/xuewei/service/DepartmentService.java | [
{
"identifier": "Leader",
"path": "src/main/java/world/xuewei/constant/Leader.java",
"snippet": "public class Leader {\n public static final Integer YES = 1;\n public static final Integer NO = 0;\n}"
},
{
"identifier": "DepartmentMapper",
"path": "src/main/java/world/xuewei/dao/Departm... | import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import world.xuewei.constant.Leader;
import world.xuewei.dao.DepartmentMapper;
import world.xuewei.entity.College;
import world.xuewei.entity.Department;
import world.xuewei.entity.Teacher;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 2,510 | package world.xuewei.service;
/**
* 部门服务
*
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Slf4j
@Service
public class DepartmentService {
@Resource
private DepartmentMapper departmentMapper;
@Resource
private CollegeService collegeService;
@Resource
private TeacherService teacherService;
public boolean insert(Department department) {
return departmentMapper.insert(department) == 1;
}
public boolean deleteById(Integer id) {
return departmentMapper.deleteById(id) == 1;
}
public Department getById(Integer id) {
return departmentMapper.getById(id);
}
public Department getByNo(String no) {
return departmentMapper.getByNo(no);
}
public List<Department> listDepartments() {
return departmentMapper.listDepartments();
}
public List<Department> listDepartments(Department department) {
return departmentMapper.listDepartments(department);
}
public int countDepartments(Department department) {
return departmentMapper.countDepartments(department);
}
public boolean update(Department department) {
return departmentMapper.update(department) == 1;
}
/**
* 分页查询部门
*/
public Map<String, Object> pageAllDepartments(Integer page, Integer rows, String searchField, String searchString) {
Map<String, Object> map = new HashMap<>();
List<Department> departments = new ArrayList<>();
if (StrUtil.isNotEmpty(searchString)) {
// 搜索
Department search = null;
if ("no".equals(searchField)) {
search = Department.builder().no(searchString).build();
}
if ("name".equals(searchField)) {
search = Department.builder().name(searchString).build();
}
if ("college.name".equals(searchField)) {
College college = College.builder().name(searchString).build();
List<College> colleges = collegeService.listColleges(college);
if (colleges.size() > 0) {
search = Department.builder().collegeId(colleges.get(0).getId()).build();
} else {
search = Department.builder().collegeId(-1).build();
}
}
departments = listDepartments(search);
} else {
// 分页查询
PageHelper.startPage(page, rows);
departments = listDepartments();
}
PageInfo<Department> pageInfo = new PageInfo<>(departments);
// 将查询结果放入map
map.put("rows", dealDepartment(departments));
// 总页数
map.put("total", pageInfo.getPages());
// 总条数
map.put("records", pageInfo.getTotal());
return map;
}
/**
* 处理完善部门对象
*/
private List<Department> dealDepartment(List<Department> list) {
list.forEach(department -> {
// 设置学院
Integer collegeId = department.getCollegeId();
College college = collegeService.getById(collegeId);
// 设置部长
Integer leaderId = department.getLeaderId();
Teacher teacher = teacherService.getById(leaderId);
department.setCollege(college);
department.setLeader(teacher);
});
return list;
}
/**
* 编辑部门
*/
public void editDepartment(Department department, String action) {
if ("edit".equals(action)) {
// 编辑
update(department);
// 获取原来部门的信息
Department target = getById(department.getId());
// 获取编辑部门的领导
Teacher teacher = teacherService.getByNo(department.getLeader().getNo());
if (ObjectUtil.isNotEmpty(teacher)) {
if (target.getLeaderId().intValue() != teacher.getId()) {
// 更换领导
Integer oldLeaderId = target.getLeaderId(); | package world.xuewei.service;
/**
* 部门服务
*
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Slf4j
@Service
public class DepartmentService {
@Resource
private DepartmentMapper departmentMapper;
@Resource
private CollegeService collegeService;
@Resource
private TeacherService teacherService;
public boolean insert(Department department) {
return departmentMapper.insert(department) == 1;
}
public boolean deleteById(Integer id) {
return departmentMapper.deleteById(id) == 1;
}
public Department getById(Integer id) {
return departmentMapper.getById(id);
}
public Department getByNo(String no) {
return departmentMapper.getByNo(no);
}
public List<Department> listDepartments() {
return departmentMapper.listDepartments();
}
public List<Department> listDepartments(Department department) {
return departmentMapper.listDepartments(department);
}
public int countDepartments(Department department) {
return departmentMapper.countDepartments(department);
}
public boolean update(Department department) {
return departmentMapper.update(department) == 1;
}
/**
* 分页查询部门
*/
public Map<String, Object> pageAllDepartments(Integer page, Integer rows, String searchField, String searchString) {
Map<String, Object> map = new HashMap<>();
List<Department> departments = new ArrayList<>();
if (StrUtil.isNotEmpty(searchString)) {
// 搜索
Department search = null;
if ("no".equals(searchField)) {
search = Department.builder().no(searchString).build();
}
if ("name".equals(searchField)) {
search = Department.builder().name(searchString).build();
}
if ("college.name".equals(searchField)) {
College college = College.builder().name(searchString).build();
List<College> colleges = collegeService.listColleges(college);
if (colleges.size() > 0) {
search = Department.builder().collegeId(colleges.get(0).getId()).build();
} else {
search = Department.builder().collegeId(-1).build();
}
}
departments = listDepartments(search);
} else {
// 分页查询
PageHelper.startPage(page, rows);
departments = listDepartments();
}
PageInfo<Department> pageInfo = new PageInfo<>(departments);
// 将查询结果放入map
map.put("rows", dealDepartment(departments));
// 总页数
map.put("total", pageInfo.getPages());
// 总条数
map.put("records", pageInfo.getTotal());
return map;
}
/**
* 处理完善部门对象
*/
private List<Department> dealDepartment(List<Department> list) {
list.forEach(department -> {
// 设置学院
Integer collegeId = department.getCollegeId();
College college = collegeService.getById(collegeId);
// 设置部长
Integer leaderId = department.getLeaderId();
Teacher teacher = teacherService.getById(leaderId);
department.setCollege(college);
department.setLeader(teacher);
});
return list;
}
/**
* 编辑部门
*/
public void editDepartment(Department department, String action) {
if ("edit".equals(action)) {
// 编辑
update(department);
// 获取原来部门的信息
Department target = getById(department.getId());
// 获取编辑部门的领导
Teacher teacher = teacherService.getByNo(department.getLeader().getNo());
if (ObjectUtil.isNotEmpty(teacher)) {
if (target.getLeaderId().intValue() != teacher.getId()) {
// 更换领导
Integer oldLeaderId = target.getLeaderId(); | Teacher oldLeader = Teacher.builder().id(oldLeaderId).isDepartmentLeader(Leader.NO).build(); | 0 | 2023-12-21 06:59:12+00:00 | 4k |
misode/packtest | src/main/java/io/github/misode/packtest/mixin/GameTestInfoMixin.java | [
{
"identifier": "ChatListener",
"path": "src/main/java/io/github/misode/packtest/ChatListener.java",
"snippet": "public class ChatListener {\n\n private static final List<ChatListener> listeners = new ArrayList<>();\n\n public static void broadcast(ServerPlayer player, Component chatMessage) {\n ... | import com.llamalad7.mixinextras.sugar.Local;
import io.github.misode.packtest.ChatListener;
import io.github.misode.packtest.PackTestInfo;
import io.github.misode.packtest.dummy.Dummy;
import net.minecraft.gametest.framework.GameTestInfo;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.phys.AABB;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 1,702 | package io.github.misode.packtest.mixin;
/**
* Adds chat listener field and accessors. Removes the listener when finishing.
* Prevents crash when test has already started.
* Clears dummies after succeeding.
*/
@Mixin(GameTestInfo.class)
public abstract class GameTestInfoMixin implements PackTestInfo {
@Shadow
public abstract ServerLevel getLevel();
@Shadow private long tickCount;
@Unique
private ChatListener chatListener;
@Override
public long packtest$getTick() {
return this.tickCount;
}
@Override
public void packtest$setChatListener(ChatListener chatListener) {
this.chatListener = chatListener;
}
@Override
public ChatListener packtest$getChatListener() {
return this.chatListener;
}
@Inject(method = "startTest", cancellable = true, at = @At(value = "INVOKE", target = "Ljava/lang/IllegalStateException;<init>(Ljava/lang/String;)V"))
private void startTest(CallbackInfo ci) {
ci.cancel();
}
@Inject(method = "finish", at = @At("HEAD"))
private void finish(CallbackInfo ci) {
this.chatListener.stop();
}
@Inject(method = "succeed", at = @At(value = "INVOKE", target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", shift = At.Shift.AFTER))
private void succeed(CallbackInfo ci, @Local(ordinal = 0) AABB aabb) { | package io.github.misode.packtest.mixin;
/**
* Adds chat listener field and accessors. Removes the listener when finishing.
* Prevents crash when test has already started.
* Clears dummies after succeeding.
*/
@Mixin(GameTestInfo.class)
public abstract class GameTestInfoMixin implements PackTestInfo {
@Shadow
public abstract ServerLevel getLevel();
@Shadow private long tickCount;
@Unique
private ChatListener chatListener;
@Override
public long packtest$getTick() {
return this.tickCount;
}
@Override
public void packtest$setChatListener(ChatListener chatListener) {
this.chatListener = chatListener;
}
@Override
public ChatListener packtest$getChatListener() {
return this.chatListener;
}
@Inject(method = "startTest", cancellable = true, at = @At(value = "INVOKE", target = "Ljava/lang/IllegalStateException;<init>(Ljava/lang/String;)V"))
private void startTest(CallbackInfo ci) {
ci.cancel();
}
@Inject(method = "finish", at = @At("HEAD"))
private void finish(CallbackInfo ci) {
this.chatListener.stop();
}
@Inject(method = "succeed", at = @At(value = "INVOKE", target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", shift = At.Shift.AFTER))
private void succeed(CallbackInfo ci, @Local(ordinal = 0) AABB aabb) { | this.getLevel().getEntitiesOfClass(Dummy.class, aabb.inflate(1)) | 2 | 2023-12-15 10:08:54+00:00 | 4k |
John200410/rusherhack-spotify | src/main/java/me/john200410/spotify/http/SpotifyAPI.java | [
{
"identifier": "Config",
"path": "src/main/java/me/john200410/spotify/Config.java",
"snippet": "public class Config {\n\t\n\tpublic String appId = \"\";\n\tpublic String appSecret = \"\";\n\tpublic String refresh_token = \"\";\n\t\n}"
},
{
"identifier": "SpotifyPlugin",
"path": "src/main/ja... | import com.google.gson.JsonSyntaxException;
import me.john200410.spotify.Config;
import me.john200410.spotify.SpotifyPlugin;
import me.john200410.spotify.http.responses.CodeGrant;
import me.john200410.spotify.http.responses.PlaybackState;
import me.john200410.spotify.http.responses.Response;
import me.john200410.spotify.http.responses.User;
import net.minecraft.Util;
import org.rusherhack.client.api.RusherHackAPI;
import org.rusherhack.core.notification.NotificationType;
import org.rusherhack.core.utils.MathUtils;
import org.rusherhack.core.utils.Timer;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors; | 2,692 | package me.john200410.spotify.http;
public class SpotifyAPI {
/**
* Constants
*/
public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
private static final String API_URL = "https://api.spotify.com";
private static final String AUTH_URL = "https://accounts.spotify.com";
/**
* Variables
*/
private final SpotifyPlugin plugin;
private boolean isConnected = false;
private boolean playbackAvailable = false; | package me.john200410.spotify.http;
public class SpotifyAPI {
/**
* Constants
*/
public static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
private static final String API_URL = "https://api.spotify.com";
private static final String AUTH_URL = "https://accounts.spotify.com";
/**
* Variables
*/
private final SpotifyPlugin plugin;
private boolean isConnected = false;
private boolean playbackAvailable = false; | private PlaybackState currentStatus; | 3 | 2023-12-19 17:59:37+00:00 | 4k |
SciBorgs/Crescendo-2024 | src/main/java/org/sciborgs1155/robot/Robot.java | [
{
"identifier": "CommandRobot",
"path": "src/main/java/org/sciborgs1155/lib/CommandRobot.java",
"snippet": "public class CommandRobot extends TimedRobot {\n\n protected CommandRobot(double period) {\n super(period);\n }\n\n @Override\n public void robotPeriodic() {\n CommandScheduler.getInstan... | import edu.wpi.first.wpilibj.DataLogManager;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj2.command.ProxyCommand;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import java.util.List;
import monologue.Logged;
import monologue.Monologue;
import monologue.Monologue.LogBoth;
import org.sciborgs1155.lib.CommandRobot;
import org.sciborgs1155.lib.Fallible;
import org.sciborgs1155.lib.SparkUtils;
import org.sciborgs1155.robot.Ports.OI;
import org.sciborgs1155.robot.commands.Autos; | 3,300 | package org.sciborgs1155.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class Robot extends CommandRobot implements Logged, Fallible {
// INPUT DEVICES
private final CommandXboxController operator = new CommandXboxController(OI.OPERATOR);
private final CommandXboxController driver = new CommandXboxController(OI.DRIVER);
// SUBSYSTEMS
// COMMANDS | package org.sciborgs1155.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class Robot extends CommandRobot implements Logged, Fallible {
// INPUT DEVICES
private final CommandXboxController operator = new CommandXboxController(OI.OPERATOR);
private final CommandXboxController driver = new CommandXboxController(OI.DRIVER);
// SUBSYSTEMS
// COMMANDS | @LogBoth Autos autos = new Autos(); | 4 | 2023-12-19 00:56:38+00:00 | 4k |
Swofty-Developments/HypixelSkyBlock | generic/src/main/java/net/swofty/types/generic/item/set/impl/ArmorSet.java | [
{
"identifier": "ArmorSetRegistry",
"path": "generic/src/main/java/net/swofty/types/generic/item/set/ArmorSetRegistry.java",
"snippet": "@Getter\npublic enum ArmorSetRegistry {\n LEAFLET(LeafletSet.class, ItemType.LEAFLET_SANDALS, ItemType.LEAFLET_PANTS, ItemType.LEAFLET_TUNIC, ItemType.LEAFLET_HAT),... | import net.swofty.types.generic.SkyBlockGenericLoader;
import net.swofty.types.generic.item.set.ArmorSetRegistry;
import net.swofty.types.generic.user.SkyBlockPlayer;
import java.util.ArrayList;
import java.util.List; | 3,583 | package net.swofty.types.generic.item.set.impl;
public interface ArmorSet {
String getName();
String getDescription();
default boolean isWearingSet(SkyBlockPlayer player) { | package net.swofty.types.generic.item.set.impl;
public interface ArmorSet {
String getName();
String getDescription();
default boolean isWearingSet(SkyBlockPlayer player) { | return player.getArmorSet() != null && player.getArmorSet().equals(ArmorSetRegistry.getArmorSet(this.getClass())); | 0 | 2023-12-14 09:51:15+00:00 | 4k |
refutix/refutix | refutix-server/src/main/java/org/refutix/refutix/server/controller/TableController.java | [
{
"identifier": "TableDTO",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/dto/TableDTO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TableDTO {\n\n private Integer catalogId;\n\n private String catalogName;\n\n private String d... | import lombok.extern.slf4j.Slf4j;
import org.refutix.refutix.server.data.dto.TableDTO;
import org.refutix.refutix.server.data.model.AlterTableRequest;
import org.refutix.refutix.server.data.result.R;
import org.refutix.refutix.server.data.result.enums.Status;
import org.refutix.refutix.server.data.vo.TableVO;
import org.refutix.refutix.server.service.TableService;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors; | 3,425 | /*
* 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 org.refutix.refutix.server.controller;
/** Table api controller. */
@Slf4j
@RestController
@RequestMapping("/api/table")
public class TableController {
private final TableService tableService;
public TableController(TableService tableService) {
this.tableService = tableService;
}
/**
* Creates a table in the database based on the provided TableInfo.
*
* @param tableDTO The TableDTO object containing information about the table.
* @return R<Void/> indicating the success or failure of the operation.
*/
@PostMapping("/create")
public R<Void> createTable(@RequestBody TableDTO tableDTO) {
return tableService.createTable(tableDTO);
}
/**
* Adds a column to the table.
*
* @param tableDTO The information of the table, including the catalog name, database name,
* table name, and table columns.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/column/add")
public R<Void> addColumn(@RequestBody TableDTO tableDTO) {
return tableService.addColumn(tableDTO);
}
/**
* Drops a column from a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param columnName The name of the column to be dropped.
* @return The result indicating the success or failure of the operation.
*/
@DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}")
public R<Void> dropColumn(
@PathVariable String catalogName,
@PathVariable String databaseName,
@PathVariable String tableName,
@PathVariable String columnName) {
return tableService.dropColumn(catalogName, databaseName, tableName, columnName);
}
/**
* Modify a column in a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param alterTableRequest The param of the alter table request.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/alter")
public R<Void> alterTable(
@RequestParam String catalogName,
@RequestParam String databaseName,
@RequestParam String tableName, | /*
* 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 org.refutix.refutix.server.controller;
/** Table api controller. */
@Slf4j
@RestController
@RequestMapping("/api/table")
public class TableController {
private final TableService tableService;
public TableController(TableService tableService) {
this.tableService = tableService;
}
/**
* Creates a table in the database based on the provided TableInfo.
*
* @param tableDTO The TableDTO object containing information about the table.
* @return R<Void/> indicating the success or failure of the operation.
*/
@PostMapping("/create")
public R<Void> createTable(@RequestBody TableDTO tableDTO) {
return tableService.createTable(tableDTO);
}
/**
* Adds a column to the table.
*
* @param tableDTO The information of the table, including the catalog name, database name,
* table name, and table columns.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/column/add")
public R<Void> addColumn(@RequestBody TableDTO tableDTO) {
return tableService.addColumn(tableDTO);
}
/**
* Drops a column from a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param columnName The name of the column to be dropped.
* @return The result indicating the success or failure of the operation.
*/
@DeleteMapping("/column/drop/{catalogName}/{databaseName}/{tableName}/{columnName}")
public R<Void> dropColumn(
@PathVariable String catalogName,
@PathVariable String databaseName,
@PathVariable String tableName,
@PathVariable String columnName) {
return tableService.dropColumn(catalogName, databaseName, tableName, columnName);
}
/**
* Modify a column in a table.
*
* @param catalogName The name of the catalog.
* @param databaseName The name of the database.
* @param tableName The name of the table.
* @param alterTableRequest The param of the alter table request.
* @return A response indicating the success or failure of the operation.
*/
@PostMapping("/alter")
public R<Void> alterTable(
@RequestParam String catalogName,
@RequestParam String databaseName,
@RequestParam String tableName, | @RequestBody AlterTableRequest alterTableRequest) { | 1 | 2023-12-21 03:39:07+00:00 | 4k |
Tianscar/uxgl | desktop/src/main/java/unrefined/runtime/DesktopConsole.java | [
{
"identifier": "ConsoleSignal",
"path": "desktop/src/main/java/unrefined/desktop/ConsoleSignal.java",
"snippet": "public final class ConsoleSignal {\n\n private ConsoleSignal() {\n throw new NotInstantiableError(ConsoleSignal.class);\n }\n\n private static final Set<Handler> CONSOLE_SIG... | import unrefined.desktop.ConsoleSignal;
import unrefined.io.AlreadyUsedException;
import unrefined.io.console.Console;
import unrefined.io.console.SignalNotFoundException;
import unrefined.io.console.UnhandledSignalException; | 1,723 | package unrefined.runtime;
public class DesktopConsole extends Console {
public DesktopConsole() { | package unrefined.runtime;
public class DesktopConsole extends Console {
public DesktopConsole() { | ConsoleSignal.addConsoleSignalHandler((signal, identifier) -> | 0 | 2023-12-15 19:03:31+00:00 | 4k |
jlokitha/layered-architecture-jlokitha | src/main/java/lk/jl/layeredarchitecture/controller/PlaceOrderFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/lk/jl/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private static BOFactory boFactory;\n\n private BOFactory() {\n\n }\n\n public static BOFactory getBoFactory() {\n return (boFactory == null) ? boFa... | import lk.jl.layeredarchitecture.bo.BOFactory;
import lk.jl.layeredarchitecture.bo.custom.PlaceOrderBO;
import lk.jl.layeredarchitecture.dto.CustomerDTO;
import lk.jl.layeredarchitecture.dto.ItemDTO;
import lk.jl.layeredarchitecture.dto.OrderDetailDTO;
import lk.jl.layeredarchitecture.view.tdm.OrderDetailTM;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 2,099 | package lk.jl.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId; | package lk.jl.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId; | PlaceOrderBO placeOrderBO = (PlaceOrderBO) BOFactory.getBoFactory().getBO( BOFactory.BOType.PLACE_ORDER ); | 1 | 2023-12-16 04:21:58+00:00 | 4k |
lemonguge/autogen4j | src/test/java/cn/homj/autogen4j/GroupChatManagerTest.java | [
{
"identifier": "Client",
"path": "src/main/java/cn/homj/autogen4j/support/Client.java",
"snippet": "public class Client {\n /**\n * application/json\n */\n private static final MediaType APPLICATION_JSON = MediaType.parse(\"application/json\");\n /**\n * OpenAI API\n */\n pr... | import cn.homj.autogen4j.support.Client;
import static cn.homj.autogen4j.Definition.qianWenApiKey; | 2,110 | package cn.homj.autogen4j;
/**
* @author jiehong.jh
* @date 2023/12/1
*/
public class GroupChatManagerTest {
public static void main(String[] args) {
Client client = new Client();
UserProxyAgent user = new UserProxyAgent("Hom J.");
QianWenAgent taylor = new QianWenAgent("Taylor");
QianWenAgent jarvis = new QianWenAgent("Jarvis");
GroupChat groupChat = new GroupChat()
.addAgent(user, "正在寻求帮助的用户")
.addAgent(taylor, "温柔的知心姐姐,当你遇到问题时,总是会给予鼓励和支持。")
.addAgent(jarvis, "旅游达人,可以提供目的地建议、行程规划。");
GroupChatManager manager = taylor.newManager("manager").groupChat(groupChat);
taylor
.client(client)
.model("qwen-plus") | package cn.homj.autogen4j;
/**
* @author jiehong.jh
* @date 2023/12/1
*/
public class GroupChatManagerTest {
public static void main(String[] args) {
Client client = new Client();
UserProxyAgent user = new UserProxyAgent("Hom J.");
QianWenAgent taylor = new QianWenAgent("Taylor");
QianWenAgent jarvis = new QianWenAgent("Jarvis");
GroupChat groupChat = new GroupChat()
.addAgent(user, "正在寻求帮助的用户")
.addAgent(taylor, "温柔的知心姐姐,当你遇到问题时,总是会给予鼓励和支持。")
.addAgent(jarvis, "旅游达人,可以提供目的地建议、行程规划。");
GroupChatManager manager = taylor.newManager("manager").groupChat(groupChat);
taylor
.client(client)
.model("qwen-plus") | .apiKey(qianWenApiKey) | 1 | 2023-12-15 01:43:11+00:00 | 4k |
wenbochang888/min-read-book | house/src/main/java/com/tianya/controller/MybatisPlusController.java | [
{
"identifier": "UserMapper",
"path": "house/src/main/java/com/tianya/dao3/UserMapper.java",
"snippet": "@Repository(\"userMapper\")\npublic interface UserMapper extends BaseMapper<User> {\n\n}"
},
{
"identifier": "TElement",
"path": "house/src/main/java/com/tianya/entity/TElement.java",
... | import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.tianya.dao3.UserMapper;
import com.tianya.entity.TElement;
import com.tianya.entity.User;
import com.tianya.service.TelementService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; | 2,161 | package com.tianya.controller;
/**
* @author changwenbo
* @date 2022/6/14 11:17
*/
@RestController
@Slf4j
public class MybatisPlusController {
@Autowired
private UserMapper userMapper;
@Autowired
private TelementService service;
@RequestMapping("/test/mybatis/test")
public String test() {
TElement element = new TElement();
element.setfElementName("111");
log.info("element = {}", JSON.toJSONString(element));
boolean save = service.save(element);
log.info("save = {}, element = {}", save, JSON.toJSONString(element));
return "ok";
}
@RequestMapping("/test/mybatis/page")
public String testPublish0(String str, int page, int current) {
List<Integer> list = Lists.newArrayList(1, 2,3 ,4,5 ,6);
List<Integer> remove = Lists.newArrayList(2, 5);
System.out.println(list);
list.removeIf(remove::contains);
System.out.println(list);
return "ok";
}
@RequestMapping("/test/mybatis/select/one")
public String testPublish1() {
| package com.tianya.controller;
/**
* @author changwenbo
* @date 2022/6/14 11:17
*/
@RestController
@Slf4j
public class MybatisPlusController {
@Autowired
private UserMapper userMapper;
@Autowired
private TelementService service;
@RequestMapping("/test/mybatis/test")
public String test() {
TElement element = new TElement();
element.setfElementName("111");
log.info("element = {}", JSON.toJSONString(element));
boolean save = service.save(element);
log.info("save = {}, element = {}", save, JSON.toJSONString(element));
return "ok";
}
@RequestMapping("/test/mybatis/page")
public String testPublish0(String str, int page, int current) {
List<Integer> list = Lists.newArrayList(1, 2,3 ,4,5 ,6);
List<Integer> remove = Lists.newArrayList(2, 5);
System.out.println(list);
list.removeIf(remove::contains);
System.out.println(list);
return "ok";
}
@RequestMapping("/test/mybatis/select/one")
public String testPublish1() {
| LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery(User.class); | 2 | 2023-12-18 13:31:20+00:00 | 4k |
Valerde/vadb | va-collection/src/main/java/com/sovava/vacollection/valist/VaArrayList.java | [
{
"identifier": "VaPredicate",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/function/VaPredicate.java",
"snippet": "@FunctionalInterface\npublic interface VaPredicate<T> {\n /**\n * description: 判断输入的参数t是否满足断言\n *\n * @Author sovava\n * @Date 12/18/23 6:02 PM\n ... | import com.sovava.vacollection.api.*;
import com.sovava.vacollection.api.function.VaPredicate;
import com.sovava.vacollection.api.function.VaUnaryOperator;
import com.sovava.vacollection.collections.VaArrays;
import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer; | 2,991 | }
@Override
public int indexOf(Object o) {
if (null == o) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Object[] toVaArray() {
return VaArrays.copyOf(elementData, size);
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toVaArray(T[] ts) {
if (ts.length < size) {
return (T[]) VaArrays.copyOf(ts, size, ts.getClass());
}
System.arraycopy(elementData, 0, ts, 0, size);
if (ts.length > size) {
ts[size] = null;
}
return ts;
}
@Override
public int lastIndexOf(Object o) {
if (null == o) {
for (int i = size - 1; i > 0; i--) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i > 0; i--) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
protected Object clone() throws CloneNotSupportedException {
VaArrayList<?> clone = (VaArrayList<?>) super.clone();
clone.elementData = VaArrays.copyOf(this.elementData, size);
return clone;
}
@Override
public boolean removeAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
private boolean batchRemove(VaCollection<?> c, boolean exit) {
Object[] dataTmp = this.elementData;
int toIdx, newSize = 0;
boolean modified = false;
for (toIdx = 0; toIdx < size; toIdx++) {
if (c.contains(dataTmp[toIdx]) == exit) {
dataTmp[newSize++] = dataTmp[toIdx];
}
}
if (newSize != size) {
for (int i = newSize; i < size; i++) {
dataTmp[i] = null;
}
size = newSize;
modified = true;
}
return modified;
}
@Override
public boolean retainAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
@Override
public void replaceAll(VaUnaryOperator<E> operator) {
Objects.requireNonNull(operator);
int size = this.size;
for (int i = 0; i < size; i++) {
elementData[i] = operator.apply(elementData(i));
}
}
@Override
public void forEach(VaConsumer<? super E> action) {
Objects.requireNonNull(action);
int size = this.size;
for (int i = 0; i < size; i++) {
action.accept(elementData(i));
}
}
@Override | package com.sovava.vacollection.valist;
/**
* Description: 由于后续不会将此类用于线程不安全场景,因此暂不对类中的方法做快速失败与对线程安全的一些基本措施
*
* @author: ykn
* @date: 2023年12月25日 8:32 PM
**/
public class VaArrayList<E> extends VaAbstractList<E> implements VaList<E>, RandomAccess, Cloneable, Serializable {
private static final long serialVersionUID = 5716796482536510252L;
/**
* 默认大小, 10
*/
private static final int DEFAULT_CAPACITY = 10;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 用于空实例的共享数组实例
*/
private static final Object[] EMPTY_ELEMENT_DATA = {};
/**
* 用于默认大小的空实例
*/
private static final Object[] DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA = {};
Object[] elementData;
private int size;
public VaArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENT_DATA;
} else {
throw new IllegalArgumentException("不合理的容量:" + initialCapacity);
}
}
public VaArrayList() {
this.elementData = DEFAULT_CAPACITY_EMPTY_ELEMENT_DATA;
}
public VaArrayList(VaCollection<? extends E> c) {
elementData = c.toVaArray();
if ((size = elementData.length) != 0) {
if (elementData.getClass() != Object[].class) {
elementData = VaArrays.copyOf(elementData, size, Object[].class);
}
} else {
this.elementData = EMPTY_ELEMENT_DATA;
}
}
@SuppressWarnings("unchecked")
E elementData(int idx) {
return (E) elementData[idx];
}
public int size() {
return size;
}
public E set(int idx, E e) {
rangeCheck(idx);
E oldV = elementData(idx);
elementData[idx] = e;
return oldV;
}
@Override
public E get(int idx) {
rangeCheck(idx);
return elementData(idx);
}
@Override
public boolean add(E e) {
ensureCapInternal(size + 1);
elementData[size++] = e;
return true;
}
@Override
public void add(int idx, E e) {
rangeCheck(idx);
ensureCapInternal(size + 1);
System.arraycopy(elementData, idx, elementData, idx + 1, size - idx);
elementData[idx] = e;
size++;
}
@Override
public E remove(int idx) {
rangeCheck(idx);
E oldV = elementData(idx);
int numMoved = size - idx - 1;
if (numMoved > 0) {
System.arraycopy(elementData, idx + 1, elementData, idx, numMoved);
}
elementData[size--] = null;
return oldV;
}
@Override
public boolean remove(Object o) {
if (null == o) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
fastRemove(i);
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
fastRemove(i);
return true;
}
}
}
return false;
}
private void fastRemove(int idx) {
int numMoved = size - idx - 1;
if (numMoved > 0) {
System.arraycopy(elementData, idx + 1, elementData, idx, numMoved);
}
elementData[--size] = null;
}
public void clear() {
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
public boolean addAll(VaCollection<? extends E> c) {
return addAll(size, c);
}
public boolean addAll(int index, VaCollection<? extends E> c) {
rangeCheckForAdd(index);
Object[] cs = c.toVaArray();
int csSize = c.size();
if (csSize == 0) return false;
ensureCapInternal(size + csSize);
int numMoved = size - index;
if (numMoved > 0) {
System.arraycopy(elementData, index, elementData, index + csSize, numMoved);
}
System.arraycopy(cs, 0, elementData, index, csSize);
size += csSize;
return true;
}
protected void removeRange(int fromIndex, int toIndex) {
System.arraycopy(elementData, toIndex, elementData, fromIndex, toIndex - fromIndex);
int newSize = size - (toIndex - fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
public void ensureCapInternal(int minCap) {
ensureLegalCap(calcCap(elementData, minCap));
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public int indexOf(Object o) {
if (null == o) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Object[] toVaArray() {
return VaArrays.copyOf(elementData, size);
}
@Override
@SuppressWarnings("unchecked")
public <T> T[] toVaArray(T[] ts) {
if (ts.length < size) {
return (T[]) VaArrays.copyOf(ts, size, ts.getClass());
}
System.arraycopy(elementData, 0, ts, 0, size);
if (ts.length > size) {
ts[size] = null;
}
return ts;
}
@Override
public int lastIndexOf(Object o) {
if (null == o) {
for (int i = size - 1; i > 0; i--) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i > 0; i--) {
if (o.equals(elementData[i])) {
return i;
}
}
}
return -1;
}
@Override
protected Object clone() throws CloneNotSupportedException {
VaArrayList<?> clone = (VaArrayList<?>) super.clone();
clone.elementData = VaArrays.copyOf(this.elementData, size);
return clone;
}
@Override
public boolean removeAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
private boolean batchRemove(VaCollection<?> c, boolean exit) {
Object[] dataTmp = this.elementData;
int toIdx, newSize = 0;
boolean modified = false;
for (toIdx = 0; toIdx < size; toIdx++) {
if (c.contains(dataTmp[toIdx]) == exit) {
dataTmp[newSize++] = dataTmp[toIdx];
}
}
if (newSize != size) {
for (int i = newSize; i < size; i++) {
dataTmp[i] = null;
}
size = newSize;
modified = true;
}
return modified;
}
@Override
public boolean retainAll(VaCollection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
@Override
public void replaceAll(VaUnaryOperator<E> operator) {
Objects.requireNonNull(operator);
int size = this.size;
for (int i = 0; i < size; i++) {
elementData[i] = operator.apply(elementData(i));
}
}
@Override
public void forEach(VaConsumer<? super E> action) {
Objects.requireNonNull(action);
int size = this.size;
for (int i = 0; i < size; i++) {
action.accept(elementData(i));
}
}
@Override | public boolean removeIf(VaPredicate<? super E> filter) { | 0 | 2023-12-17 13:29:10+00:00 | 4k |
alexeytereshchenko/CodeGuardian | plugin/src/main/java/io/github/alexeytereshchenko/guardian/GuardianPlugin.java | [
{
"identifier": "ErrorProneExtension",
"path": "plugin/src/main/java/io/github/alexeytereshchenko/guardian/extention/ErrorProneExtension.java",
"snippet": "public class ErrorProneExtension {\n private boolean enable = true;\n private String dependency = \"com.google.errorprone:error_prone_core:2.23.0\... | import io.github.alexeytereshchenko.guardian.extention.ErrorProneExtension;
import io.github.alexeytereshchenko.guardian.extention.GuardianCheckStyleExtension;
import io.github.alexeytereshchenko.guardian.extention.GuardianExtension;
import io.github.alexeytereshchenko.guardian.meta.TaskName;
import net.ltgt.gradle.errorprone.CheckSeverity;
import net.ltgt.gradle.errorprone.ErrorProneCompilerArgumentProvider;
import net.ltgt.gradle.errorprone.ErrorProneOptions;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.file.DuplicatesStrategy;
import org.gradle.api.plugins.quality.Checkstyle;
import org.gradle.api.plugins.quality.CheckstyleExtension;
import org.gradle.api.tasks.Copy;
import org.gradle.api.tasks.Delete;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.language.base.internal.plugins.CleanRule;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.Set;
import io.github.alexeytereshchenko.guardian.task.DownloadCheckstyleFile; | 3,178 | package io.github.alexeytereshchenko.guardian;
public class GuardianPlugin implements Plugin<Project> {
@Override
public void apply(@NotNull Project project) {
project.getExtensions().create("guardian", GuardianExtension.class);
project.afterEvaluate(evaluatedProject -> {
GuardianExtension guardianExtension = project.getExtensions()
.getByType(GuardianExtension.class);
configurePlugins(evaluatedProject);
configureDependencies(evaluatedProject, guardianExtension);
configureErrorProne(evaluatedProject, guardianExtension);
configureGitHooks(evaluatedProject, guardianExtension);
boolean enableChecker = guardianExtension.getCheckStyle().isEnable();
if (enableChecker) {
project.getPlugins().apply("checkstyle");
configureValidateStyleTask(evaluatedProject);
configureDownloadConfigFileTask(evaluatedProject, guardianExtension);
configureCheckstyle(project, guardianExtension);
}
});
}
private void configurePlugins(Project project) {
Set<String> plugins = Set.of("java", "net.ltgt.errorprone");
plugins.stream()
.filter(plugin -> !project.getPlugins().hasPlugin(plugin))
.forEach(plugin -> project.getPlugins().apply(plugin));
}
private void configureDependencies(Project project, GuardianExtension guardianExtension) { | package io.github.alexeytereshchenko.guardian;
public class GuardianPlugin implements Plugin<Project> {
@Override
public void apply(@NotNull Project project) {
project.getExtensions().create("guardian", GuardianExtension.class);
project.afterEvaluate(evaluatedProject -> {
GuardianExtension guardianExtension = project.getExtensions()
.getByType(GuardianExtension.class);
configurePlugins(evaluatedProject);
configureDependencies(evaluatedProject, guardianExtension);
configureErrorProne(evaluatedProject, guardianExtension);
configureGitHooks(evaluatedProject, guardianExtension);
boolean enableChecker = guardianExtension.getCheckStyle().isEnable();
if (enableChecker) {
project.getPlugins().apply("checkstyle");
configureValidateStyleTask(evaluatedProject);
configureDownloadConfigFileTask(evaluatedProject, guardianExtension);
configureCheckstyle(project, guardianExtension);
}
});
}
private void configurePlugins(Project project) {
Set<String> plugins = Set.of("java", "net.ltgt.errorprone");
plugins.stream()
.filter(plugin -> !project.getPlugins().hasPlugin(plugin))
.forEach(plugin -> project.getPlugins().apply(plugin));
}
private void configureDependencies(Project project, GuardianExtension guardianExtension) { | ErrorProneExtension errorProne = guardianExtension.getErrorProne(); | 0 | 2023-12-21 17:03:07+00:00 | 4k |
chamithKavinda/layered-architecture-ChamithKavinda | src/main/java/com/example/layeredarchitecture/bo/custom/impl/PlaceOrderBOImpl.java | [
{
"identifier": "PlaceOrderBO",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/PlaceOrderBO.java",
"snippet": "public interface PlaceOrderBO extends SuperBO {\n\n boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQL... | import com.example.layeredarchitecture.bo.custom.PlaceOrderBO;
import com.example.layeredarchitecture.dao.DAOFactory;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.dto.CustomerDTO;
import com.example.layeredarchitecture.dto.ItemDTO;
import com.example.layeredarchitecture.dto.OrderDetailDTO;
import com.example.layeredarchitecture.entity.Customer;
import com.example.layeredarchitecture.entity.Item;
import com.example.layeredarchitecture.entity.Order;
import com.example.layeredarchitecture.entity.OrderDetail;
import com.example.layeredarchitecture.dao.custom.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List; | 3,328 | package com.example.layeredarchitecture.bo.custom.impl;
public class PlaceOrderBOImpl implements PlaceOrderBO {
OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER);
CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);
ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM);
OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL);
QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY);
@Override
public boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {
Connection connection = null;
connection= DBConnection.getDbConnection().getConnection();
boolean b1 = orderDAO.exist(orderId);
if (b1) {
return false;
}
connection.setAutoCommit(false);
boolean b2 = orderDAO.save(new Order(orderId, orderDate, customerId));
if (!b2) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
for (OrderDetailDTO detail : orderDetails) {
boolean b3 = orderDetailsDAO.save(new OrderDetail(detail.getOid(),detail.getItemCode(),detail.getQty(),detail.getUnitPrice()));
if (!b3) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
ItemDTO item = findItem(detail.getItemCode());
item.setQtyOnHand(item.getQtyOnHand() - detail.getQty());
| package com.example.layeredarchitecture.bo.custom.impl;
public class PlaceOrderBOImpl implements PlaceOrderBO {
OrderDAO orderDAO = (OrderDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER);
CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);
ItemDAO itemDAO = (ItemDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ITEM);
OrderDetailsDAO orderDetailsDAO = (OrderDetailsDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.ORDER_DETAIL);
QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.QUERY);
@Override
public boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException {
Connection connection = null;
connection= DBConnection.getDbConnection().getConnection();
boolean b1 = orderDAO.exist(orderId);
if (b1) {
return false;
}
connection.setAutoCommit(false);
boolean b2 = orderDAO.save(new Order(orderId, orderDate, customerId));
if (!b2) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
for (OrderDetailDTO detail : orderDetails) {
boolean b3 = orderDetailsDAO.save(new OrderDetail(detail.getOid(),detail.getItemCode(),detail.getQty(),detail.getUnitPrice()));
if (!b3) {
connection.rollback();
connection.setAutoCommit(true);
return false;
}
ItemDTO item = findItem(detail.getItemCode());
item.setQtyOnHand(item.getQtyOnHand() - detail.getQty());
| boolean b = itemDAO.update(new Item(item.getCode(), item.getDescription(), item.getUnitPrice(), item.getQtyOnHand())); | 7 | 2023-12-16 04:21:25+00:00 | 4k |
akpaevj/OpenAPI.1C | ru.akpaev.dt.openapi/src/ru/akpaev/dt/openapi/models/OpenApiRoot.java | [
{
"identifier": "Activator",
"path": "ru.akpaev.dt.openapi/src/ru/akpaev/dt/openapi/Activator.java",
"snippet": "public class Activator\n extends AbstractUIPlugin\n{\n public static final String PLUGIN_ID = \"ru.akpaev.dt.openapi\"; //$NON-NLS-1$\n private static Activator plugin;\n private ... | import java.io.FileInputStream;
import java.util.Map;
import java.util.regex.Pattern;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.base.Charsets;
import ru.akpaev.dt.openapi.Activator;
import ru.akpaev.dt.openapi.StringUtil; | 2,064 | /**
*
*/
package ru.akpaev.dt.openapi.models;
/**
* @author akpaev.e
*
*/
public class OpenApiRoot
{
private static Pattern inFileRefPartsPattern = Pattern.compile("(?<=/).+?(?=(/|$))"); //$NON-NLS-1$
private String fileContent;
private OpenApiInfo info;
private Map<String, OpenApiPath> paths;
private OpenApiComponents components;
public static OpenApiRoot deserializeFromFile(String path)
{
var root = new OpenApiRoot();
try (var stream = new FileInputStream(path))
{
var fileContent = new String(stream.readAllBytes(), Charsets.UTF_8);
var mapper = new ObjectMapper(new YAMLFactory());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.findAndRegisterModules();
root = mapper.readValue(fileContent, OpenApiRoot.class);
root.setFileContent(fileContent);
}
catch (Exception e)
{ | /**
*
*/
package ru.akpaev.dt.openapi.models;
/**
* @author akpaev.e
*
*/
public class OpenApiRoot
{
private static Pattern inFileRefPartsPattern = Pattern.compile("(?<=/).+?(?=(/|$))"); //$NON-NLS-1$
private String fileContent;
private OpenApiInfo info;
private Map<String, OpenApiPath> paths;
private OpenApiComponents components;
public static OpenApiRoot deserializeFromFile(String path)
{
var root = new OpenApiRoot();
try (var stream = new FileInputStream(path))
{
var fileContent = new String(stream.readAllBytes(), Charsets.UTF_8);
var mapper = new ObjectMapper(new YAMLFactory());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.findAndRegisterModules();
root = mapper.readValue(fileContent, OpenApiRoot.class);
root.setFileContent(fileContent);
}
catch (Exception e)
{ | Activator.logError(e); | 0 | 2023-12-15 22:41:41+00:00 | 4k |
ZakariaAitAli/MesDepensesTelecom | app/src/main/java/com/gi3/mesdepensestelecom/ui/recharge/RechargeSupplementFragment.java | [
{
"identifier": "getKeyByValue",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/ui/abonnement_form/AbonnementFragment.java",
"snippet": "public static int getKeyByValue(HashMap<Integer, String> hashMap, String value) {\n for (HashMap.Entry<Integer, String> entry : hashMap.entrySet()) {\n ... | import static android.content.Context.MODE_PRIVATE;
import static com.gi3.mesdepensestelecom.R.*;
import static com.gi3.mesdepensestelecom.ui.abonnement_form.AbonnementFragment.getKeyByValue;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.gi3.mesdepensestelecom.Models.Abonnement;
import com.gi3.mesdepensestelecom.Models.Recharge;
import com.gi3.mesdepensestelecom.Models.Supplement;
import com.gi3.mesdepensestelecom.R;
import com.gi3.mesdepensestelecom.database.RechargeRepository;
import com.gi3.mesdepensestelecom.database.SupplementRepository;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; | 2,402 | package com.gi3.mesdepensestelecom.ui.recharge;
/**
* A simple {@link Fragment} subclass.
* Use the {@link RechargeSupplementFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RechargeSupplementFragment extends Fragment {
SharedPreferences sharedPreferences;
private Button btnSubmit;
private EditText editTextAmount;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Spinner spinnerAbonnement;
HashMap<Integer,String> abonnementHashMap ;
public RechargeSupplementFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment RechargeSupplementFragment.
*/
// TODO: Rename and change types and number of parameters
public static RechargeSupplementFragment newInstance(String param1, String param2) {
RechargeSupplementFragment fragment = new RechargeSupplementFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(layout.fragment_recharge_supplement, container, false) ;
sharedPreferences = requireContext().getSharedPreferences("user_session", MODE_PRIVATE);
String displayName = sharedPreferences.getString("display_name", "");
String userIdString = sharedPreferences.getString("user_id", "");
int userId = Integer.parseInt(userIdString);
abonnementHashMap = new SupplementRepository(requireContext()).getAbonnementsMapByUserId(userId);
spinnerAbonnement = view.findViewById(id.spinnerAbonnement);
editTextAmount = view.findViewById(R.id.editTextAmount);
btnSubmit = view.findViewById(R.id.btnSubmit);
populateAbonnementSpinner();
btnSubmit.setOnClickListener(view1 -> {
// Call a method to handle the insertion of data
insertRechargeSupplementData();
});
return view;
}
private void populateAbonnementSpinner(){
// Ici je vais faire appel à une methode pour afficher la liste des abonnements de l'utilisateur avec id= id_session
List<String> nameAbonnementList = new ArrayList<>(abonnementHashMap.values());
Log.d("AbonnementListSize", String.valueOf(nameAbonnementList.size()));
ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, nameAbonnementList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAbonnement.setAdapter(adapter);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void insertRechargeSupplementData() {
// Retrieve data from UI elements
String prix = editTextAmount.getText().toString();
String selectedAbonnement = spinnerAbonnement.getSelectedItem().toString();
LocalDateTime currentDateTime = LocalDateTime.now();
// Define a formatter with the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// Format LocalDateTime to a string
String date = currentDateTime.format(formatter);
int idAbonnement = getKeyByValue(abonnementHashMap, selectedAbonnement);
// Create an Recharge object with the retrieved data | package com.gi3.mesdepensestelecom.ui.recharge;
/**
* A simple {@link Fragment} subclass.
* Use the {@link RechargeSupplementFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class RechargeSupplementFragment extends Fragment {
SharedPreferences sharedPreferences;
private Button btnSubmit;
private EditText editTextAmount;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private Spinner spinnerAbonnement;
HashMap<Integer,String> abonnementHashMap ;
public RechargeSupplementFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment RechargeSupplementFragment.
*/
// TODO: Rename and change types and number of parameters
public static RechargeSupplementFragment newInstance(String param1, String param2) {
RechargeSupplementFragment fragment = new RechargeSupplementFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(layout.fragment_recharge_supplement, container, false) ;
sharedPreferences = requireContext().getSharedPreferences("user_session", MODE_PRIVATE);
String displayName = sharedPreferences.getString("display_name", "");
String userIdString = sharedPreferences.getString("user_id", "");
int userId = Integer.parseInt(userIdString);
abonnementHashMap = new SupplementRepository(requireContext()).getAbonnementsMapByUserId(userId);
spinnerAbonnement = view.findViewById(id.spinnerAbonnement);
editTextAmount = view.findViewById(R.id.editTextAmount);
btnSubmit = view.findViewById(R.id.btnSubmit);
populateAbonnementSpinner();
btnSubmit.setOnClickListener(view1 -> {
// Call a method to handle the insertion of data
insertRechargeSupplementData();
});
return view;
}
private void populateAbonnementSpinner(){
// Ici je vais faire appel à une methode pour afficher la liste des abonnements de l'utilisateur avec id= id_session
List<String> nameAbonnementList = new ArrayList<>(abonnementHashMap.values());
Log.d("AbonnementListSize", String.valueOf(nameAbonnementList.size()));
ArrayAdapter<String> adapter = new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_item, nameAbonnementList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerAbonnement.setAdapter(adapter);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void insertRechargeSupplementData() {
// Retrieve data from UI elements
String prix = editTextAmount.getText().toString();
String selectedAbonnement = spinnerAbonnement.getSelectedItem().toString();
LocalDateTime currentDateTime = LocalDateTime.now();
// Define a formatter with the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// Format LocalDateTime to a string
String date = currentDateTime.format(formatter);
int idAbonnement = getKeyByValue(abonnementHashMap, selectedAbonnement);
// Create an Recharge object with the retrieved data | Supplement supplement = new Supplement(idAbonnement, Float.parseFloat(prix), date); | 3 | 2023-12-20 13:43:21+00:00 | 4k |
litongjava/next-jfinal | src/main/java/com/jfinal/core/paragetter/JsonRequest.java | [
{
"identifier": "AsyncContext",
"path": "src/main/java/com/jfinal/servlet/AsyncContext.java",
"snippet": "public class AsyncContext {\n\n}"
},
{
"identifier": "DispatcherType",
"path": "src/main/java/com/jfinal/servlet/DispatcherType.java",
"snippet": "public class DispatcherType {\n\n}"... | import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import com.jfinal.servlet.AsyncContext;
import com.jfinal.servlet.DispatcherType;
import com.jfinal.servlet.RequestDispatcher;
import com.jfinal.servlet.ServletContext;
import com.jfinal.servlet.ServletException;
import com.jfinal.servlet.ServletInputStream;
import com.jfinal.servlet.ServletRequest;
import com.jfinal.servlet.ServletResponse;
import com.jfinal.servlet.http.Cookie;
import com.jfinal.servlet.http.HttpServletRequest;
import com.jfinal.servlet.http.HttpServletResponse;
import com.jfinal.servlet.http.HttpSession;
import com.jfinal.servlet.http.HttpUpgradeHandler;
import com.jfinal.servlet.multipart.Part; | 3,370 | throws IllegalStateException {
return req.startAsync(servletRequest, servletResponse);
}
@Override
public boolean isAsyncStarted() {
return req.isAsyncStarted();
}
@Override
public boolean isAsyncSupported() {
return req.isAsyncSupported();
}
@Override
public AsyncContext getAsyncContext() {
return req.getAsyncContext();
}
@Override
public DispatcherType getDispatcherType() {
return req.getDispatcherType();
}
@Override
public String getAuthType() {
return req.getAuthType();
}
@Override
public Cookie[] getCookies() {
return req.getCookies();
}
@Override
public long getDateHeader(String name) {
return req.getDateHeader(name);
}
@Override
public String getHeader(String name) {
return req.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
return req.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
return req.getHeaderNames();
}
@Override
public int getIntHeader(String name) {
return req.getIntHeader(name);
}
@Override
public String getMethod() {
return req.getMethod();
}
@Override
public String getPathInfo() {
return req.getPathInfo();
}
@Override
public String getPathTranslated() {
return req.getPathTranslated();
}
@Override
public String getContextPath() {
return req.getContextPath();
}
@Override
public String getQueryString() {
return req.getQueryString();
}
@Override
public String getRemoteUser() {
return req.getRemoteUser();
}
@Override
public boolean isUserInRole(String role) {
return req.isUserInRole(role);
}
@Override
public Principal getUserPrincipal() {
return req.getUserPrincipal();
}
@Override
public String getRequestedSessionId() {
return req.getRequestedSessionId();
}
@Override
public String getRequestURI() {
return req.getRequestURI();
}
@Override
public StringBuffer getRequestURL() {
return req.getRequestURL();
}
@Override
public String getServletPath() {
return req.getServletPath();
}
@Override | /**
* Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com) / 玛雅牛 (myaniu AT gmail dot com).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package com.jfinal.core.paragetter;
/**
* JsonRequest 包装 json 请求,从底层接管所有 parameter 操作
*/
public class JsonRequest implements HttpServletRequest {
// 缓存 JSONObject、JSONArray 对象
private com.alibaba.fastjson.JSONObject jsonObject;
private com.alibaba.fastjson.JSONArray jsonArray;
// 包装请求对象
private HttpServletRequest req;
// 通过 JSONObject 延迟生成 paraMap
private HashMap<String, String[]> paraMap;
public JsonRequest(String jsonString, HttpServletRequest req) {
Object json = com.alibaba.fastjson.JSON.parse(jsonString);
if (json instanceof com.alibaba.fastjson.JSONObject) {
jsonObject = (com.alibaba.fastjson.JSONObject) json;
} else if (json instanceof com.alibaba.fastjson.JSONArray) {
jsonArray = (com.alibaba.fastjson.JSONArray) json;
}
this.req = req;
}
/**
* 第一个版本只做简单转换,用户获取 JSONObject 与 JSONArray 后可以进一步进行复杂转换
*/
public com.alibaba.fastjson.JSONObject getJSONObject() {
return jsonObject;
}
public com.alibaba.fastjson.JSONArray getJSONArray() {
return jsonArray;
}
/*
* public Map<String, Object> getJsonMap() { return jsonObject; } public java.util.List<Object> getJsonList() { return jsonArray; }
*/
/**
* 获取内部 HttpServletRequest 对象
*/
public HttpServletRequest getInnerRequest() {
return req;
}
/**
* 请求参数是否为 JSONObject 对象
*/
public boolean isJSONObject() {
return jsonObject != null;
}
/**
* 请求参数是否为 JSONArray 对象
*/
public boolean isJSONArray() {
return jsonArray != null;
}
// 延迟创建,不是每次都会调用 parameter 相关方法
private HashMap<String, String[]> getParaMap() {
if (paraMap == null) {
paraMap = (jsonObject != null ? createParaMap(jsonObject) : new HashMap<>());
}
return paraMap;
}
private HashMap<String, String[]> createParaMap(com.alibaba.fastjson.JSONObject jsonPara) {
HashMap<String, String[]> newPara = new HashMap<>();
// 先读取 parameter,否则后续从流中读取 rawData 后将无法读取 parameter(部分 servlet 容器)
Map<String, String[]> oldPara = req.getParameterMap();
if (oldPara != null && oldPara.size() > 0) {
newPara.putAll(oldPara);
}
for (Map.Entry<String, Object> e : jsonPara.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
// 只转换最外面一层 json 数据,如果存在多层 json 结构,仅将其视为 String 留给后续流程转换
if (value instanceof com.alibaba.fastjson.JSON) {
newPara.put(key, new String[] { ((com.alibaba.fastjson.JSON) value).toJSONString() });
} else if (value != null) {
newPara.put(key, new String[] { value.toString() });
} else {
// 需要考虑 value 是否转成 String[] array = {""},ActionRepoter.getParameterValues() 有依赖
newPara.put(key, null);
}
}
return newPara;
}
@Override
public String getParameter(String name) {
// String[] ret = getParaMap().get(name);
// return ret != null && ret.length != 0 ? ret[0] : null;
// 优化性能,避免调用 getParaMap() 触发调用 createParaMap(),从而大概率避免对整个 jsonObject 进行转换
if (jsonObject != null && jsonObject.containsKey(name)) {
Object value = jsonObject.get(name);
if (value instanceof com.alibaba.fastjson.JSON) {
return ((com.alibaba.fastjson.JSON) value).toJSONString();
} else if (value != null) {
return value.toString();
} else {
// 需要考虑是否返回 "",表单提交请求只要 name 存在则值不会为 null
return null;
}
} else {
return req.getParameter(name);
}
}
/**
* 该方法将触发 createParaMap(),框架内部应尽可能避免该事情发生,以优化性能
*/
@Override
public Map<String, String[]> getParameterMap() {
return getParaMap();
}
/**
* 该方法将触发 createParaMap(),框架内部应尽可能避免该事情发生,以优化性能
*/
@Override
public String[] getParameterValues(String name) {
return getParaMap().get(name);
}
@Override
public Enumeration<String> getParameterNames() {
// return Collections.enumeration(getParaMap().keySet());
if (jsonObject != null) {
return Collections.enumeration(jsonObject.keySet());
} else {
return Collections.emptyEnumeration();
}
}
// ---------------------------------------------------------------
// 以下方法仅为对 req 对象的转调 -------------------------------------
@Override
public ServletInputStream getInputStream() throws IOException {
return req.getInputStream();
}
@Override
public BufferedReader getReader() throws IOException {
return req.getReader();
}
@Override
public Object getAttribute(String name) {
return req.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return req.getAttributeNames();
}
@Override
public String getCharacterEncoding() {
return req.getCharacterEncoding();
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
req.setCharacterEncoding(env);
}
@Override
public int getContentLength() {
return req.getContentLength();
}
@Override
public long getContentLengthLong() {
return req.getContentLengthLong();
}
@Override
public String getContentType() {
return req.getContentType();
}
@Override
public String getProtocol() {
return req.getProtocol();
}
@Override
public String getScheme() {
return req.getScheme();
}
@Override
public String getServerName() {
return req.getServerName();
}
@Override
public int getServerPort() {
return req.getServerPort();
}
@Override
public String getRemoteAddr() {
return req.getRemoteAddr();
}
@Override
public String getRemoteHost() {
return req.getRemoteHost();
}
@Override
public void setAttribute(String name, Object o) {
req.setAttribute(name, o);
}
@Override
public void removeAttribute(String name) {
req.removeAttribute(name);
}
@Override
public Locale getLocale() {
return req.getLocale();
}
@Override
public Enumeration<Locale> getLocales() {
return req.getLocales();
}
@Override
public boolean isSecure() {
return req.isSecure();
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return req.getRequestDispatcher(path);
}
@Override
public String getRealPath(String path) {
return req.getRealPath(path);
}
@Override
public int getRemotePort() {
return req.getRemotePort();
}
@Override
public String getLocalName() {
return req.getLocalName();
}
@Override
public String getLocalAddr() {
return req.getLocalAddr();
}
@Override
public int getLocalPort() {
return req.getLocalPort();
}
@Override
public ServletContext getServletContext() {
return req.getServletContext();
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return req.startAsync();
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
return req.startAsync(servletRequest, servletResponse);
}
@Override
public boolean isAsyncStarted() {
return req.isAsyncStarted();
}
@Override
public boolean isAsyncSupported() {
return req.isAsyncSupported();
}
@Override
public AsyncContext getAsyncContext() {
return req.getAsyncContext();
}
@Override
public DispatcherType getDispatcherType() {
return req.getDispatcherType();
}
@Override
public String getAuthType() {
return req.getAuthType();
}
@Override
public Cookie[] getCookies() {
return req.getCookies();
}
@Override
public long getDateHeader(String name) {
return req.getDateHeader(name);
}
@Override
public String getHeader(String name) {
return req.getHeader(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
return req.getHeaders(name);
}
@Override
public Enumeration<String> getHeaderNames() {
return req.getHeaderNames();
}
@Override
public int getIntHeader(String name) {
return req.getIntHeader(name);
}
@Override
public String getMethod() {
return req.getMethod();
}
@Override
public String getPathInfo() {
return req.getPathInfo();
}
@Override
public String getPathTranslated() {
return req.getPathTranslated();
}
@Override
public String getContextPath() {
return req.getContextPath();
}
@Override
public String getQueryString() {
return req.getQueryString();
}
@Override
public String getRemoteUser() {
return req.getRemoteUser();
}
@Override
public boolean isUserInRole(String role) {
return req.isUserInRole(role);
}
@Override
public Principal getUserPrincipal() {
return req.getUserPrincipal();
}
@Override
public String getRequestedSessionId() {
return req.getRequestedSessionId();
}
@Override
public String getRequestURI() {
return req.getRequestURI();
}
@Override
public StringBuffer getRequestURL() {
return req.getRequestURL();
}
@Override
public String getServletPath() {
return req.getServletPath();
}
@Override | public HttpSession getSession(boolean create) { | 11 | 2023-12-19 10:58:33+00:00 | 4k |
ViniciusJPSilva/TSI-PizzeriaExpress | PizzeriaExpress/src/main/java/br/vjps/tsi/pe/managedbeans/ChefMB.java | [
{
"identifier": "DAO",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/DAO.java",
"snippet": "public class DAO<T> {\n\tprivate Class<T> tClass;\n\n\t/**\n * Construtor que recebe a classe da entidade para ser manipulada pelo DAO.\n *\n * @param tClass A classe da entidade.\n */... | import java.io.IOException;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import br.vjps.tsi.pe.dao.DAO;
import br.vjps.tsi.pe.dao.RequestDAO;
import br.vjps.tsi.pe.model.Item;
import br.vjps.tsi.pe.model.Request; | 2,673 | package br.vjps.tsi.pe.managedbeans;
@SessionScoped
@ManagedBean
public class ChefMB {
private Request chefRequest;
private List<Request> openRequests;
/**
* Define o pedido que está sendo servido pelo chef e redireciona para a página de serviço.
*
* @param request Pedido que está sendo servido.
* @return Redireciona para a página de serviço.
*/
public String serve(Request request) {
setChefRequest(request);
return"serve-request?faces-redirect=true";
}
/**
* Atualiza o estado do pedido.
* Imprime no console o estado de entrega de cada item do pedido do chef.
*/
public void updateRequest() { | package br.vjps.tsi.pe.managedbeans;
@SessionScoped
@ManagedBean
public class ChefMB {
private Request chefRequest;
private List<Request> openRequests;
/**
* Define o pedido que está sendo servido pelo chef e redireciona para a página de serviço.
*
* @param request Pedido que está sendo servido.
* @return Redireciona para a página de serviço.
*/
public String serve(Request request) {
setChefRequest(request);
return"serve-request?faces-redirect=true";
}
/**
* Atualiza o estado do pedido.
* Imprime no console o estado de entrega de cada item do pedido do chef.
*/
public void updateRequest() { | for(Item item : chefRequest.getItems()) | 2 | 2023-12-16 01:25:27+00:00 | 4k |
my-virtual-hub/omni-comm-domain | src/main/java/br/com/myvirtualhub/omni/domain/sms/model/SmsPayload.java | [
{
"identifier": "PhoneNumberException",
"path": "src/main/java/br/com/myvirtualhub/omni/domain/core/exceptions/PhoneNumberException.java",
"snippet": "public class PhoneNumberException extends OmniException{\n /**\n * Constructs a new PhoneNumberException with the specified message.\n *\n ... | import br.com.myvirtualhub.omni.domain.core.exceptions.PhoneNumberException;
import br.com.myvirtualhub.omni.domain.core.model.interfaces.Copyable;
import br.com.myvirtualhub.omni.domain.core.model.interfaces.Model;
import java.util.Objects; | 1,678 | /*
* Copyright (c) 2024.
*
* This software is provided under the BSD-2-Clause license. By using this software,
* * you agree to respect the terms and conditions of the BSD-2-Clause license.
*/
package br.com.myvirtualhub.omni.domain.sms.model;
/**
* Represents an SMS Payload message with details for sending and tracking.
*
* @author Marco Quiçula
* @version 1.0
* @since 2024-01-09
*/
public class SmsPayload implements Model, Copyable<SmsPayload> {
private SmsRecipient recipient;
private SmsMessage message;
private String clientMessageId;
private final SmsOmniProcessId smsOmniProcessId;
/**
* Constructs a new SmsPayload.
*
* @param recipient The phone number of the message recipient.
* @param message The text content of the message.
* @param clientMessageId A unique identifier provided by the client for tracking.
*/
public SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = new SmsOmniProcessId();
}
private SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId, SmsOmniProcessId smsOmniProcessId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = smsOmniProcessId;
}
/**
* Retrieves the recipient of the SMS payload.
*
* @return The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public SmsRecipient getRecipient() {
return recipient;
}
/**
* Sets the recipient of the SMS payload.
*
* @param recipient The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public void setRecipient(SmsRecipient recipient) {
this.recipient = recipient;
}
/**
* Retrieves the message of the SMS payload.
*
* @return The message of the SMS payload as an instance of the SmsMessage class.
* @see SmsPayload
* @see SmsMessage
*/
public SmsMessage getMessage() {
return message;
}
/**
* Sets the message of the SMS payload.
*
* @param message The message of the SMS payload as an instance of the SmsMessage class.
*/
public void setMessage(SmsMessage message) {
this.message = message;
}
/**
* Retrieves the client message ID associated with the SMS payload.
*
* @return The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public String getClientMessageId() {
return clientMessageId;
}
/**
* Sets the client message ID associated with the SMS payload.
* This method sets the client message ID provided by the client for tracking purposes.
* The client message ID is a unique identifier associated with the SMS payload.
*
* @param clientMessageId The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public void setClientMessageId(String clientMessageId) {
this.clientMessageId = clientMessageId;
}
/**
* Retrieves the OmniMessageId associated with the SMS payload.
*
* @return The OmniMessageId of the SMS payload as an instance of the SmsOmniProcessId class.
* @see SmsPayload
* @see SmsOmniProcessId
*/
public SmsOmniProcessId getOmniMessageId() {
return smsOmniProcessId;
}
/**
* Creates a copy of the SmsPayload object.
*
* @return A copy of the SmsPayload object.
* @throws PhoneNumberException if there is an issue with the phone number
* @see SmsPayload
* @see PhoneNumberException
*/
@Override | /*
* Copyright (c) 2024.
*
* This software is provided under the BSD-2-Clause license. By using this software,
* * you agree to respect the terms and conditions of the BSD-2-Clause license.
*/
package br.com.myvirtualhub.omni.domain.sms.model;
/**
* Represents an SMS Payload message with details for sending and tracking.
*
* @author Marco Quiçula
* @version 1.0
* @since 2024-01-09
*/
public class SmsPayload implements Model, Copyable<SmsPayload> {
private SmsRecipient recipient;
private SmsMessage message;
private String clientMessageId;
private final SmsOmniProcessId smsOmniProcessId;
/**
* Constructs a new SmsPayload.
*
* @param recipient The phone number of the message recipient.
* @param message The text content of the message.
* @param clientMessageId A unique identifier provided by the client for tracking.
*/
public SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = new SmsOmniProcessId();
}
private SmsPayload(SmsRecipient recipient, SmsMessage message, String clientMessageId, SmsOmniProcessId smsOmniProcessId) {
this.recipient = recipient;
this.message = message;
this.clientMessageId = clientMessageId;
this.smsOmniProcessId = smsOmniProcessId;
}
/**
* Retrieves the recipient of the SMS payload.
*
* @return The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public SmsRecipient getRecipient() {
return recipient;
}
/**
* Sets the recipient of the SMS payload.
*
* @param recipient The recipient of the SMS payload as an instance of the SmsRecipient class.
* @see SmsPayload
* @see SmsRecipient
*/
public void setRecipient(SmsRecipient recipient) {
this.recipient = recipient;
}
/**
* Retrieves the message of the SMS payload.
*
* @return The message of the SMS payload as an instance of the SmsMessage class.
* @see SmsPayload
* @see SmsMessage
*/
public SmsMessage getMessage() {
return message;
}
/**
* Sets the message of the SMS payload.
*
* @param message The message of the SMS payload as an instance of the SmsMessage class.
*/
public void setMessage(SmsMessage message) {
this.message = message;
}
/**
* Retrieves the client message ID associated with the SMS payload.
*
* @return The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public String getClientMessageId() {
return clientMessageId;
}
/**
* Sets the client message ID associated with the SMS payload.
* This method sets the client message ID provided by the client for tracking purposes.
* The client message ID is a unique identifier associated with the SMS payload.
*
* @param clientMessageId The client message ID as a String.
* @see SmsPayload
* @since 2023-08-01
*/
public void setClientMessageId(String clientMessageId) {
this.clientMessageId = clientMessageId;
}
/**
* Retrieves the OmniMessageId associated with the SMS payload.
*
* @return The OmniMessageId of the SMS payload as an instance of the SmsOmniProcessId class.
* @see SmsPayload
* @see SmsOmniProcessId
*/
public SmsOmniProcessId getOmniMessageId() {
return smsOmniProcessId;
}
/**
* Creates a copy of the SmsPayload object.
*
* @return A copy of the SmsPayload object.
* @throws PhoneNumberException if there is an issue with the phone number
* @see SmsPayload
* @see PhoneNumberException
*/
@Override | public SmsPayload copy() throws PhoneNumberException { | 0 | 2023-12-18 03:42:25+00:00 | 4k |
IzanagiCraft/izanagi-librarian | izanagi-librarian-shared/src/main/java/com/izanagicraft/librarian/players/IzanagiPlayer.java | [
{
"identifier": "DiscordConnection",
"path": "izanagi-librarian-shared/src/main/java/com/izanagicraft/librarian/connection/DiscordConnection.java",
"snippet": "public interface DiscordConnection {\n\n /**\n * Link the Discord user's account with their Minecraft account.\n *\n * @param dis... | import com.izanagicraft.librarian.connection.DiscordConnection;
import com.izanagicraft.librarian.connection.MinecraftConnection;
import com.izanagicraft.librarian.economy.EconomicAgent; | 2,774 | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.librarian.players;
/**
* izanagi-librarian; com.izanagicraft.librarian.players:IzanagiPlayer
* <p>
* Represents a player in the Izanagi systems.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 14.12.2023
*/
public interface IzanagiPlayer extends EconomicAgent {
/**
* Get the connection manager for the player's Minecraft account.
*
* @return The {@link MinecraftConnection} instance for the player.
*/
MinecraftConnection getMinecraftConnection();
/**
* Get the connection manager for the player's Discord account.
*
* @return The {@link DiscordConnection} instance for the player.
*/ | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.librarian.players;
/**
* izanagi-librarian; com.izanagicraft.librarian.players:IzanagiPlayer
* <p>
* Represents a player in the Izanagi systems.
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 14.12.2023
*/
public interface IzanagiPlayer extends EconomicAgent {
/**
* Get the connection manager for the player's Minecraft account.
*
* @return The {@link MinecraftConnection} instance for the player.
*/
MinecraftConnection getMinecraftConnection();
/**
* Get the connection manager for the player's Discord account.
*
* @return The {@link DiscordConnection} instance for the player.
*/ | DiscordConnection getDiscordConnection(); | 0 | 2023-12-14 00:52:33+00:00 | 4k |
ThomasGorisseGit/TodoList | backend/src/main/java/fr/gorisse/todoApp/TodoListApp/controller/UserController.java | [
{
"identifier": "EmailAlreadyExistException",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/exception/EmailAlreadyExistException.java",
"snippet": "@ResponseStatus(value = HttpStatus.CONFLICT)\npublic class EmailAlreadyExistException extends RuntimeException{\n public EmailAlreadyExis... | import fr.gorisse.todoApp.TodoListApp.exception.EmailAlreadyExistException;
import fr.gorisse.todoApp.TodoListApp.exception.UsernameAlreadyExistException;
import fr.gorisse.todoApp.TodoListApp.entity.TodoList;
import fr.gorisse.todoApp.TodoListApp.entity.User;
import fr.gorisse.todoApp.TodoListApp.services.TodoListService;
import fr.gorisse.todoApp.TodoListApp.services.UserService;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,981 | package fr.gorisse.todoApp.TodoListApp.controller;
@RestController // Is a Bean -> Injection de dépendance
@RequestMapping("/api/user")
public class UserController {
private final UserService userService;
private final TodoListService todoListService;
public UserController(UserService userService, TodoListService todoListService) {
this.userService = userService;
this.todoListService = todoListService;
}
// ? Get / find
// ? Récupère un utilisateur par id
@GetMapping("/find/idUser") | package fr.gorisse.todoApp.TodoListApp.controller;
@RestController // Is a Bean -> Injection de dépendance
@RequestMapping("/api/user")
public class UserController {
private final UserService userService;
private final TodoListService todoListService;
public UserController(UserService userService, TodoListService todoListService) {
this.userService = userService;
this.todoListService = todoListService;
}
// ? Get / find
// ? Récupère un utilisateur par id
@GetMapping("/find/idUser") | public User findUserById( | 3 | 2023-12-15 17:32:43+00:00 | 4k |
Konloch/HeadlessIRC | src/main/java/com/konloch/ircbot/listener/event/PrivateMessageEvent.java | [
{
"identifier": "Server",
"path": "src/main/java/com/konloch/ircbot/server/Server.java",
"snippet": "public class Server implements Runnable\n{\n\tprivate static final CharsetEncoder ENCODER = StandardCharsets.UTF_8.newEncoder();\n\tprivate static final CharsetDecoder DECODER = StandardCharsets.UTF_8.ne... | import com.konloch.ircbot.server.Server;
import com.konloch.ircbot.server.User; | 3,076 | package com.konloch.ircbot.listener.event;
/**
* @author Konloch
* @since 12/15/2023
*/
public class PrivateMessageEvent extends GenericServerEvent
{ | package com.konloch.ircbot.listener.event;
/**
* @author Konloch
* @since 12/15/2023
*/
public class PrivateMessageEvent extends GenericServerEvent
{ | private final User user; | 1 | 2023-12-16 02:09:21+00:00 | 4k |
sasmithx/layered-architecture-Sasmithx | src/main/java/lk/sasax/layeredarchitecture/controller/MainFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/lk/sasax/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n\n private static BOFactory boFactory;\n\n private BOFactory() {\n }\n\n public static BOFactory getBoFactory() {\n return (boFactory == null) ? b... | import lk.sasax.layeredarchitecture.bo.BOFactory;
import lk.sasax.layeredarchitecture.bo.custom.QueryBO;
import lk.sasax.layeredarchitecture.dto.CustomerOrderDTO;
import lk.sasax.layeredarchitecture.dao.custom.impl.QueryDAOImpl;
import javafx.animation.FadeTransition;
import javafx.animation.ScaleTransition;
import javafx.animation.TranslateTransition;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ResourceBundle; | 1,803 | package lk.sasax.layeredarchitecture.controller;
public class MainFormController {
@FXML
private AnchorPane root;
@FXML
private ImageView imgCustomer;
@FXML
private ImageView imgItem;
@FXML
private ImageView imgOrder;
@FXML
private ImageView imgViewOrders;
@FXML
private Label lblMenu;
@FXML
private Label lblDescription;
QueryBO queryBO = (QueryBO) BOFactory.getBoFactory().getTypes(BOFactory.BOTypes.QUERY);
/**
* Initializes the controller class.
*/
public void initialize(URL url, ResourceBundle rb) {
FadeTransition fadeIn = new FadeTransition(Duration.millis(2000), root);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
fadeIn.play();
}
@FXML
private void playMouseExitAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1);
scaleT.setToY(1);
scaleT.play();
icon.setEffect(null);
lblMenu.setText("Welcome");
lblDescription.setText("Please select one of above main operations to proceed");
}
}
@FXML
private void playMouseEnterAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
switch (icon.getId()) {
case "imgCustomer":
lblMenu.setText("Manage Customers");
lblDescription.setText("Click to add, edit, delete, search or view customers");
break;
case "imgItem":
lblMenu.setText("Manage Items");
lblDescription.setText("Click to add, edit, delete, search or view items");
break;
case "imgOrder":
lblMenu.setText("Place Orders");
lblDescription.setText("Click here if you want to place a new order");
break;
case "imgViewOrders":
lblMenu.setText("Search Orders");
lblDescription.setText("Click if you want to search orders");
break;
}
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1.2);
scaleT.setToY(1.2);
scaleT.play();
DropShadow glow = new DropShadow();
glow.setColor(Color.CORNFLOWERBLUE);
glow.setWidth(20);
glow.setHeight(20);
glow.setRadius(20);
icon.setEffect(glow);
}
}
@FXML
private void navigate(MouseEvent event) throws IOException, SQLException, ClassNotFoundException {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
Parent root = null;
switch (icon.getId()) {
case "imgCustomer":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-customers-form.fxml"));
break;
case "imgItem":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-items-form.fxml"));
break;
case "imgOrder":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/place-order-form.fxml"));
break;
case "imgViewOrders":
QueryDAOImpl queryDAO = new QueryDAOImpl(); | package lk.sasax.layeredarchitecture.controller;
public class MainFormController {
@FXML
private AnchorPane root;
@FXML
private ImageView imgCustomer;
@FXML
private ImageView imgItem;
@FXML
private ImageView imgOrder;
@FXML
private ImageView imgViewOrders;
@FXML
private Label lblMenu;
@FXML
private Label lblDescription;
QueryBO queryBO = (QueryBO) BOFactory.getBoFactory().getTypes(BOFactory.BOTypes.QUERY);
/**
* Initializes the controller class.
*/
public void initialize(URL url, ResourceBundle rb) {
FadeTransition fadeIn = new FadeTransition(Duration.millis(2000), root);
fadeIn.setFromValue(0.0);
fadeIn.setToValue(1.0);
fadeIn.play();
}
@FXML
private void playMouseExitAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1);
scaleT.setToY(1);
scaleT.play();
icon.setEffect(null);
lblMenu.setText("Welcome");
lblDescription.setText("Please select one of above main operations to proceed");
}
}
@FXML
private void playMouseEnterAnimation(MouseEvent event) {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
switch (icon.getId()) {
case "imgCustomer":
lblMenu.setText("Manage Customers");
lblDescription.setText("Click to add, edit, delete, search or view customers");
break;
case "imgItem":
lblMenu.setText("Manage Items");
lblDescription.setText("Click to add, edit, delete, search or view items");
break;
case "imgOrder":
lblMenu.setText("Place Orders");
lblDescription.setText("Click here if you want to place a new order");
break;
case "imgViewOrders":
lblMenu.setText("Search Orders");
lblDescription.setText("Click if you want to search orders");
break;
}
ScaleTransition scaleT = new ScaleTransition(Duration.millis(200), icon);
scaleT.setToX(1.2);
scaleT.setToY(1.2);
scaleT.play();
DropShadow glow = new DropShadow();
glow.setColor(Color.CORNFLOWERBLUE);
glow.setWidth(20);
glow.setHeight(20);
glow.setRadius(20);
icon.setEffect(glow);
}
}
@FXML
private void navigate(MouseEvent event) throws IOException, SQLException, ClassNotFoundException {
if (event.getSource() instanceof ImageView) {
ImageView icon = (ImageView) event.getSource();
Parent root = null;
switch (icon.getId()) {
case "imgCustomer":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-customers-form.fxml"));
break;
case "imgItem":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/manage-items-form.fxml"));
break;
case "imgOrder":
root = FXMLLoader.load(this.getClass().getResource("/lk/sasax/layeredarchitecture/place-order-form.fxml"));
break;
case "imgViewOrders":
QueryDAOImpl queryDAO = new QueryDAOImpl(); | List<CustomerOrderDTO> customerOrderDTOS1 = queryDAO.customerOrderDetails(); | 2 | 2023-12-16 04:19:42+00:00 | 4k |
madhushiillesinghe/layered-architecture-madhushi | src/main/java/com/example/layeredarchitecture/dao/BOFactory.java | [
{
"identifier": "SuperBo",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/SuperBo.java",
"snippet": "public interface SuperBo {\n}"
},
{
"identifier": "CustomerBoImpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/custom/impl/CustomerBoImpl.java",
"snippet"... | import com.example.layeredarchitecture.bo.custom.SuperBo;
import com.example.layeredarchitecture.bo.custom.impl.CustomerBoImpl;
import com.example.layeredarchitecture.bo.custom.impl.ItemBoImpl;
import com.example.layeredarchitecture.bo.custom.impl.PlaceOrderBoImpl;
import com.example.layeredarchitecture.dao.custom.CustomerDao; | 2,254 | package com.example.layeredarchitecture.dao;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory==null)?boFactory=new BOFactory():boFactory;
}
public static SuperBo getBo(BOType boType){
switch (boType){ | package com.example.layeredarchitecture.dao;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory==null)?boFactory=new BOFactory():boFactory;
}
public static SuperBo getBo(BOType boType){
switch (boType){ | case CUSTOM:return new CustomerBoImpl(); | 1 | 2023-12-17 02:17:36+00:00 | 4k |
HypixelSkyblockmod/ChromaHud | src/java/xyz/apfelmus/cheeto/client/modules/render/TPSViewer.java | [
{
"identifier": "Category",
"path": "src/java/xyz/apfelmus/cf4m/module/Category.java",
"snippet": "public enum Category {\n COMBAT,\n RENDER,\n MOVEMENT,\n PLAYER,\n WORLD,\n MISC,\n NONE;\n\n}"
},
{
"identifier": "PacketReceivedEvent",
"path": "src/java/xyz/apfelmus/che... | import java.util.ArrayList;
import java.util.List;
import net.minecraft.network.play.server.S03PacketTimeUpdate;
import xyz.apfelmus.cf4m.annotation.Event;
import xyz.apfelmus.cf4m.annotation.Setting;
import xyz.apfelmus.cf4m.annotation.module.Enable;
import xyz.apfelmus.cf4m.annotation.module.Module;
import xyz.apfelmus.cf4m.module.Category;
import xyz.apfelmus.cheeto.client.events.PacketReceivedEvent;
import xyz.apfelmus.cheeto.client.events.Render2DEvent;
import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent;
import xyz.apfelmus.cheeto.client.settings.BooleanSetting;
import xyz.apfelmus.cheeto.client.settings.IntegerSetting;
import xyz.apfelmus.cheeto.client.utils.client.FontUtils; | 1,618 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.network.play.server.S03PacketTimeUpdate
*/
package xyz.apfelmus.cheeto.client.modules.render;
@Module(name="TPSViewer", category=Category.RENDER)
public class TPSViewer {
@Setting(name="xPos")
private IntegerSetting xPos = new IntegerSetting(0, 0, 1000);
@Setting(name="yPos")
private IntegerSetting yPos = new IntegerSetting(0, 0, 1000);
@Setting(name="RGB")
private BooleanSetting rgb = new BooleanSetting(true);
public static List<Float> serverTPS = new ArrayList<Float>();
private static long systemTime = 0L;
private static long serverTime = 0L;
@Enable
public void onEnable() {
serverTPS.clear();
systemTime = 0L;
serverTime = 0L;
}
@Event
public void onRender(Render2DEvent event) {
if (this.rgb.isEnabled()) {
FontUtils.drawHVCenteredChromaString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), 0);
} else {
FontUtils.drawHVCenteredString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), -1);
}
}
@Event | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.network.play.server.S03PacketTimeUpdate
*/
package xyz.apfelmus.cheeto.client.modules.render;
@Module(name="TPSViewer", category=Category.RENDER)
public class TPSViewer {
@Setting(name="xPos")
private IntegerSetting xPos = new IntegerSetting(0, 0, 1000);
@Setting(name="yPos")
private IntegerSetting yPos = new IntegerSetting(0, 0, 1000);
@Setting(name="RGB")
private BooleanSetting rgb = new BooleanSetting(true);
public static List<Float> serverTPS = new ArrayList<Float>();
private static long systemTime = 0L;
private static long serverTime = 0L;
@Enable
public void onEnable() {
serverTPS.clear();
systemTime = 0L;
serverTime = 0L;
}
@Event
public void onRender(Render2DEvent event) {
if (this.rgb.isEnabled()) {
FontUtils.drawHVCenteredChromaString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), 0);
} else {
FontUtils.drawHVCenteredString(String.format("TPS: %.1f", this.calcTps()), this.xPos.getCurrent(), this.yPos.getCurrent(), -1);
}
}
@Event | public void onPacket(PacketReceivedEvent event) { | 1 | 2023-12-21 16:22:25+00:00 | 4k |
vitri-ent/finorza | src/main/java/io/pyke/vitri/finorza/inference/gui/ModOptionsScreen.java | [
{
"identifier": "Config",
"path": "src/main/java/io/pyke/vitri/finorza/inference/config/Config.java",
"snippet": "public class Config {\r\n\tpublic static final BooleanConfigOption SYNCHRONIZE_INTEGRATED_SERVER = new BooleanConfigOption(\r\n\t\t\"synchronizeIntegratedServer\", false, (ignored, value) ->... | import java.util.List;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.OptionsList;
import net.minecraft.client.gui.screens.OptionsSubScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.util.FormattedCharSequence;
import io.pyke.vitri.finorza.inference.config.Config;
import io.pyke.vitri.finorza.inference.config.ConfigManager;
| 1,782 | package io.pyke.vitri.finorza.inference.gui;
public class ModOptionsScreen extends OptionsSubScreen {
private final Screen previous;
private OptionsList list;
public ModOptionsScreen(Screen previous) {
super(previous, Minecraft.getInstance().options, new TextComponent("Finorza Options"));
this.previous = previous;
}
protected void init() {
this.minecraft.keyboardHandler.setSendRepeatsToGui(true);
this.list = new OptionsList(this.minecraft, this.width, this.height, 32, this.height - 32, 25);
| package io.pyke.vitri.finorza.inference.gui;
public class ModOptionsScreen extends OptionsSubScreen {
private final Screen previous;
private OptionsList list;
public ModOptionsScreen(Screen previous) {
super(previous, Minecraft.getInstance().options, new TextComponent("Finorza Options"));
this.previous = previous;
}
protected void init() {
this.minecraft.keyboardHandler.setSendRepeatsToGui(true);
this.list = new OptionsList(this.minecraft, this.width, this.height, 32, this.height - 32, 25);
| this.list.addSmall(Config.asOptions());
| 0 | 2023-12-20 05:19:21+00:00 | 4k |
ciallo-dev/JWSystemLib | src/test/java/TestMyCourse.java | [
{
"identifier": "JWSystem",
"path": "src/main/java/moe/snowflake/jwSystem/JWSystem.java",
"snippet": "public class JWSystem {\n public Connection.Response jwLoggedResponse;\n public Connection.Response courseSelectSystemResponse;\n public Map<String, String> headers = new HashMap<>();\n priv... | import moe.snowflake.jwSystem.JWSystem;
import moe.snowflake.jwSystem.course.Course;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner; | 2,570 |
public class TestMyCourse {
@Test
public void test() throws IOException {
JWSystem system = new JWSystem().login("username", "password");
if (system.isCourseLogged()) {
System.out.println("当前课程查询结果: "); |
public class TestMyCourse {
@Test
public void test() throws IOException {
JWSystem system = new JWSystem().login("username", "password");
if (system.isCourseLogged()) {
System.out.println("当前课程查询结果: "); | ArrayList<Course> courses = system.getCourseSelectManager().getCurrentCourses(); | 1 | 2023-12-21 10:58:12+00:00 | 4k |
IzanagiCraft/Velocity-Maintenance | src/main/java/com/izanagicraft/velocity/maintenance/VelocityMaintenancePlugin.java | [
{
"identifier": "MaintenanceCommand",
"path": "src/main/java/com/izanagicraft/velocity/maintenance/commands/MaintenanceCommand.java",
"snippet": "public class MaintenanceCommand implements RawCommand {\n private final VelocityMaintenancePlugin plugin;\n\n public MaintenanceCommand(VelocityMaintena... | import com.google.inject.Inject;
import com.izanagicraft.velocity.maintenance.commands.MaintenanceCommand;
import com.izanagicraft.velocity.maintenance.data.JsonData;
import com.izanagicraft.velocity.maintenance.data.types.MaintenanceData;
import com.izanagicraft.velocity.maintenance.listener.LoginEventListener;
import com.izanagicraft.velocity.maintenance.listener.PingEventListener;
import com.moandjiezana.toml.Toml;
import com.velocitypowered.api.command.CommandManager;
import com.velocitypowered.api.event.EventManager;
import com.velocitypowered.api.event.Subscribe;
import com.velocitypowered.api.event.proxy.ProxyInitializeEvent;
import com.velocitypowered.api.event.proxy.ProxyShutdownEvent;
import com.velocitypowered.api.plugin.Plugin;
import com.velocitypowered.api.plugin.annotation.DataDirectory;
import com.velocitypowered.api.proxy.ProxyServer;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Logger; | 2,825 | /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.velocity.maintenance;
/**
* Velocity-Maintenance; com.izanagicraft.velocity.maintenance:VelocityMaintenancePlugin
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 16.12.2023
*/
@Plugin(
id = "velocity-maintenance",
name = "VelocityMaintenance",
version = "1.0-SNAPSHOT",
description = "A customizable maintenance plugin for Velocity.",
authors = {"sanguine6660"},
url = "https://github.com/IzanagiCraft/Velocity-Maintenance",
dependencies = {}
)
public class VelocityMaintenancePlugin {
private static VelocityMaintenancePlugin instance;
public static VelocityMaintenancePlugin getInstance() {
return instance;
}
private ProxyServer server;
private Logger logger;
private @DataDirectory Path dataDir;
private File dataFolder;
private Toml config;
| /*
* ▪ ·▄▄▄▄• ▄▄▄· ▐ ▄ ▄▄▄· ▄▄ • ▪ ▄▄· ▄▄▄ ▄▄▄· ·▄▄▄▄▄▄▄▄
* ██ ▪▀·.█▌▐█ ▀█ •█▌▐█▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▀▄ █·▐█ ▀█ ▐▄▄·•██
* ▐█·▄█▀▀▀•▄█▀▀█ ▐█▐▐▌▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐▀▀▄ ▄█▀▀█ ██▪ ▐█.▪
* ▐█▌█▌▪▄█▀▐█ ▪▐▌██▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌▐█•█▌▐█ ▪▐▌██▌. ▐█▌·
* ▀▀▀·▀▀▀ • ▀ ▀ ▀▀ █▪ ▀ ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ .▀ ▀ ▀ ▀ ▀▀▀ ▀▀▀
*
*
* @@@@@
* @@* *@@
* @@@ @@@
* @@@ @@ @@@ @@@@@@@@@@@
* @@@@@@@@ @@@@@@@@@@@@@@@@@@@@@
* @@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* #@@@ @@ @@ @@@@ @@@@
* @@@@ @@@ @@@@ @@@@ @@@
* @@@@@@ @@@@@@ @@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@@@@@@@@@
* @@@@@@@@@@@
*
* Copyright (c) 2023 - present | sanguine6660 <sanguine6660@gmail.com>
* Copyright (c) 2023 - present | izanagicraft.com <contact@izanagicraft.com>
* Copyright (c) 2023 - present | izanagicraft.com team and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.izanagicraft.velocity.maintenance;
/**
* Velocity-Maintenance; com.izanagicraft.velocity.maintenance:VelocityMaintenancePlugin
*
* @author <a href="https://github.com/sanguine6660">@sanguine6660</a>
* @since 16.12.2023
*/
@Plugin(
id = "velocity-maintenance",
name = "VelocityMaintenance",
version = "1.0-SNAPSHOT",
description = "A customizable maintenance plugin for Velocity.",
authors = {"sanguine6660"},
url = "https://github.com/IzanagiCraft/Velocity-Maintenance",
dependencies = {}
)
public class VelocityMaintenancePlugin {
private static VelocityMaintenancePlugin instance;
public static VelocityMaintenancePlugin getInstance() {
return instance;
}
private ProxyServer server;
private Logger logger;
private @DataDirectory Path dataDir;
private File dataFolder;
private Toml config;
| private JsonData<MaintenanceData> maintenanceData; | 2 | 2023-12-16 14:17:06+00:00 | 4k |
emtee40/ApkSignatureKill-pc | app/src/main/java/org/jf/dexlib2/util/SyntheticAccessorFSM.java | [
{
"identifier": "Opcodes",
"path": "app/src/main/java/org/jf/dexlib2/Opcodes.java",
"snippet": "public class Opcodes {\n\n /**\n * Either the api level for dalvik opcodes, or the art version for art opcodes\n */\n public final int api;\n public final int artVersion;\n @NonNull\n p... | import androidx.annotation.NonNull;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.iface.instruction.Instruction;
import org.jf.dexlib2.iface.instruction.OneRegisterInstruction;
import org.jf.dexlib2.iface.instruction.WideLiteralInstruction;
import java.util.List; | 2,023 | // line 1 "SyntheticAccessorFSM.rl"
/*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.util;
public class SyntheticAccessorFSM {
// line 43 "SyntheticAccessorFSM.rl"
// math type constants
public static final int ADD = SyntheticAccessorResolver.ADD_ASSIGNMENT;
public static final int SUB = SyntheticAccessorResolver.SUB_ASSIGNMENT;
public static final int MUL = SyntheticAccessorResolver.MUL_ASSIGNMENT;
public static final int DIV = SyntheticAccessorResolver.DIV_ASSIGNMENT;
public static final int REM = SyntheticAccessorResolver.REM_ASSIGNMENT;
public static final int AND = SyntheticAccessorResolver.AND_ASSIGNMENT;
public static final int OR = SyntheticAccessorResolver.OR_ASSIGNMENT;
public static final int XOR = SyntheticAccessorResolver.XOR_ASSIGNMENT;
public static final int SHL = SyntheticAccessorResolver.SHL_ASSIGNMENT;
public static final int SHR = SyntheticAccessorResolver.SHR_ASSIGNMENT;
public static final int USHR = SyntheticAccessorResolver.USHR_ASSIGNMENT;
public static final int INT = 0;
public static final int LONG = 1;
public static final int FLOAT = 2;
public static final int DOUBLE = 3;
public static final int POSITIVE_ONE = 1;
public static final int NEGATIVE_ONE = -1;
public static final int OTHER = 0;
static final int SyntheticAccessorFSM_start = 1;
static final int SyntheticAccessorFSM_first_final = 17;
static final int SyntheticAccessorFSM_error = 0;
static final int SyntheticAccessorFSM_en_main = 1;
// line 44 "SyntheticAccessorFSM.rl"
private static final byte _SyntheticAccessorFSM_actions[] = init__SyntheticAccessorFSM_actions_0();
private static final short _SyntheticAccessorFSM_key_offsets[] = init__SyntheticAccessorFSM_key_offsets_0();
private static final short _SyntheticAccessorFSM_trans_keys[] = init__SyntheticAccessorFSM_trans_keys_0();
private static final byte _SyntheticAccessorFSM_single_lengths[] = init__SyntheticAccessorFSM_single_lengths_0();
private static final byte _SyntheticAccessorFSM_range_lengths[] = init__SyntheticAccessorFSM_range_lengths_0();
private static final short _SyntheticAccessorFSM_index_offsets[] = init__SyntheticAccessorFSM_index_offsets_0();
private static final byte _SyntheticAccessorFSM_indicies[] = init__SyntheticAccessorFSM_indicies_0();
private static final byte _SyntheticAccessorFSM_trans_targs[] = init__SyntheticAccessorFSM_trans_targs_0();
private static final byte _SyntheticAccessorFSM_trans_actions[] = init__SyntheticAccessorFSM_trans_actions_0();
@NonNull | // line 1 "SyntheticAccessorFSM.rl"
/*
* Copyright 2012, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.jf.dexlib2.util;
public class SyntheticAccessorFSM {
// line 43 "SyntheticAccessorFSM.rl"
// math type constants
public static final int ADD = SyntheticAccessorResolver.ADD_ASSIGNMENT;
public static final int SUB = SyntheticAccessorResolver.SUB_ASSIGNMENT;
public static final int MUL = SyntheticAccessorResolver.MUL_ASSIGNMENT;
public static final int DIV = SyntheticAccessorResolver.DIV_ASSIGNMENT;
public static final int REM = SyntheticAccessorResolver.REM_ASSIGNMENT;
public static final int AND = SyntheticAccessorResolver.AND_ASSIGNMENT;
public static final int OR = SyntheticAccessorResolver.OR_ASSIGNMENT;
public static final int XOR = SyntheticAccessorResolver.XOR_ASSIGNMENT;
public static final int SHL = SyntheticAccessorResolver.SHL_ASSIGNMENT;
public static final int SHR = SyntheticAccessorResolver.SHR_ASSIGNMENT;
public static final int USHR = SyntheticAccessorResolver.USHR_ASSIGNMENT;
public static final int INT = 0;
public static final int LONG = 1;
public static final int FLOAT = 2;
public static final int DOUBLE = 3;
public static final int POSITIVE_ONE = 1;
public static final int NEGATIVE_ONE = -1;
public static final int OTHER = 0;
static final int SyntheticAccessorFSM_start = 1;
static final int SyntheticAccessorFSM_first_final = 17;
static final int SyntheticAccessorFSM_error = 0;
static final int SyntheticAccessorFSM_en_main = 1;
// line 44 "SyntheticAccessorFSM.rl"
private static final byte _SyntheticAccessorFSM_actions[] = init__SyntheticAccessorFSM_actions_0();
private static final short _SyntheticAccessorFSM_key_offsets[] = init__SyntheticAccessorFSM_key_offsets_0();
private static final short _SyntheticAccessorFSM_trans_keys[] = init__SyntheticAccessorFSM_trans_keys_0();
private static final byte _SyntheticAccessorFSM_single_lengths[] = init__SyntheticAccessorFSM_single_lengths_0();
private static final byte _SyntheticAccessorFSM_range_lengths[] = init__SyntheticAccessorFSM_range_lengths_0();
private static final short _SyntheticAccessorFSM_index_offsets[] = init__SyntheticAccessorFSM_index_offsets_0();
private static final byte _SyntheticAccessorFSM_indicies[] = init__SyntheticAccessorFSM_indicies_0();
private static final byte _SyntheticAccessorFSM_trans_targs[] = init__SyntheticAccessorFSM_trans_targs_0();
private static final byte _SyntheticAccessorFSM_trans_actions[] = init__SyntheticAccessorFSM_trans_actions_0();
@NonNull | private final Opcodes opcodes; | 0 | 2023-12-16 11:11:16+00:00 | 4k |
nimashidewanmini/layered-architecture-nimashi | src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java | [
{
"identifier": "ItemDAOImpl",
"path": "src/main/java/com/example/layeredarchitecture/dao/ItemDAOImpl.java",
"snippet": "public class ItemDAOImpl implements ItemDao {\n @Override\n public ArrayList<ItemDTO> getAllItems() throws SQLException, ClassNotFoundException {\n Connection connect... | import com.example.layeredarchitecture.dao.ItemDAOImpl;
import com.example.layeredarchitecture.dao.ItemDao;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.view.tdm.ItemTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*; | 2,201 | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
| package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
| ItemDao itemDAO=new ItemDAOImpl(); | 0 | 2023-12-16 04:14:29+00:00 | 4k |
J-SPOT/playground | backend/funnyboard/src/test/java/funnyboard/CommentServiceTest.java | [
{
"identifier": "CommentNotFoundException",
"path": "backend/funnyboard/src/main/java/funnyboard/config/error/exception/comment/CommentNotFoundException.java",
"snippet": "public class CommentNotFoundException extends NotFoundException {\n public CommentNotFoundException() {\n super(ErrorCode.... | import funnyboard.config.error.exception.comment.CommentNotFoundException;
import funnyboard.domain.Article;
import funnyboard.domain.Comment;
import funnyboard.dto.CommentForm;
import funnyboard.repository.ArticleRepository;
import funnyboard.repository.CommentRepository;
import funnyboard.service.CommentService;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat; | 2,206 | package funnyboard;
@ExtendWith(MockitoExtension.class)
public class CommentServiceTest {
@Mock
private CommentRepository commentRepository;
@Mock
private ArticleRepository articleRepository;
@InjectMocks
private CommentService commentService;
Article article1, article2;
Comment comment1, comment2, comment3, beforeUpdateComment, updatedComment, createdComment;
CommentForm createForm, updateForm;
@BeforeEach
void setup() {
article1 = new Article(1L, "제목 1", "내용 1");
article2 = new Article(2L, "제목 2", "내용 2");
comment1 = new Comment(null, article1, "작성자 1", "내용 1");
comment2 = new Comment(null, article1, "작성자 1", "내용 2");
comment3 = new Comment(null, article1, "작성자 2", "내용 3");
beforeUpdateComment = new Comment(1L, article1, "작성자 1", "내용 1");
updatedComment = new Comment(1L, article1, "작성자 1 수정", "내용 1 수정");
createdComment = new Comment(1L, article1, "작성자 1", "내용 1");
updateForm = new CommentForm(1L, article1.getId(), "작성자 1 수정", "내용 1 수정");
createForm = new CommentForm(null, article1.getId(), "작성자 1", "내용 1");
}
@DisplayName("특정 게시글에 모든 댓글 가져오기")
@Test
void FindComments_ReturnFindComments() {
//given
List<Comment> comments = Arrays.asList(comment1, comment2, comment3);
Mockito.when(commentRepository.findByArticleId(article1.getId())).thenReturn(comments);
//when
List<CommentForm> findCommentsDto = commentService.findAllComments(article1.getId());
List<Comment> findComments = findCommentsDto.stream()
.map(comment -> Comment.createComment(comment, article1))
.collect(Collectors.toList());
//then
assertThat(findComments).isNotNull();
assertThat(findComments).usingRecursiveComparison().isEqualTo(comments);
}
@DisplayName("특정 게시글에 특정 댓글 수정하기")
@Test
void UpdateComment_ReturnUpdatedComment() {
//given
Mockito.when(commentRepository.findById(beforeUpdateComment.getId())).thenReturn(Optional.of(updatedComment));
Mockito.when(commentRepository.save(updatedComment)).thenReturn(updatedComment);
//when
CommentForm updatedForm = commentService.update(beforeUpdateComment.getId(), updateForm);
//then
assertThat(updatedForm).isNotNull();
assertThat(updatedForm).usingRecursiveComparison().isEqualTo(updateForm);
}
@DisplayName("특정 댓글 생성하기")
@Test
void CreateComment_ReturnCreatedComment() {
//given
Mockito.when(articleRepository.findById(article1.getId())).thenReturn(Optional.of(article1));
Mockito.when(commentRepository.save(Mockito.any(Comment.class))).thenReturn(comment1);
//when
CommentForm createdForm = commentService.create(article1.getId(), createForm);
//then
assertThat(createdForm).isNotNull();
assertThat(createdForm).usingRecursiveComparison().isEqualTo(createForm);
}
@DisplayName("존재하는 특정 게시글 삭제하기")
@Test
void DeleteArticle_ReturnDeletedArticle() {
//given
Mockito.when(commentRepository.findById(createdComment.getId())).thenReturn(Optional.of(createdComment));
Mockito.doNothing().when(commentRepository).delete(createdComment);
//when
CommentForm deletedForm = commentService.delete(article1.getId());
//then
Mockito.verify(commentRepository).delete(createdComment);
}
@DisplayName("존재 하지 않는 특정 게시글 삭제하기")
@Test
void DeleteArticleNotExist_ReturnNull() {
//given
Mockito.when(commentRepository.findById(comment1.getId())).thenReturn(Optional.empty());
//when
//then
Assertions.assertThatThrownBy(() -> {
commentService.delete(comment1.getId()); | package funnyboard;
@ExtendWith(MockitoExtension.class)
public class CommentServiceTest {
@Mock
private CommentRepository commentRepository;
@Mock
private ArticleRepository articleRepository;
@InjectMocks
private CommentService commentService;
Article article1, article2;
Comment comment1, comment2, comment3, beforeUpdateComment, updatedComment, createdComment;
CommentForm createForm, updateForm;
@BeforeEach
void setup() {
article1 = new Article(1L, "제목 1", "내용 1");
article2 = new Article(2L, "제목 2", "내용 2");
comment1 = new Comment(null, article1, "작성자 1", "내용 1");
comment2 = new Comment(null, article1, "작성자 1", "내용 2");
comment3 = new Comment(null, article1, "작성자 2", "내용 3");
beforeUpdateComment = new Comment(1L, article1, "작성자 1", "내용 1");
updatedComment = new Comment(1L, article1, "작성자 1 수정", "내용 1 수정");
createdComment = new Comment(1L, article1, "작성자 1", "내용 1");
updateForm = new CommentForm(1L, article1.getId(), "작성자 1 수정", "내용 1 수정");
createForm = new CommentForm(null, article1.getId(), "작성자 1", "내용 1");
}
@DisplayName("특정 게시글에 모든 댓글 가져오기")
@Test
void FindComments_ReturnFindComments() {
//given
List<Comment> comments = Arrays.asList(comment1, comment2, comment3);
Mockito.when(commentRepository.findByArticleId(article1.getId())).thenReturn(comments);
//when
List<CommentForm> findCommentsDto = commentService.findAllComments(article1.getId());
List<Comment> findComments = findCommentsDto.stream()
.map(comment -> Comment.createComment(comment, article1))
.collect(Collectors.toList());
//then
assertThat(findComments).isNotNull();
assertThat(findComments).usingRecursiveComparison().isEqualTo(comments);
}
@DisplayName("특정 게시글에 특정 댓글 수정하기")
@Test
void UpdateComment_ReturnUpdatedComment() {
//given
Mockito.when(commentRepository.findById(beforeUpdateComment.getId())).thenReturn(Optional.of(updatedComment));
Mockito.when(commentRepository.save(updatedComment)).thenReturn(updatedComment);
//when
CommentForm updatedForm = commentService.update(beforeUpdateComment.getId(), updateForm);
//then
assertThat(updatedForm).isNotNull();
assertThat(updatedForm).usingRecursiveComparison().isEqualTo(updateForm);
}
@DisplayName("특정 댓글 생성하기")
@Test
void CreateComment_ReturnCreatedComment() {
//given
Mockito.when(articleRepository.findById(article1.getId())).thenReturn(Optional.of(article1));
Mockito.when(commentRepository.save(Mockito.any(Comment.class))).thenReturn(comment1);
//when
CommentForm createdForm = commentService.create(article1.getId(), createForm);
//then
assertThat(createdForm).isNotNull();
assertThat(createdForm).usingRecursiveComparison().isEqualTo(createForm);
}
@DisplayName("존재하는 특정 게시글 삭제하기")
@Test
void DeleteArticle_ReturnDeletedArticle() {
//given
Mockito.when(commentRepository.findById(createdComment.getId())).thenReturn(Optional.of(createdComment));
Mockito.doNothing().when(commentRepository).delete(createdComment);
//when
CommentForm deletedForm = commentService.delete(article1.getId());
//then
Mockito.verify(commentRepository).delete(createdComment);
}
@DisplayName("존재 하지 않는 특정 게시글 삭제하기")
@Test
void DeleteArticleNotExist_ReturnNull() {
//given
Mockito.when(commentRepository.findById(comment1.getId())).thenReturn(Optional.empty());
//when
//then
Assertions.assertThatThrownBy(() -> {
commentService.delete(comment1.getId()); | }).isInstanceOf(CommentNotFoundException.class) | 0 | 2023-12-15 16:05:45+00:00 | 4k |
matthiasbergneels/dhbwmawwi2023seb | src/excersises/chapter5/hausbau/builderpattern/constructionarea/HouseExampleRun.java | [
{
"identifier": "House",
"path": "src/excersises/chapter5/hausbau/builderpattern/house/House.java",
"snippet": "public class House {\n final static int DEFAULT_DOOR = 1;\n final static int DEFAULT_WINDOW = 1;\n final static int DEFAULT_FLOOR = 1;\n final static int DEFAULT_FLOOR_SPACE = 100;\n fina... | import excersises.chapter5.hausbau.builderpattern.house.House;
import excersises.chapter5.hausbau.builderpattern.house.HouseBuilder; | 1,744 | package excersises.chapter5.hausbau.builderpattern.constructionarea;
public class HouseExampleRun {
public static void main(String[] args) {
System.out.println("Aktuelle Anzahl Häuser: " + House.getObjCnt()); | package excersises.chapter5.hausbau.builderpattern.constructionarea;
public class HouseExampleRun {
public static void main(String[] args) {
System.out.println("Aktuelle Anzahl Häuser: " + House.getObjCnt()); | House myHouse = new HouseBuilder().buildFloors(5).buildDoors(3).buildWindows(20).setFloorSpace(300).buildFlatRoof().finalizeHouseBuilding(); | 1 | 2023-12-20 21:17:12+00:00 | 4k |
aborroy/alfresco-genai | alfresco-ai/alfresco-ai-listener/src/main/java/org/alfresco/genai/service/GenAiClient.java | [
{
"identifier": "Answer",
"path": "alfresco-ai/alfresco-ai-listener/src/main/java/org/alfresco/genai/model/Answer.java",
"snippet": "public class Answer {\n\n /**\n * The generated answer content.\n */\n private String answer;\n\n /**\n * The model information associated with the ge... | import jakarta.annotation.PostConstruct;
import okhttp3.*;
import org.alfresco.genai.model.Answer;
import org.alfresco.genai.model.Summary;
import org.alfresco.genai.model.Term;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit; | 1,893 | package org.alfresco.genai.service;
/**
* The {@code GenAiClient} class is a Spring service that interacts with the GenAI service to obtain document summaries
* and answers to specific questions. It uses an {@link OkHttpClient} to perform HTTP requests to the GenAI service
* endpoint, and it is configured with properties such as the GenAI service URL and request timeout.
*/
@Service
public class GenAiClient {
/**
* The base URL of the GenAI service obtained from configuration.
*/
@Value("${genai.url}")
String genaiUrl;
/**
* The request timeout for GenAI service requests obtained from configuration.
*/
@Value("${genai.request.timeout}")
Integer genaiTimeout;
/**
* Static instance of {@link JsonParser} to parse JSON responses from the GenAI service.
*/
static final JsonParser JSON_PARSER = JsonParserFactory.getJsonParser();
/**
* The OkHttpClient instance for making HTTP requests to the GenAI service.
*/
OkHttpClient client;
/**
* Initializes the OkHttpClient with specified timeouts during bean creation.
*/
@PostConstruct
public void init() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(genaiTimeout, TimeUnit.SECONDS)
.build();
}
/**
* Retrieves a document summary from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file for which the summary is requested.
* @return A {@link Summary} object containing the summary, tags, and model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/
public Summary getSummary(File pdfFile) throws IOException {
RequestBody requestBody = new MultipartBody
.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", pdfFile.getName(), RequestBody.create(pdfFile, MediaType.parse("application/pdf")))
.build();
Request request = new Request
.Builder()
.url(genaiUrl + "/summary")
.post(requestBody)
.build();
String response = client.newCall(request).execute().body().string();
Map<String, Object> aiResponse = JSON_PARSER.parseMap(response);
return new Summary()
.summary(aiResponse.get("summary").toString().trim())
.tags(Arrays.asList(aiResponse.get("tags").toString().split(",", -1)))
.model(aiResponse.get("model").toString());
}
/**
* Retrieves an answer to a specific question from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file containing the document related to the question.
* @param question The question for which an answer is requested.
* @return An {@link Answer} object containing the answer and the model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/ | package org.alfresco.genai.service;
/**
* The {@code GenAiClient} class is a Spring service that interacts with the GenAI service to obtain document summaries
* and answers to specific questions. It uses an {@link OkHttpClient} to perform HTTP requests to the GenAI service
* endpoint, and it is configured with properties such as the GenAI service URL and request timeout.
*/
@Service
public class GenAiClient {
/**
* The base URL of the GenAI service obtained from configuration.
*/
@Value("${genai.url}")
String genaiUrl;
/**
* The request timeout for GenAI service requests obtained from configuration.
*/
@Value("${genai.request.timeout}")
Integer genaiTimeout;
/**
* Static instance of {@link JsonParser} to parse JSON responses from the GenAI service.
*/
static final JsonParser JSON_PARSER = JsonParserFactory.getJsonParser();
/**
* The OkHttpClient instance for making HTTP requests to the GenAI service.
*/
OkHttpClient client;
/**
* Initializes the OkHttpClient with specified timeouts during bean creation.
*/
@PostConstruct
public void init() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(genaiTimeout, TimeUnit.SECONDS)
.build();
}
/**
* Retrieves a document summary from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file for which the summary is requested.
* @return A {@link Summary} object containing the summary, tags, and model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/
public Summary getSummary(File pdfFile) throws IOException {
RequestBody requestBody = new MultipartBody
.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", pdfFile.getName(), RequestBody.create(pdfFile, MediaType.parse("application/pdf")))
.build();
Request request = new Request
.Builder()
.url(genaiUrl + "/summary")
.post(requestBody)
.build();
String response = client.newCall(request).execute().body().string();
Map<String, Object> aiResponse = JSON_PARSER.parseMap(response);
return new Summary()
.summary(aiResponse.get("summary").toString().trim())
.tags(Arrays.asList(aiResponse.get("tags").toString().split(",", -1)))
.model(aiResponse.get("model").toString());
}
/**
* Retrieves an answer to a specific question from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file containing the document related to the question.
* @param question The question for which an answer is requested.
* @return An {@link Answer} object containing the answer and the model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/ | public Answer getAnswer(File pdfFile, String question) throws IOException { | 0 | 2023-12-21 12:28:53+00:00 | 4k |
dishantharuka/layered-architecture | src/main/java/com/example/layeredarchitecture/controller/PlaceOrderFormController.java | [
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLE... | import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.model.OrderDetailDTO;
import com.example.layeredarchitecture.view.tdm.OrderDetailTM;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 2,573 | package com.example.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId;
public void initialize() throws SQLException, ClassNotFoundException {
tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty"));
tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total"));
TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5);
lastCol.setCellValueFactory(param -> {
Button btnDelete = new Button("Delete");
btnDelete.setOnAction(event -> {
tblOrderDetails.getItems().remove(param.getValue());
tblOrderDetails.getSelectionModel().clearSelection();
calculateTotal();
enableOrDisablePlaceOrderButton();
});
return new ReadOnlyObjectWrapper<>(btnDelete);
});
orderId = generateNewOrderId();
lblId.setText("Order ID: " + orderId);
lblDate.setText(LocalDate.now().toString());
btnPlaceOrder.setDisable(true);
txtCustomerName.setFocusTraversable(false);
txtCustomerName.setEditable(false);
txtDescription.setFocusTraversable(false);
txtDescription.setEditable(false);
txtUnitPrice.setFocusTraversable(false);
txtUnitPrice.setEditable(false);
txtQtyOnHand.setFocusTraversable(false);
txtQtyOnHand.setEditable(false);
txtQty.setOnAction(event -> btnSave.fire());
txtQty.setEditable(false);
btnSave.setDisable(true);
cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
enableOrDisablePlaceOrderButton();
if (newValue != null) {
try {
/*Search Customer*/
Connection connection = DBConnection.getDbConnection().getConnection();
try {
if (!existCustomer(newValue + "")) {
// "There is no such customer associated with the id " + id
new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show();
}
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?");
pstm.setString(1, newValue + "");
ResultSet rst = pstm.executeQuery();
rst.next();
CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address"));
txtCustomerName.setText(customerDTO.getName());
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
txtCustomerName.clear();
}
});
cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> {
txtQty.setEditable(newItemCode != null);
btnSave.setDisable(newItemCode == null);
if (newItemCode != null) {
/*Find Item*/
try {
if (!existItem(newItemCode + "")) {
// throw new NotFoundException("There is no such item associated with the id " + code);
}
Connection connection = DBConnection.getDbConnection().getConnection();
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?");
pstm.setString(1, newItemCode + "");
ResultSet rst = pstm.executeQuery();
rst.next(); | package com.example.layeredarchitecture.controller;
public class PlaceOrderFormController {
public AnchorPane root;
public JFXButton btnPlaceOrder;
public TextField txtCustomerName;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnSave;
public TableView<OrderDetailTM> tblOrderDetails;
public TextField txtUnitPrice;
public JFXComboBox<String> cmbCustomerId;
public JFXComboBox<String> cmbItemCode;
public TextField txtQty;
public Label lblId;
public Label lblDate;
public Label lblTotal;
private String orderId;
public void initialize() throws SQLException, ClassNotFoundException {
tblOrderDetails.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblOrderDetails.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblOrderDetails.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qty"));
tblOrderDetails.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
tblOrderDetails.getColumns().get(4).setCellValueFactory(new PropertyValueFactory<>("total"));
TableColumn<OrderDetailTM, Button> lastCol = (TableColumn<OrderDetailTM, Button>) tblOrderDetails.getColumns().get(5);
lastCol.setCellValueFactory(param -> {
Button btnDelete = new Button("Delete");
btnDelete.setOnAction(event -> {
tblOrderDetails.getItems().remove(param.getValue());
tblOrderDetails.getSelectionModel().clearSelection();
calculateTotal();
enableOrDisablePlaceOrderButton();
});
return new ReadOnlyObjectWrapper<>(btnDelete);
});
orderId = generateNewOrderId();
lblId.setText("Order ID: " + orderId);
lblDate.setText(LocalDate.now().toString());
btnPlaceOrder.setDisable(true);
txtCustomerName.setFocusTraversable(false);
txtCustomerName.setEditable(false);
txtDescription.setFocusTraversable(false);
txtDescription.setEditable(false);
txtUnitPrice.setFocusTraversable(false);
txtUnitPrice.setEditable(false);
txtQtyOnHand.setFocusTraversable(false);
txtQtyOnHand.setEditable(false);
txtQty.setOnAction(event -> btnSave.fire());
txtQty.setEditable(false);
btnSave.setDisable(true);
cmbCustomerId.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
enableOrDisablePlaceOrderButton();
if (newValue != null) {
try {
/*Search Customer*/
Connection connection = DBConnection.getDbConnection().getConnection();
try {
if (!existCustomer(newValue + "")) {
// "There is no such customer associated with the id " + id
new Alert(Alert.AlertType.ERROR, "There is no such customer associated with the id " + newValue + "").show();
}
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Customer WHERE id=?");
pstm.setString(1, newValue + "");
ResultSet rst = pstm.executeQuery();
rst.next();
CustomerDTO customerDTO = new CustomerDTO(newValue + "", rst.getString("name"), rst.getString("address"));
txtCustomerName.setText(customerDTO.getName());
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to find the customer " + newValue + "" + e).show();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
txtCustomerName.clear();
}
});
cmbItemCode.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newItemCode) -> {
txtQty.setEditable(newItemCode != null);
btnSave.setDisable(newItemCode == null);
if (newItemCode != null) {
/*Find Item*/
try {
if (!existItem(newItemCode + "")) {
// throw new NotFoundException("There is no such item associated with the id " + code);
}
Connection connection = DBConnection.getDbConnection().getConnection();
PreparedStatement pstm = connection.prepareStatement("SELECT * FROM Item WHERE code=?");
pstm.setString(1, newItemCode + "");
ResultSet rst = pstm.executeQuery();
rst.next(); | ItemDTO item = new ItemDTO(newItemCode + "", rst.getString("description"), rst.getBigDecimal("unitPrice"), rst.getInt("qtyOnHand")); | 2 | 2023-12-16 04:23:56+00:00 | 4k |
drSolutions-OpenSource/Cotacao_Moedas_Estrangeiras | src/cotacao/Cotacao.java | [
{
"identifier": "ConverterJsonString",
"path": "src/classes/ConverterJsonString.java",
"snippet": "public class ConverterJsonString {\n /**\n * Converter um JSON recebido via webservice em uma String\n *\n * @param buffereReader sendo o JSON recebido do webservice\n * @return uma Srti... | import classes.ConverterJsonString;
import classes.Moeda;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; | 1,795 | package cotacao;
/**
* Obter a contação atual de moedas estrangeiras através do webservice: https://economia.awesomeapi.com.br/last/USD-BRL
* As seguintes cotações estão disponíveis:
* - Dólar Americano Comercial (USD-BRL)
* - Dólar Americano Turismo (USD-BRLT)
* - Euro (EUR-BRL)
* - Franco Suíço (CHF-BRL)
* - Libra Esterlina (GBP-BRL)
* - Peso Chileno (CLP-BRL)
*
* @author Diego Mendes Rodrigues
*/
public class Cotacao {
static String webService = "https://economia.awesomeapi.com.br/last/";
static int codigoSucesso = 200;
/**
* Realiza a cotação atual de uma moeda estrangeira
*
* @param moeda sendo a moeda em que a cotação será realizada (USD, USDT, EUR, CHF, GBP ou CLP)
* @return a cotação atual da moeda como umo instância da classe Maeda
*/ | package cotacao;
/**
* Obter a contação atual de moedas estrangeiras através do webservice: https://economia.awesomeapi.com.br/last/USD-BRL
* As seguintes cotações estão disponíveis:
* - Dólar Americano Comercial (USD-BRL)
* - Dólar Americano Turismo (USD-BRLT)
* - Euro (EUR-BRL)
* - Franco Suíço (CHF-BRL)
* - Libra Esterlina (GBP-BRL)
* - Peso Chileno (CLP-BRL)
*
* @author Diego Mendes Rodrigues
*/
public class Cotacao {
static String webService = "https://economia.awesomeapi.com.br/last/";
static int codigoSucesso = 200;
/**
* Realiza a cotação atual de uma moeda estrangeira
*
* @param moeda sendo a moeda em que a cotação será realizada (USD, USDT, EUR, CHF, GBP ou CLP)
* @return a cotação atual da moeda como umo instância da classe Maeda
*/ | public Moeda realizarCotacao(String moeda) { | 1 | 2023-12-16 14:27:51+00:00 | 4k |
123yyh123/xiaofanshu | xfs-third-server/src/main/java/com/yyh/xfs/third/sevice/impl/AliyunOssServiceImpl.java | [
{
"identifier": "Result",
"path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java",
"snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv... | import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yyh.xfs.common.domain.Result;
import com.yyh.xfs.common.myEnum.ExceptionMsgEnum;
import com.yyh.xfs.common.utils.ResultUtil;
import com.yyh.xfs.common.web.exception.BusinessException;
import com.yyh.xfs.common.web.exception.SystemException;
import com.yyh.xfs.third.config.AliyunOss;
import com.yyh.xfs.third.sevice.AliyunOssService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID; | 2,009 | package com.yyh.xfs.third.sevice.impl;
/**
* @author yyh
* @date 2023-12-21
*/
@Service
public class AliyunOssServiceImpl implements AliyunOssService {
private final AliyunOss aliyunOss;
public AliyunOssServiceImpl(AliyunOss aliyunOss) {
this.aliyunOss = aliyunOss;
}
@Override
public Result<String> uploadImg(MultipartFile file) {
OSS ossClient = getOssClient(file);
try {
String s = uploadAndCreateUrl(ossClient, file,".png");
return ResultUtil.successPost(s);
} catch (Exception e) { | package com.yyh.xfs.third.sevice.impl;
/**
* @author yyh
* @date 2023-12-21
*/
@Service
public class AliyunOssServiceImpl implements AliyunOssService {
private final AliyunOss aliyunOss;
public AliyunOssServiceImpl(AliyunOss aliyunOss) {
this.aliyunOss = aliyunOss;
}
@Override
public Result<String> uploadImg(MultipartFile file) {
OSS ossClient = getOssClient(file);
try {
String s = uploadAndCreateUrl(ossClient, file,".png");
return ResultUtil.successPost(s);
} catch (Exception e) { | throw new SystemException(ExceptionMsgEnum.ALIYUN_OSS_INIT_ERROR, e); | 1 | 2023-12-15 08:13:42+00:00 | 4k |
catools2/athena | athena-api-boot/src/test/java/org/catools/athena/rest/core/mapper/AthenaCoreMapperIT.java | [
{
"identifier": "EnvironmentDto",
"path": "athena-core/src/main/java/org/catools/athena/core/model/EnvironmentDto.java",
"snippet": "@Data\n@Accessors(chain = true)\n@NoArgsConstructor\npublic class EnvironmentDto {\n private Long id;\n\n @NotBlank\n @Size(max = 5)\n private String code;\n\n @NotBl... | import org.catools.athena.core.model.EnvironmentDto;
import org.catools.athena.core.model.ProjectDto;
import org.catools.athena.core.model.UserDto;
import org.catools.athena.rest.AthenaBaseTest;
import org.catools.athena.rest.core.builder.AthenaCoreBuilder;
import org.catools.athena.rest.core.entity.Environment;
import org.catools.athena.rest.core.entity.Project;
import org.catools.athena.rest.core.entity.User;
import org.catools.athena.rest.core.service.AthenaCoreService;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo; | 2,559 | package org.catools.athena.rest.core.mapper;
public class AthenaCoreMapperIT extends AthenaBaseTest {
private static ProjectDto PROJECT_DTO;
private static Project PROJECT; | package org.catools.athena.rest.core.mapper;
public class AthenaCoreMapperIT extends AthenaBaseTest {
private static ProjectDto PROJECT_DTO;
private static Project PROJECT; | private static EnvironmentDto ENVIRONMENT_DTO; | 0 | 2023-12-16 22:30:49+00:00 | 4k |
premiering/permad-game | src/main/java/club/premiering/permad/format/v2/V2MapDataSkapConverter.java | [
{
"identifier": "EntityLavaSpike",
"path": "src/main/java/club/premiering/permad/entity/spawners/EntityLavaSpike.java",
"snippet": "public class EntityLavaSpike extends SpawnerEntity {\n public EntityLavaSpike() {\n this.setSolid(false);\n this.setCollideWithSolids(false);\n this... | import club.premiering.permad.entity.*;
import club.premiering.permad.entity.spawners.EntityLavaSpike;
import club.premiering.permad.math.Vector2;
import club.premiering.permad.math.Vector4;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.awt.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Objects; | 1,916 | package club.premiering.permad.format.v2;
public class V2MapDataSkapConverter extends V2MapData {
//If set to false, then all obstacle colors won't work (does not affect blocks!)
private static final boolean OBSTACLES_USE_CUSTOM_COLOR = false;
@Override
public void loadMapData(byte[] mapData) {
super.loadMapData(this.convertMapFromSkap(new String(mapData)).getBytes(StandardCharsets.UTF_8));
}
public String convertMapFromSkap(String skapMap) {
JsonObject json = GSON.fromJson(skapMap, JsonObject.class);
var v2Map = new V2Map();
v2Map.worlds = new ArrayList<>();
var settings = json.getAsJsonObject("settings");
v2Map.metadata.name = settings.get("name").getAsString();
v2Map.metadata.creator = settings.get("creator").getAsString();
var worlds = json.getAsJsonArray("maps");
var nameOfSpawn = settings.get("spawnArea").getAsString();
var spawnPos = readSkapVec2(settings.getAsJsonArray("spawnPosition"));
int worldIdCounter = 0;
for (int i = 0; i < worlds.size(); i++) {
var world = new V2World();
world.entities = new ArrayList<>();
world.worldId = worldIdCounter;
worldIdCounter++;
var sWorld = worlds.get(i).getAsJsonObject();
world.worldName = sWorld.get("name").getAsString();
if (world.worldName.equals(nameOfSpawn)) {
world.worldSpawn = spawnPos;
v2Map.spawnWorldId = world.worldId;
}
var worldSize = readSkapVec2(sWorld.get("size").getAsJsonArray()); | package club.premiering.permad.format.v2;
public class V2MapDataSkapConverter extends V2MapData {
//If set to false, then all obstacle colors won't work (does not affect blocks!)
private static final boolean OBSTACLES_USE_CUSTOM_COLOR = false;
@Override
public void loadMapData(byte[] mapData) {
super.loadMapData(this.convertMapFromSkap(new String(mapData)).getBytes(StandardCharsets.UTF_8));
}
public String convertMapFromSkap(String skapMap) {
JsonObject json = GSON.fromJson(skapMap, JsonObject.class);
var v2Map = new V2Map();
v2Map.worlds = new ArrayList<>();
var settings = json.getAsJsonObject("settings");
v2Map.metadata.name = settings.get("name").getAsString();
v2Map.metadata.creator = settings.get("creator").getAsString();
var worlds = json.getAsJsonArray("maps");
var nameOfSpawn = settings.get("spawnArea").getAsString();
var spawnPos = readSkapVec2(settings.getAsJsonArray("spawnPosition"));
int worldIdCounter = 0;
for (int i = 0; i < worlds.size(); i++) {
var world = new V2World();
world.entities = new ArrayList<>();
world.worldId = worldIdCounter;
worldIdCounter++;
var sWorld = worlds.get(i).getAsJsonObject();
world.worldName = sWorld.get("name").getAsString();
if (world.worldName.equals(nameOfSpawn)) {
world.worldSpawn = spawnPos;
v2Map.spawnWorldId = world.worldId;
}
var worldSize = readSkapVec2(sWorld.get("size").getAsJsonArray()); | world.worldSize = new Vector4(0, 0, worldSize.x, worldSize.y); | 2 | 2023-12-20 03:13:05+00:00 | 4k |
VRavindu/layered-architecture-Vimukthi-Ravindu | src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java | [
{
"identifier": "ItemBO",
"path": "src/main/java/com/example/layeredarchitecture/bo/ItemBO.java",
"snippet": "public interface ItemBO {\n ArrayList<ItemDTO> getAllItem() throws SQLException, ClassNotFoundException;\n\n boolean deleteItem(String code) throws SQLException, ClassNotFoundException;\n\... | import com.example.layeredarchitecture.bo.ItemBO;
import com.example.layeredarchitecture.bo.ItemBOimpl;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.view.tdm.ItemTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList; | 1,680 | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
ItemBO itemBO = new ItemBOimpl();
public void initialize() {
tblItems.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblItems.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblItems.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qtyOnHand"));
tblItems.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
initUI();
tblItems.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
btnDelete.setDisable(newValue == null);
btnSave.setText(newValue != null ? "Update" : "Save");
btnSave.setDisable(newValue == null);
if (newValue != null) {
txtCode.setText(newValue.getCode());
txtDescription.setText(newValue.getDescription());
txtUnitPrice.setText(newValue.getUnitPrice().setScale(2).toString());
txtQtyOnHand.setText(newValue.getQtyOnHand() + "");
txtCode.setDisable(false);
txtDescription.setDisable(false);
txtUnitPrice.setDisable(false);
txtQtyOnHand.setDisable(false);
}
});
txtQtyOnHand.setOnAction(event -> btnSave.fire());
loadAllItems();
}
private void loadAllItems() {
tblItems.getItems().clear();
try {
/*Get all items*/
| package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem;
ItemBO itemBO = new ItemBOimpl();
public void initialize() {
tblItems.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("code"));
tblItems.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("description"));
tblItems.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("qtyOnHand"));
tblItems.getColumns().get(3).setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
initUI();
tblItems.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
btnDelete.setDisable(newValue == null);
btnSave.setText(newValue != null ? "Update" : "Save");
btnSave.setDisable(newValue == null);
if (newValue != null) {
txtCode.setText(newValue.getCode());
txtDescription.setText(newValue.getDescription());
txtUnitPrice.setText(newValue.getUnitPrice().setScale(2).toString());
txtQtyOnHand.setText(newValue.getQtyOnHand() + "");
txtCode.setDisable(false);
txtDescription.setDisable(false);
txtUnitPrice.setDisable(false);
txtQtyOnHand.setDisable(false);
}
});
txtQtyOnHand.setOnAction(event -> btnSave.fire());
loadAllItems();
}
private void loadAllItems() {
tblItems.getItems().clear();
try {
/*Get all items*/
| ArrayList<ItemDTO> allItems = itemBO.getAllItem(); | 2 | 2023-12-16 04:19:18+00:00 | 4k |
egisac/ethicalvoting | src/main/java/net/egis/ethicalvoting/data/ProfileManager.java | [
{
"identifier": "EthicalVoting",
"path": "src/main/java/net/egis/ethicalvoting/EthicalVoting.java",
"snippet": "@Getter\npublic final class EthicalVoting extends JavaPlugin {\n\n @Getter\n private static EthicalVoting self;\n\n private StorageInterface storage;\n private ProfileManager profi... | import lombok.Getter;
import net.egis.ethicalvoting.EthicalVoting;
import net.egis.ethicalvoting.data.player.EthicalProfile;
import net.egis.ethicalvoting.lists.PagedList;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitTask;
import java.util.List;
import java.util.UUID;
| 1,714 | package net.egis.ethicalvoting.data;
@Getter
public class ProfileManager {
private final StorageInterface storage;
private final List<EthicalProfile> profiles;
private final BukkitTask sortProfilesTask;
public ProfileManager(StorageInterface storage) {
profiles = storage.getProfiles();
this.storage = storage;
| package net.egis.ethicalvoting.data;
@Getter
public class ProfileManager {
private final StorageInterface storage;
private final List<EthicalProfile> profiles;
private final BukkitTask sortProfilesTask;
public ProfileManager(StorageInterface storage) {
profiles = storage.getProfiles();
this.storage = storage;
| sortProfilesTask = Bukkit.getScheduler().runTaskTimerAsynchronously(EthicalVoting.getSelf(), new SortPlayersTask(this), 0, 20*60*5);
| 0 | 2023-12-15 16:48:38+00:00 | 4k |
SAMJ-CSDC26BB/samj-javafx | samj/src/main/java/com/samj/shared/DatabaseAPI.java | [
{
"identifier": "CallForwardingRecordsDAO",
"path": "samj/src/main/java/com/samj/backend/CallForwardingRecordsDAO.java",
"snippet": "public class CallForwardingRecordsDAO {\n\n private static final String LOAD_RECORDS_SQL = \"SELECT c.*, u.number, u.username FROM call_forwarding_records as c JOIN use... | import com.samj.backend.CallForwardingRecordsDAO;
import com.samj.backend.UserDAO;
import java.time.LocalDateTime;
import java.util.Set; | 3,274 | package com.samj.shared;
public class DatabaseAPI {
public static boolean createNewUser(UserDTO userDTO) {
// todo hash the user psw. | package com.samj.shared;
public class DatabaseAPI {
public static boolean createNewUser(UserDTO userDTO) {
// todo hash the user psw. | return UserDAO.createUser(userDTO); | 1 | 2023-12-18 09:42:06+00:00 | 4k |
approachcircle/Pong | src/main/java/net/approachcircle/game/PauseScreen.java | [
{
"identifier": "Button",
"path": "src/main/java/net/approachcircle/game/backend/Button.java",
"snippet": "public class Button implements Renderable, Transformable {\n private float x;\n private float y;\n private final boolean background;\n private TransformableRect buttonBackground;\n p... | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import net.approachcircle.game.backend.Button;
import net.approachcircle.game.backend.DefaultTextScaling;
import net.approachcircle.game.backend.Screen;
import net.approachcircle.game.backend.TextRenderable; | 3,187 | package net.approachcircle.game;
public class PauseScreen extends Screen {
private final Button resumeButton;
private final Button quitButton; | package net.approachcircle.game;
public class PauseScreen extends Screen {
private final Button resumeButton;
private final Button quitButton; | private final TextRenderable title; | 3 | 2023-12-20 16:25:30+00:00 | 4k |
jollyboss123/astra | modules/app/src/main/java/com/jolly/astra/config/SecurityConfiguration.java | [
{
"identifier": "AuthoritiesConstants",
"path": "modules/app/src/main/java/com/jolly/astra/security/AuthoritiesConstants.java",
"snippet": "public final class AuthoritiesConstants {\n\n public static final String ADMIN = \"ADMIN\";\n\n public static final String USER = \"USER\";\n\n public static fin... | import com.jolly.astra.security.AuthoritiesConstants;
import com.jolly.heimdall.JwtAbstractAuthenticationTokenConverter;
import com.jolly.heimdall.OAuthentication;
import com.jolly.heimdall.claimset.OpenIdClaimSet;
import com.jolly.heimdall.hooks.ExpressionInterceptUrlRegistryPostProcessor;
import com.jolly.heimdall.properties.HeimdallOidcProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.jwt.JwtClaimNames;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.util.Collection;
import java.util.Map; | 2,944 | package com.jolly.astra.config;
/**
* @author jolly
*/
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
JwtAbstractAuthenticationTokenConverter authenticationConverter(
Converter<Map<String, Object>, Collection<? extends GrantedAuthority>> authoritiesConverter,
HeimdallOidcProperties heimdallProperties
) {
return jwt -> new OAuthentication<>(
new OpenIdClaimSet(jwt.getClaims(), heimdallProperties.getOpProperties(jwt.getClaims().get(JwtClaimNames.ISS)).getUsernameClaim()),
authoritiesConverter.convert(jwt.getClaims()),
jwt.getTokenValue()
);
}
@Bean | package com.jolly.astra.config;
/**
* @author jolly
*/
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
JwtAbstractAuthenticationTokenConverter authenticationConverter(
Converter<Map<String, Object>, Collection<? extends GrantedAuthority>> authoritiesConverter,
HeimdallOidcProperties heimdallProperties
) {
return jwt -> new OAuthentication<>(
new OpenIdClaimSet(jwt.getClaims(), heimdallProperties.getOpProperties(jwt.getClaims().get(JwtClaimNames.ISS)).getUsernameClaim()),
authoritiesConverter.convert(jwt.getClaims()),
jwt.getTokenValue()
);
}
@Bean | ExpressionInterceptUrlRegistryPostProcessor expressionInterceptUrlRegistryPostProcessor() { | 4 | 2023-12-17 05:24:05+00:00 | 4k |
Blawuken/MicroG-Extended | play-services-cast/src/main/java/org/microg/gms/cast/CastApiClientBuilder.java | [
{
"identifier": "Cast",
"path": "play-services-cast/src/main/java/com/google/android/gms/cast/Cast.java",
"snippet": "@PublicApi\npublic final class Cast {\n\n /**\n * A constant indicating that the Google Cast device is not the currently active video input.\n */\n public static final int ... | import android.content.Context;
import android.os.Looper;
import com.google.android.gms.cast.Cast;
import com.google.android.gms.common.api.Api;
import org.microg.gms.common.api.ApiClientBuilder;
import org.microg.gms.common.api.ApiClientSettings;
import org.microg.gms.common.api.ConnectionCallbacks;
import org.microg.gms.common.api.OnConnectionFailedListener; | 3,053 | /*
* Copyright (C) 2013-2017 microG Project Team
*
* 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 org.microg.gms.cast;
public class CastApiClientBuilder implements ApiClientBuilder<Cast.CastOptions> {
@Override | /*
* Copyright (C) 2013-2017 microG Project Team
*
* 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 org.microg.gms.cast;
public class CastApiClientBuilder implements ApiClientBuilder<Cast.CastOptions> {
@Override | public Api.Client build(Cast.CastOptions options, Context context, Looper looper, ApiClientSettings clientSettings, ConnectionCallbacks callbacks, OnConnectionFailedListener connectionFailedListener) { | 3 | 2023-12-17 16:14:53+00:00 | 4k |
Yolka5/FTC-Imu3 | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/redCheck.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java",
"snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(2, 0, 0);\n publi... | import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.geometry.Vector2d;
import com.acmerobotics.roadrunner.trajectory.Trajectory;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.ColorSensor;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.OpticalDistanceSensor;
import org.firstinspires.ftc.teamcode.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; | 3,100 | package org.firstinspires.ftc.teamcode;
/*
* This is an example of a more complex path to really test the tuning.
*/
@Autonomous(group = "drive")
public class redCheck extends LinearOpMode {
public static double SPEED = 0.15;
OpticalDistanceSensor lightSensor;
private ColorSensor colorSensor;
Boolean RedFirstTime = false;
public double correction;
public double BlueCorrection;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode;
/*
* This is an example of a more complex path to really test the tuning.
*/
@Autonomous(group = "drive")
public class redCheck extends LinearOpMode {
public static double SPEED = 0.15;
OpticalDistanceSensor lightSensor;
private ColorSensor colorSensor;
Boolean RedFirstTime = false;
public double correction;
public double BlueCorrection;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 0 | 2023-12-15 16:57:19+00:00 | 4k |
Dhananjay-mygithubcode/CRM-PROJECT | src/main/java/com/inn/cafe/serviceImpl/UserServiceImpl.java | [
{
"identifier": "CustomerUserDetailsService",
"path": "src/main/java/com/inn/cafe/JWT/CustomerUserDetailsService.java",
"snippet": "@Slf4j\n@Service\npublic class CustomerUserDetailsService implements UserDetailsService {\n\n @Autowired\n UserDao userDao;\n\n private com.inn.cafe.POJO.User user... | import com.google.common.base.Strings;
import com.inn.cafe.JWT.CustomerUserDetailsService;
import com.inn.cafe.JWT.JwtFilter;
import com.inn.cafe.JWT.jwtUtil;
import com.inn.cafe.POJO.User;
import com.inn.cafe.constents.CafeConstants;
import com.inn.cafe.dao.UserDao;
import com.inn.cafe.service.UserService;
import com.inn.cafe.utils.CafeUtils;
import com.inn.cafe.utils.EmailUtil;
import com.inn.cafe.wrapper.UserWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import java.util.*; | 3,236 | package com.inn.cafe.serviceImpl;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
jwtUtil jwtUtil;
@Autowired | package com.inn.cafe.serviceImpl;
@Slf4j
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao userDao;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
jwtUtil jwtUtil;
@Autowired | JwtFilter jwtFilter; | 1 | 2023-12-20 11:47:58+00:00 | 4k |
Frig00/Progetto-Ing-Software | src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/service/TitoloViaggioService.java | [
{
"identifier": "TitoloViaggioDao",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/dao/TitoloViaggioDao.java",
"snippet": "public class TitoloViaggioDao implements ITitoloViaggioDao {\n /**\n * Connessione al database mediante il framework di Hibernate\n */\n privat... | import it.unipv.po.aioobe.trenissimo.model.persistence.dao.TitoloViaggioDao;
import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity;
import it.unipv.po.aioobe.trenissimo.model.persistence.util.service.ITitoloVIaggioService;
import java.util.List; | 3,001 | package it.unipv.po.aioobe.trenissimo.model.persistence.service;
/**
* Classe che, secondo il pattern Facade, implementa gli stessi metodi di TitoloViaggioDao con l'aggiunta della gestione delle sessioni del framework Hibernate.
* Classe progettata per nascondere al modello delle classi la complessità del sistema sottostante (Hibernate)
*
* @author ArrayIndexOutOfBoundsException
*/
public class TitoloViaggioService implements ITitoloVIaggioService {
private static TitoloViaggioDao titoloViaggioDao;
public TitoloViaggioService() {
titoloViaggioDao = new TitoloViaggioDao();
}
@Override | package it.unipv.po.aioobe.trenissimo.model.persistence.service;
/**
* Classe che, secondo il pattern Facade, implementa gli stessi metodi di TitoloViaggioDao con l'aggiunta della gestione delle sessioni del framework Hibernate.
* Classe progettata per nascondere al modello delle classi la complessità del sistema sottostante (Hibernate)
*
* @author ArrayIndexOutOfBoundsException
*/
public class TitoloViaggioService implements ITitoloVIaggioService {
private static TitoloViaggioDao titoloViaggioDao;
public TitoloViaggioService() {
titoloViaggioDao = new TitoloViaggioDao();
}
@Override | public List<TitoloViaggioEntity> findAll() { | 1 | 2023-12-21 10:41:11+00:00 | 4k |
Workworks/rule-engine-practice | drools-demo/src/test/java/org/kfaino/test/DroolsTest.java | [
{
"identifier": "ComparisonOperatorEntity",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/ComparisonOperatorEntity.java",
"snippet": "public class ComparisonOperatorEntity {\n private String names;\n private List<String> list;\n\n public String getNames() {\n return names;\... | import org.kfaino.drools.entity.ComparisonOperatorEntity;
import org.kfaino.drools.entity.Order;
import org.kfaino.drools.entity.Student;
import org.kfaino.drools.service.UserService;
import org.drools.core.base.RuleNameEqualsAgendaFilter;
import org.drools.core.base.RuleNameStartsWithAgendaFilter;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
import java.util.ArrayList;
import java.util.List; | 2,495 | package org.kfaino.test;
public class DroolsTest {
@Test
public void test1(){
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
Order order = new Order();
order.setOriginalPrice(500d);
//将Order对象插入到工作内存中
session.insert(order);
System.out.println("----优惠后价格:"+order.getRealPrice());
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
System.out.println("优惠后价格:"+order.getRealPrice());
}
//测试比较操作符
@Test
public void test2(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("李四");
List<String> list = new ArrayList<String>();
list.add("张三2");
//list.add("李四");
fact.setList(list);
session.insert(fact);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试执行指定规则
@Test
public void test3(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("李四");
List<String> list = new ArrayList<String>();
list.add("张三2");
//list.add("李四");
fact.setList(list);
session.insert(fact);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
//使用框架提供的规则过滤器执行指定规则
//session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_comparison_notcontains"));
session.fireAllRules(new RuleNameStartsWithAgendaFilter("rule_"));
//关闭会话
session.dispose();
}
//测试Drools内置方法---update
@Test
public void test4(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(4);
session.insert(student);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试Drools内置方法---insert
@Test
public void test5(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(50);
session.insert(student);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试规则属性agenda-group属性
@Test
public void test6(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//指定组获得焦点
session.getAgenda().getAgendaGroup("agenda_group_1").setFocus();
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试规则属性timer属性
@Test
public void test7() throws Exception{
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
final KieSession session = kieContainer.newKieSession();
new Thread(new Runnable() {
public void run() {
//启动规则引擎进行规则匹配,直到调用halt方法才结束规则引擎
session.fireUntilHalt();
}
}).start();
Thread.sleep(10000);
//结束规则引擎
session.halt();
//关闭会话
session.dispose();
}
//测试规则属性date-effective属性
@Test
public void test8(){
//设置日期格式
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_dateeffective_1"));
//关闭会话
session.dispose();
}
//测试全局变量
@Test
public void test9(){
//设置日期格式
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//设置全局变量,变量名称必须和规则文件中定义的变量名一致
session.setGlobal("count",5);
List<String> list = new ArrayList<String>();
list.add("itheima");
session.setGlobal("gList",list);
| package org.kfaino.test;
public class DroolsTest {
@Test
public void test1(){
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
Order order = new Order();
order.setOriginalPrice(500d);
//将Order对象插入到工作内存中
session.insert(order);
System.out.println("----优惠后价格:"+order.getRealPrice());
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
System.out.println("优惠后价格:"+order.getRealPrice());
}
//测试比较操作符
@Test
public void test2(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("李四");
List<String> list = new ArrayList<String>();
list.add("张三2");
//list.add("李四");
fact.setList(list);
session.insert(fact);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试执行指定规则
@Test
public void test3(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
ComparisonOperatorEntity fact = new ComparisonOperatorEntity();
fact.setNames("李四");
List<String> list = new ArrayList<String>();
list.add("张三2");
//list.add("李四");
fact.setList(list);
session.insert(fact);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
//使用框架提供的规则过滤器执行指定规则
//session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_comparison_notcontains"));
session.fireAllRules(new RuleNameStartsWithAgendaFilter("rule_"));
//关闭会话
session.dispose();
}
//测试Drools内置方法---update
@Test
public void test4(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(4);
session.insert(student);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试Drools内置方法---insert
@Test
public void test5(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
Student student = new Student();
student.setAge(50);
session.insert(student);
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试规则属性agenda-group属性
@Test
public void test6(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//指定组获得焦点
session.getAgenda().getAgendaGroup("agenda_group_1").setFocus();
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
}
//测试规则属性timer属性
@Test
public void test7() throws Exception{
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
final KieSession session = kieContainer.newKieSession();
new Thread(new Runnable() {
public void run() {
//启动规则引擎进行规则匹配,直到调用halt方法才结束规则引擎
session.fireUntilHalt();
}
}).start();
Thread.sleep(10000);
//结束规则引擎
session.halt();
//关闭会话
session.dispose();
}
//测试规则属性date-effective属性
@Test
public void test8(){
//设置日期格式
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules(new RuleNameEqualsAgendaFilter("rule_dateeffective_1"));
//关闭会话
session.dispose();
}
//测试全局变量
@Test
public void test9(){
//设置日期格式
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//设置全局变量,变量名称必须和规则文件中定义的变量名一致
session.setGlobal("count",5);
List<String> list = new ArrayList<String>();
list.add("itheima");
session.setGlobal("gList",list);
| session.setGlobal("userService",new UserService()); | 3 | 2023-12-21 06:23:04+00:00 | 4k |
SagenApp/gpt-for-uds | src/main/java/app/sagen/chatgptclient/UnixSocketServer.java | [
{
"identifier": "ChatCompletionRequestMessage",
"path": "src/main/java/app/sagen/chatgptclient/data/ChatCompletionRequestMessage.java",
"snippet": "public final class ChatCompletionRequestMessage {\n @SerializedName(\"role\")\n private final String role;\n @SerializedName(\"content\")\n priv... | import app.sagen.chatgptclient.data.ChatCompletionRequestMessage;
import app.sagen.chatgptclient.gpt.ChatGptClient;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.Type;
import java.net.StandardProtocolFamily;
import java.net.UnixDomainSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List; | 1,607 | package app.sagen.chatgptclient;
public class UnixSocketServer {
private static final Gson gson = new GsonBuilder().create();
private record ServerConfig(Path socketFile, String apiKey) {}
public static ServerConfig parseConfig(String...args) {
String socketFilePath = "/tmp/gpt_socket"; // Default socket file path
String gptApiToken = ""; // GPT API token
// Parse the command-line arguments
if (args.length >= 2) {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--socket-file":
case "-f":
if (i + 1 < args.length) {
socketFilePath = args[++i];
} else {
System.err.println("Expected argument for socket file path");
throw new IllegalStateException("Expected argument for socket file path");
}
break;
case "--gpt-token":
case "-t":
if (i + 1 < args.length) {
gptApiToken = args[++i];
} else {
throw new IllegalStateException("Expected argument for GPT API token");
}
break;
default:
System.err.println("Unexpected argument: " + args[i]);
throw new IllegalStateException("Unexpected argument: " + args[i]);
}
}
} else {
throw new IllegalStateException("Usage: java -jar app.jar -f <socket-file-path> -t <gpt-api-token>");
}
// Verify that the GPT API token is set
if (gptApiToken.isEmpty()) {
throw new IllegalStateException("GPT API token is required");
}
if (socketFilePath.isEmpty()) {
throw new IllegalStateException("Socket file path is required");
}
try {
Path path = Path.of(socketFilePath);
return new ServerConfig(path, gptApiToken);
} catch (Exception e) {
throw new IllegalStateException("Invalid socket file path: " + socketFilePath, e);
}
}
public static void main(String[] args) throws IOException {
ServerConfig serverConfig = parseConfig(args);
// Delete the socket file if it already exists
Files.deleteIfExists(serverConfig.socketFile());
// Create the server socket channel and bind it
try (ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(serverConfig.socketFile());
serverChannel.bind(address);
System.out.println("Server listening on " + serverConfig.socketFile());
ChatGptClient gpt = new ChatGptClient(serverConfig.apiKey());
// Server loop
while (true) {
// Accept an incoming connection
try (SocketChannel socketChannel = serverChannel.accept()) {
System.out.println("Accepted a connection from " + socketChannel.getRemoteAddress());
// Read the length of the incoming message
ByteBuffer inputLengthBuffer = ByteBuffer.allocate(4);
socketChannel.read(inputLengthBuffer);
inputLengthBuffer.flip();
int length = inputLengthBuffer.getInt();
System.out.println("Incoming message length: " + length);
// Allocate a buffer of the specified size to store the incoming message
ByteBuffer messageBuffer = ByteBuffer.allocate(length);
socketChannel.read(messageBuffer);
messageBuffer.flip();
// Convert the ByteBuffer to a String that contains our JSON message
String jsonMessage = new String(messageBuffer.array());
System.out.println("Incoming message: " + jsonMessage);
| package app.sagen.chatgptclient;
public class UnixSocketServer {
private static final Gson gson = new GsonBuilder().create();
private record ServerConfig(Path socketFile, String apiKey) {}
public static ServerConfig parseConfig(String...args) {
String socketFilePath = "/tmp/gpt_socket"; // Default socket file path
String gptApiToken = ""; // GPT API token
// Parse the command-line arguments
if (args.length >= 2) {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--socket-file":
case "-f":
if (i + 1 < args.length) {
socketFilePath = args[++i];
} else {
System.err.println("Expected argument for socket file path");
throw new IllegalStateException("Expected argument for socket file path");
}
break;
case "--gpt-token":
case "-t":
if (i + 1 < args.length) {
gptApiToken = args[++i];
} else {
throw new IllegalStateException("Expected argument for GPT API token");
}
break;
default:
System.err.println("Unexpected argument: " + args[i]);
throw new IllegalStateException("Unexpected argument: " + args[i]);
}
}
} else {
throw new IllegalStateException("Usage: java -jar app.jar -f <socket-file-path> -t <gpt-api-token>");
}
// Verify that the GPT API token is set
if (gptApiToken.isEmpty()) {
throw new IllegalStateException("GPT API token is required");
}
if (socketFilePath.isEmpty()) {
throw new IllegalStateException("Socket file path is required");
}
try {
Path path = Path.of(socketFilePath);
return new ServerConfig(path, gptApiToken);
} catch (Exception e) {
throw new IllegalStateException("Invalid socket file path: " + socketFilePath, e);
}
}
public static void main(String[] args) throws IOException {
ServerConfig serverConfig = parseConfig(args);
// Delete the socket file if it already exists
Files.deleteIfExists(serverConfig.socketFile());
// Create the server socket channel and bind it
try (ServerSocketChannel serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(serverConfig.socketFile());
serverChannel.bind(address);
System.out.println("Server listening on " + serverConfig.socketFile());
ChatGptClient gpt = new ChatGptClient(serverConfig.apiKey());
// Server loop
while (true) {
// Accept an incoming connection
try (SocketChannel socketChannel = serverChannel.accept()) {
System.out.println("Accepted a connection from " + socketChannel.getRemoteAddress());
// Read the length of the incoming message
ByteBuffer inputLengthBuffer = ByteBuffer.allocate(4);
socketChannel.read(inputLengthBuffer);
inputLengthBuffer.flip();
int length = inputLengthBuffer.getInt();
System.out.println("Incoming message length: " + length);
// Allocate a buffer of the specified size to store the incoming message
ByteBuffer messageBuffer = ByteBuffer.allocate(length);
socketChannel.read(messageBuffer);
messageBuffer.flip();
// Convert the ByteBuffer to a String that contains our JSON message
String jsonMessage = new String(messageBuffer.array());
System.out.println("Incoming message: " + jsonMessage);
| Type listType = new TypeToken<List<ChatCompletionRequestMessage>>() {}.getType(); | 0 | 2023-12-18 22:47:47+00:00 | 4k |
TerronesDiaz/easyOnlineShopApiRest | src/main/java/com/example/easyOnlineShop/easyOnlineShop/Service/impl/ProductIMPL.java | [
{
"identifier": "ProductDTO",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Dto/ProductDTO.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ProductDTO {\n\n private long productId;\n private String productName;\n private String produc... | import com.example.easyOnlineShop.easyOnlineShop.Dto.ProductDTO;
import com.example.easyOnlineShop.easyOnlineShop.Entity.DigitalProduct;
import com.example.easyOnlineShop.easyOnlineShop.Entity.PhysicalProduct;
import com.example.easyOnlineShop.easyOnlineShop.Entity.Product;
import com.example.easyOnlineShop.easyOnlineShop.Entity.ProductImage;
import com.example.easyOnlineShop.easyOnlineShop.Enums.ProductStatus;
import com.example.easyOnlineShop.easyOnlineShop.Repo.ProductImageRepository;
import com.example.easyOnlineShop.easyOnlineShop.Repo.ProductRepository;
import com.example.easyOnlineShop.easyOnlineShop.Service.ProductService;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 1,622 | package com.example.easyOnlineShop.easyOnlineShop.Service.impl;
@Service
@Transactional
public class ProductIMPL implements ProductService {
private final ProductRepository productRepository;
private final ProductImageRepository productImageRepository;
@Autowired
public ProductIMPL(ProductRepository productRepository, ProductImageRepository productImageRepository) {
this.productRepository = productRepository;
this.productImageRepository = productImageRepository;
}
@Override
public List<ProductDTO> findAllProducts() {
// Retrieve all products from the repository and map them to DTOs
return productRepository.findAll().stream()
.map(this::entityToDto)
.collect(Collectors.toList());
}
@Override
public String deleteProductById(Long productId){
if (productId <= 0){
throw new IllegalArgumentException("A valid ID for the product was not provided");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
if(optionalProduct.isPresent()){
Product existingProduct = optionalProduct.get();
existingProduct.setProductStatus(String.valueOf(ProductStatus.DELETED)); // Establecer el estado directamente como enum
productRepository.save(existingProduct); // Guardar el cambio en la base de datos
return "Product successfully marked as deleted";
} else {
return "Product not found";
}
}
// Helper method to convert an entity to a DTO
private ProductDTO entityToDto(Product entity) {
ProductDTO dto = new ProductDTO();
dto.setProductId(entity.getProductId());
dto.setProductName(entity.getProductName());
dto.setProductStatus(ProductStatus.valueOf(entity.getProductStatus()));
if (entity instanceof DigitalProduct) {
dto.setProductType("Digital Product");
} else if (entity instanceof PhysicalProduct) {
dto.setProductType("Physical Product");
}
if (entity.getProductImages() != null) {
// Map image IDs if present
List<Long> imageIds = entity.getProductImages().stream() | package com.example.easyOnlineShop.easyOnlineShop.Service.impl;
@Service
@Transactional
public class ProductIMPL implements ProductService {
private final ProductRepository productRepository;
private final ProductImageRepository productImageRepository;
@Autowired
public ProductIMPL(ProductRepository productRepository, ProductImageRepository productImageRepository) {
this.productRepository = productRepository;
this.productImageRepository = productImageRepository;
}
@Override
public List<ProductDTO> findAllProducts() {
// Retrieve all products from the repository and map them to DTOs
return productRepository.findAll().stream()
.map(this::entityToDto)
.collect(Collectors.toList());
}
@Override
public String deleteProductById(Long productId){
if (productId <= 0){
throw new IllegalArgumentException("A valid ID for the product was not provided");
}
Optional<Product> optionalProduct = productRepository.findById(productId);
if(optionalProduct.isPresent()){
Product existingProduct = optionalProduct.get();
existingProduct.setProductStatus(String.valueOf(ProductStatus.DELETED)); // Establecer el estado directamente como enum
productRepository.save(existingProduct); // Guardar el cambio en la base de datos
return "Product successfully marked as deleted";
} else {
return "Product not found";
}
}
// Helper method to convert an entity to a DTO
private ProductDTO entityToDto(Product entity) {
ProductDTO dto = new ProductDTO();
dto.setProductId(entity.getProductId());
dto.setProductName(entity.getProductName());
dto.setProductStatus(ProductStatus.valueOf(entity.getProductStatus()));
if (entity instanceof DigitalProduct) {
dto.setProductType("Digital Product");
} else if (entity instanceof PhysicalProduct) {
dto.setProductType("Physical Product");
}
if (entity.getProductImages() != null) {
// Map image IDs if present
List<Long> imageIds = entity.getProductImages().stream() | .map(ProductImage::getImageId) | 4 | 2023-12-21 20:13:34+00:00 | 4k |
kavindumal/layered-architecture-kavindu-malshan-jayasinghe | src/main/java/com/example/layeredarchitecture/controller/ManageItemsFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private BOFactory(){}\n\n private static BOFactory boFactory;\n\n public static BOFactory getBOFactory() {\n return (boFactory == null) ? boFacto... | import com.example.layeredarchitecture.bo.BOFactory;
import com.example.layeredarchitecture.bo.ItemBO;
import com.example.layeredarchitecture.bo.ItemBOImpl;
import com.example.layeredarchitecture.dao.custom.impl.ItemDAOImpl;
import com.example.layeredarchitecture.model.ItemDTO;
import com.example.layeredarchitecture.view.tdm.ItemTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList; | 2,220 | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem; | package com.example.layeredarchitecture.controller;
public class ManageItemsFormController {
public AnchorPane root;
public TextField txtCode;
public TextField txtDescription;
public TextField txtQtyOnHand;
public JFXButton btnDelete;
public JFXButton btnSave;
public TableView<ItemTM> tblItems;
public TextField txtUnitPrice;
public JFXButton btnAddNewItem; | ItemBO itemBO = (ItemBO) BOFactory.getBOFactory().getBO(BOFactory.BOType.ITEM); | 1 | 2023-12-16 04:16:50+00:00 | 4k |
chulakasam/layered | src/main/java/com/example/layeredarchitecture/controller/SearchController.java | [
{
"identifier": "CustomerDAO",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/CustomerDAO.java",
"snippet": "public interface CustomerDAO extends CrudDAO<CustomerDTO> {\n /* ArrayList<CustomerDTO> getAll() throws SQLException, ClassNotFoundException ;\n boolean SaveCustomer(Str... | import com.example.layeredarchitecture.dao.custom.CustomerDAO;
import com.example.layeredarchitecture.dao.custom.Impl.CustomerDAOImpl;
import com.example.layeredarchitecture.dao.custom.Impl.QueryDAOImpl;
import com.example.layeredarchitecture.dao.custom.QueryDAO;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.model.SearchDto;
import com.example.layeredarchitecture.model.TableDTO;
import com.example.layeredarchitecture.view.tdm.TableTM;
import com.jfoenix.controls.JFXComboBox;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList; | 3,598 | package com.example.layeredarchitecture.controller;
public class SearchController {
public AnchorPane root;
public TableColumn colCode;
public TableColumn colQty;
public TableColumn colUnitPrice;
public JFXComboBox cmbcusId;
public Label lblName;
public Label lblDate;
public JFXComboBox cmbOrderId;
public JFXComboBox cmbCode;
public TableView <TableTM> tblOrderDetail;
public TableColumn colDesc;
QueryDAO queryDAO=new QueryDAOImpl();
CustomerDAO customerDAO=new CustomerDAOImpl();
public void btnBackToHome(ActionEvent actionEvent) throws IOException {
URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml");
Parent root = FXMLLoader.load(resource);
Scene scene = new Scene(root);
Stage primaryStage = (Stage) (this.root.getScene().getWindow());
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
Platform.runLater(() -> primaryStage.sizeToScene());
}
private void loadallcustomerIds() {
try {
ArrayList<CustomerDTO> allCustomers = customerDAO.getAll();
for (CustomerDTO c : allCustomers) {
cmbcusId.getItems().add(c.getId());
}
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void initialize(){
loadallcustomerIds();
}
public void cusIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbcusId.getValue();
cmbOrderId.getItems().clear();
try {
ArrayList<SearchDto> dtolist = queryDAO.search(id);
for (SearchDto c : dtolist) {
cmbOrderId.getItems().add(c.getOid());
lblName.setText(c.getName());
lblDate.setText(c.getDate());
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public void orderIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbOrderId.getValue();
try {
tblOrderDetail.getItems().clear(); | package com.example.layeredarchitecture.controller;
public class SearchController {
public AnchorPane root;
public TableColumn colCode;
public TableColumn colQty;
public TableColumn colUnitPrice;
public JFXComboBox cmbcusId;
public Label lblName;
public Label lblDate;
public JFXComboBox cmbOrderId;
public JFXComboBox cmbCode;
public TableView <TableTM> tblOrderDetail;
public TableColumn colDesc;
QueryDAO queryDAO=new QueryDAOImpl();
CustomerDAO customerDAO=new CustomerDAOImpl();
public void btnBackToHome(ActionEvent actionEvent) throws IOException {
URL resource = this.getClass().getResource("/com/example/layeredarchitecture/main-form.fxml");
Parent root = FXMLLoader.load(resource);
Scene scene = new Scene(root);
Stage primaryStage = (Stage) (this.root.getScene().getWindow());
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
Platform.runLater(() -> primaryStage.sizeToScene());
}
private void loadallcustomerIds() {
try {
ArrayList<CustomerDTO> allCustomers = customerDAO.getAll();
for (CustomerDTO c : allCustomers) {
cmbcusId.getItems().add(c.getId());
}
} catch (SQLException e) {
new Alert(Alert.AlertType.ERROR, "Failed to load customer ids").show();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void initialize(){
loadallcustomerIds();
}
public void cusIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbcusId.getValue();
cmbOrderId.getItems().clear();
try {
ArrayList<SearchDto> dtolist = queryDAO.search(id);
for (SearchDto c : dtolist) {
cmbOrderId.getItems().add(c.getOid());
lblName.setText(c.getName());
lblDate.setText(c.getDate());
}
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public void orderIdOnAction(ActionEvent actionEvent) {
String id = (String) cmbOrderId.getValue();
try {
tblOrderDetail.getItems().clear(); | ArrayList<TableDTO> details = queryDAO.LoadToTable(id); | 6 | 2023-12-15 04:45:10+00:00 | 4k |
pan2013e/ppt4j | framework/src/main/java/ppt4j/analysis/patch/CrossMatcher.java | [
{
"identifier": "Extractor",
"path": "framework/src/main/java/ppt4j/feature/Extractor.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface Extractor extends Serializable {\n\n void parse();\n\n default void print() {\n getFeaturesMap().values().forEach(System.out::println);\n ... | import ppt4j.feature.Extractor;
import ppt4j.feature.Features;
import ppt4j.feature.bytecode.BytecodeExtractor;
import ppt4j.feature.java.JavaExtractor;
import org.apache.commons.lang3.tuple.Pair;
import static ppt4j.feature.Features.SourceType; | 3,466 | package ppt4j.analysis.patch;
@SuppressWarnings("unused")
public interface CrossMatcher {
SourceType getKeyType();
SourceType getValueType();
boolean isMatched(int index);
double getScore(int index);
Pair<Integer, Integer> getMatchedRange(int index);
Features query(int index);
| package ppt4j.analysis.patch;
@SuppressWarnings("unused")
public interface CrossMatcher {
SourceType getKeyType();
SourceType getValueType();
boolean isMatched(int index);
double getScore(int index);
Pair<Integer, Integer> getMatchedRange(int index);
Features query(int index);
| static CrossMatcher get(JavaExtractor k, Extractor v, boolean diffType) { | 3 | 2023-12-14 15:33:50+00:00 | 4k |
iagolirapasssos/chatGPTAndDallE | chatgpt/ChatGPT.java | [
{
"identifier": "DallEModel",
"path": "chatgpt/helpers/DallEModel.java",
"snippet": "public enum DallEModel implements OptionList<String> {\n DALL_E_2(\"dall-e-2\"),\n DALL_E_3(\"dall-e-3\");\n\n private String model;\n\n DallEModel(String model) {\n this.model = model;\n }\n\n ... | import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.common.*;
import com.google.appinventor.components.common.OptionList;
import com.google.appinventor.components.runtime.util.YailList;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.annotations.SimpleEvent;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import org.json.JSONException;
import org.json.JSONObject;
import com.bosonshiggs.chatgpt.helpers.DallEModel;
import com.bosonshiggs.chatgpt.helpers.ImageSize;
import com.bosonshiggs.chatgpt.helpers.VoiceModel;
import com.bosonshiggs.chatgpt.helpers.AudioQuality;
import com.bosonshiggs.chatgpt.helpers.AudioFormats;
import android.os.Environment;
import android.media.MediaScannerConnection;
import android.util.Log;
import android.app.AlertDialog;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.view.ViewGroup;
import android.graphics.drawable.ColorDrawable;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.SeekBar;
import android.os.Handler; | 3,389 |
// Configuração de layout para o EditText
if (isFullScreen) {
builder.setView(input);
} else {
int margin = 30; // Margem em pixels (ajuste conforme necessário)
FrameLayout frameLayout = new FrameLayout(container.$context());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(margin, margin, margin, margin);
input.setLayoutParams(params);
frameLayout.addView(input);
builder.setView(frameLayout);
}
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botões ao diálogo
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
if (showOkButton) {
dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String enteredText = input.getText().toString();
TextEntered(enteredText, type);
}
});
}
// Configurar cor de fundo do diálogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diálogo
dialog.show();
}
@SimpleFunction(description = "Shows a dialog with a list of items.")
public void ShowListDialog(
String title,
YailList items,
final int textColor,
final int listItemBackgroundColor,
final int dialogBackgroundColor,
final boolean isFullScreen,
final boolean showCancelButton,
final String type
) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
builder.setTitle(title);
// Converte YailList para array de Strings
final String[] itemsArray = items.toStringArray();
// Criar ArrayAdapter personalizado
ArrayAdapter<String> adapter = new ArrayAdapter<String>(container.$context(), android.R.layout.simple_list_item_1, itemsArray) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView item = (TextView) super.getView(position, convertView, parent);
item.setTextColor(textColor); // Define a cor do texto
item.setBackgroundColor(listItemBackgroundColor); // Define a cor de fundo
return item;
}
};
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = itemsArray[which];
ListItemSelected(selectedItem, type);
}
});
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botão de cancelamento, se necessário
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
// Configurar cor de fundo do diálogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
if (isFullScreen) {
// Aplica a cor de fundo para o modo tela cheia
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diálogo
dialog.show();
}
@SimpleFunction(description = "Generate speech from text")
public void GenerateSpeech(
final String prompt,
final String apiKey,
final String audioName,
final String directoryName, | /*
* ChatGPT
* Extension to use OpenAI's ChatGPT API
* Version: 1.0
* Author: Francisco Iago Lira Passos
* Date: 2023-10-15
*/
package com.bosonshiggs.chatgpt;
//Auxiliar methods Dialogs
@DesignerComponent(version = 6, // Update version here, You must do for each new release to upgrade your extension
description = "Extension to use Openai's API",
category = ComponentCategory.EXTENSION,
nonVisible = true,
iconName = "images/extension.png") // Change your extension's icon from here; can be a direct url
@SimpleObject(external = true)
public class ChatGPT extends AndroidNonvisibleComponent {
private String LOG_NAME = "ChatGPT";
private boolean flagLog = false;
private ComponentContainer container;
public ChatGPT(ComponentContainer container) {
super(container.$form());
this.container = container;
}
@SimpleFunction(description = "Extract Value from JSON Text")
public String jsonDecode(final String jsonText, final String key) {
try {
// Converter o JSON em um objeto JSON
JSONObject jsonObject = new JSONObject(jsonText);
// Use a função auxiliar para buscar o valor da chave no objeto JSON
String value = findValueForKey(jsonObject, key);
if (value != null) {
return value;
} else {
return "Error! Key not found!";
}
} catch (JSONException e) {
ReportError(e.getMessage());
return "Error: " + e.getMessage();
}
}
@SimpleFunction(description = "Send a prompt to ChatGPT")
public void SendPrompt(final String prompt, final String model, final String systemMsg, final float temperature, final String apiKey) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendRequest(prompt, model, systemMsg, temperature, apiKey);
if (responseText != null) {
ResponseReceived(responseText);
} else {
ReportError("None");
}
}
}).start();
}
@SimpleFunction(description = "Generate an image based on a prompt")
public void GenerateImage(
String prompt,
int numberOfImages,
String apiKey,
@Options(DallEModel.class) String model,
@Options(ImageSize.class) String size
)
{
/*
DallEModel model = DallEModel.fromUnderlyingValue(dalleModel);
ImageSize size = ImageSize.fromUnderlyingValue(imageSize);
*/
if (flagLog) Log.i(LOG_NAME, "GenerateImage - model: " + model);
if (flagLog) Log.i(LOG_NAME, "GenerateImage - size: " + size);
if (model == "dall-e-3") {
if (numberOfImages > 1 || numberOfImages < 1) numberOfImages = 1;
} else if (model == "dall-e-2") {
if (numberOfImages > 10 || numberOfImages < 1) numberOfImages = 1;
}
final ArrayList<String[]> headHTTP = new ArrayList<>();
headHTTP.add(new String[]{"Content-Type", "application/json"});
headHTTP.add(new String[]{"Authorization", "Bearer " + apiKey});
final String url = "https://api.openai.com/v1/images/generations";
final String payload = "{\n"
+ " \"model\": \"" + model + "\",\n"
+ " \"prompt\": \"" + prompt + "\",\n"
+ " \"n\": " + numberOfImages + ",\n"
+ " \"size\": \"" + size + "\"\n"
+ "}";
if (flagLog) Log.i(LOG_NAME, "GenerateImage - payload: " + payload);
if (flagLog) Log.i(LOG_NAME, "GenerateImage - headHTTP: " + headHTTP);
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendImageGenerationRequest(url, payload, headHTTP);
if (responseText != null) {
ImageGenerationCompleted(responseText);
} else {
ReportError("None");
}
}
}).start();
}
@SimpleFunction(description = "Create a thread")
public void CreateThread(final String apiKey) {
new Thread(new Runnable() {
@Override
public void run() {
if (flagLog) Log.i(LOG_NAME, "CreateThread - apiKey: " + apiKey);
try {
String responseText = sendThreadRequest("POST", "https://api.openai.com/v1/threads", apiKey, "");
if (responseText != null) {
ThreadCreated(responseText);
} else {
ReportError("None");
}
} catch (Exception e) {
if (flagLog) Log.e(LOG_NAME, "Error: " + e.getMessage(), e);
ReportError("Error: " + e.getMessage());
}
}
}).start();
}
// Método para recuperar uma thread
@SimpleFunction(description = "Retrieve a thread")
public void RetrieveThread(final String apiKey, final String threadId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadRequest("GET", "https://api.openai.com/v1/threads/" + threadId, apiKey, "");
if (responseText != null) {
ThreadRetrieved(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Método para modificar uma thread
@SimpleFunction(description = "Modify a thread")
public void ModifyThread(final String apiKey, final String threadId, final String metadata) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadRequest("POST", "https://api.openai.com/v1/threads/" + threadId, apiKey, metadata);
if (responseText != null) {
ThreadModified(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Método para excluir uma thread
@SimpleFunction(description = "Delete a thread")
public void DeleteThread(final String apiKey, final String threadId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadRequest("DELETE", "https://api.openai.com/v1/threads/" + threadId, apiKey, "");
if (responseText != null) {
ThreadDeleted(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Método para criar uma mensagem em uma thread
@SimpleFunction(description = "Create a message in a thread")
public void CreateMessage(final String apiKey, final String threadId, final String messageContent) {
new Thread(new Runnable() {
@Override
public void run() {
String payload = "{\n" +
" \"role\": \"user\",\n" +
" \"content\": \"" + messageContent + "\"\n" +
"}";
String responseText = sendThreadMessageRequest("POST", "https://api.openai.com/v1/threads/" + threadId + "/messages", apiKey, payload);
if (responseText != null) {
MessageCreated(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Método para recuperar uma mensagem em uma thread
@SimpleFunction(description = "Retrieve a message in a thread")
public void RetrieveMessage(final String apiKey, final String threadId, final String messageId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadMessageRequest("GET", "https://api.openai.com/v1/threads/" + threadId + "/messages/" + messageId, apiKey, "");
if (responseText != null) {
MessageRetrieved(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Método para modificar uma mensagem em uma thread
@SimpleFunction(description = "Modify a message in a thread")
public void ModifyMessage(final String apiKey, final String threadId, final String messageId, final String metadata) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadMessageRequest("POST", "https://api.openai.com/v1/threads/" + threadId + "/messages/" + messageId, apiKey, metadata);
if (responseText != null) {
MessageModified(responseText);
} else {
ReportError("None");
}
}
}).start();
}
// Método para listar mensagens em uma thread
@SimpleFunction(description = "List messages in a thread")
public void ListMessages(final String apiKey, final String threadId) {
new Thread(new Runnable() {
@Override
public void run() {
String responseText = sendThreadMessageRequest("GET", "https://api.openai.com/v1/threads/" + threadId + "/messages", apiKey, "");
if (responseText != null) {
MessagesListed(responseText);
} else {
ReportError("None");
}
}
}).start();
}
/*
* AUXILIAR METHODS
*/
// Método para mostrar um diálogo de reprodução de áudio
@SimpleFunction(description = "Show a dialog with a native audio player.")
public void ShowNativeAudioPlayerDialog(
String title,
final String audioFilePath,
final int titleColor,
final int titleBackgroundColor,
final int dialogBackgroundColor) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
builder.setTitle(title);
// Criar MediaPlayer
final MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(audioFilePath);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
ReportError("Error preparing MediaPlayer: " + e.getMessage());
return;
}
// Criar layout para adicionar os controles
LinearLayout layout = new LinearLayout(container.$context());
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// Barra de tempo
final SeekBar seekBar = new SeekBar(container.$context());
seekBar.setMax(mediaPlayer.getDuration());
layout.addView(seekBar);
// Atualizar SeekBar com o progresso do MediaPlayer
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
if (mediaPlayer != null) {
int currentPosition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentPosition);
}
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 0);
// Botões de controle
Button playButton = new Button(container.$context());
playButton.setText("Play");
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.start();
}
});
Button pauseButton = new Button(container.$context());
pauseButton.setText("Pause");
pauseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.pause();
}
});
layout.addView(playButton);
layout.addView(pauseButton);
builder.setView(layout);
// Adicionar botão de fechar
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
handler.removeCallbacks(runnable); // Parar atualização da SeekBar
dialog.dismiss();
}
});
// Criar o AlertDialog
final AlertDialog dialog = builder.create();
// Configurar cores
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
TextView titleView = dialog.findViewById(android.R.id.title);
if (titleView != null) {
titleView.setTextColor(titleColor);
}
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(titleBackgroundColor));
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
dialog.show();
}
@SimpleFunction(description = "Shows a dialog with a text input.")
public void ShowTextInputDialog(
String title,
String message,
int textColor,
int editTextBackgroundColor,
final int dialogBackgroundColor,
String hint,
String defaultText,
boolean isFullScreen,
boolean showCancelButton,
boolean showOkButton,
final String type
)
{
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
// Define o título e a mensagem do diálogo
builder.setTitle(title);
builder.setMessage(message);
// Cria o EditText para entrada de texto
final EditText input = new EditText(container.$context());
input.setTextColor(textColor);
input.setBackgroundColor(editTextBackgroundColor);
input.setHint(hint);
input.setText(defaultText);
// Configuração de layout para o EditText
if (isFullScreen) {
builder.setView(input);
} else {
int margin = 30; // Margem em pixels (ajuste conforme necessário)
FrameLayout frameLayout = new FrameLayout(container.$context());
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(margin, margin, margin, margin);
input.setLayoutParams(params);
frameLayout.addView(input);
builder.setView(frameLayout);
}
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botões ao diálogo
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
if (showOkButton) {
dialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String enteredText = input.getText().toString();
TextEntered(enteredText, type);
}
});
}
// Configurar cor de fundo do diálogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diálogo
dialog.show();
}
@SimpleFunction(description = "Shows a dialog with a list of items.")
public void ShowListDialog(
String title,
YailList items,
final int textColor,
final int listItemBackgroundColor,
final int dialogBackgroundColor,
final boolean isFullScreen,
final boolean showCancelButton,
final String type
) {
AlertDialog.Builder builder = new AlertDialog.Builder(container.$context());
builder.setTitle(title);
// Converte YailList para array de Strings
final String[] itemsArray = items.toStringArray();
// Criar ArrayAdapter personalizado
ArrayAdapter<String> adapter = new ArrayAdapter<String>(container.$context(), android.R.layout.simple_list_item_1, itemsArray) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView item = (TextView) super.getView(position, convertView, parent);
item.setTextColor(textColor); // Define a cor do texto
item.setBackgroundColor(listItemBackgroundColor); // Define a cor de fundo
return item;
}
};
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = itemsArray[which];
ListItemSelected(selectedItem, type);
}
});
// Cria o AlertDialog
final AlertDialog dialog = builder.create();
// Adiciona botão de cancelamento, se necessário
if (showCancelButton) {
dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
// Configurar cor de fundo do diálogo
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
if (isFullScreen) {
// Aplica a cor de fundo para o modo tela cheia
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(dialogBackgroundColor));
}
});
// Mostrar o diálogo
dialog.show();
}
@SimpleFunction(description = "Generate speech from text")
public void GenerateSpeech(
final String prompt,
final String apiKey,
final String audioName,
final String directoryName, | final @Options(VoiceModel.class) String voice, | 2 | 2023-12-14 15:07:14+00:00 | 4k |
MalithShehan/layered-architecture-Malith-Shehan | src/main/java/lk/ijse/layeredarchitecture/bo/BOFactory.java | [
{
"identifier": "CustomerBOImpl",
"path": "src/main/java/lk/ijse/layeredarchitecture/bo/custom/impl/CustomerBOImpl.java",
"snippet": "public class CustomerBOImpl implements CustomerBO {\n CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDaoFactory().getDAO(DAOFactory.DAOTypes.CUSTOMER);\n pub... | import com.example.layeredarchitecture.bo.custom.impl.CustomerBOImpl;
import com.example.layeredarchitecture.bo.custom.impl.ItemBOImpl;
import com.example.layeredarchitecture.bo.custom.impl.PlaceOrderBOImpl; | 2,070 | package com.example.layeredarchitecture.bo;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory == null) ? boFactory = new BOFactory() : boFactory;
}
public enum BOTypes{
CUSTOMER, ITEM, PLACE_ORDER
}
public SuperBO getBO(BOTypes boTypes) {
switch (boTypes) {
case CUSTOMER:
return new CustomerBOImpl();
case ITEM: | package com.example.layeredarchitecture.bo;
public class BOFactory {
private static BOFactory boFactory;
private BOFactory(){
}
public static BOFactory getBoFactory(){
return (boFactory == null) ? boFactory = new BOFactory() : boFactory;
}
public enum BOTypes{
CUSTOMER, ITEM, PLACE_ORDER
}
public SuperBO getBO(BOTypes boTypes) {
switch (boTypes) {
case CUSTOMER:
return new CustomerBOImpl();
case ITEM: | return new ItemBOImpl(); | 1 | 2023-12-16 04:19:09+00:00 | 4k |
f1den/MrCrayfishGunMod | src/main/java/com/mrcrayfish/guns/client/GunEntityRenderers.java | [
{
"identifier": "Reference",
"path": "src/main/java/com/mrcrayfish/guns/Reference.java",
"snippet": "public class Reference\n{\n\tpublic static final String MOD_ID = \"cgm\";\n}"
},
{
"identifier": "GrenadeRenderer",
"path": "src/main/java/com/mrcrayfish/guns/client/render/entity/GrenadeRend... | import com.mrcrayfish.guns.Reference;
import com.mrcrayfish.guns.client.render.entity.GrenadeRenderer;
import com.mrcrayfish.guns.client.render.entity.MissileRenderer;
import com.mrcrayfish.guns.client.render.entity.ProjectileRenderer;
import com.mrcrayfish.guns.client.render.entity.ThrowableGrenadeRenderer;
import com.mrcrayfish.guns.init.ModEntities;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.EntityRenderersEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod; | 2,454 | package com.mrcrayfish.guns.client;
/**
* Author: MrCrayfish
*/
@Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class GunEntityRenderers
{
@SubscribeEvent
public static void registerEntityRenders(EntityRenderersEvent.RegisterRenderers event)
{ | package com.mrcrayfish.guns.client;
/**
* Author: MrCrayfish
*/
@Mod.EventBusSubscriber(modid = Reference.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class GunEntityRenderers
{
@SubscribeEvent
public static void registerEntityRenders(EntityRenderersEvent.RegisterRenderers event)
{ | event.registerEntityRenderer(ModEntities.PROJECTILE.get(), ProjectileRenderer::new); | 5 | 2023-12-18 15:04:35+00:00 | 4k |
JenningsCrane/JDBC-Simple-Chat | Chat/src/main/java/edu/school21/chat/models/Repository/MessageRepositoryJdbcImpl.java | [
{
"identifier": "Chatroom",
"path": "Chat/src/main/java/edu/school21/chat/models/Chat/Chatroom.java",
"snippet": "public class Chatroom {\n private Long chatRoomId;\n private String chatRoomName;\n private User chatRoomOwner;\n private List<Message> chatRoomMessages;\n\n public Chatroom(L... | import edu.school21.chat.models.Chat.Chatroom;
import edu.school21.chat.models.Chat.Message;
import edu.school21.chat.models.Chat.User;
import edu.school21.chat.models.Exception.NotSavedSubEntityException;
import javax.sql.DataSource;
import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Optional; | 1,971 | package edu.school21.chat.models.Repository;
public class MessageRepositoryJdbcImpl implements MessageRepository {
private static Connection connection;
public MessageRepositoryJdbcImpl(DataSource dataSource) throws SQLException {
MessageRepositoryJdbcImpl.connection = dataSource.getConnection();
}
@Override
public Optional<Message> findById(Long id) throws SQLException {
try(PreparedStatement userStatement = connection.prepareStatement("SELECT * FROM chat.message WHERE messageid = " + id);
ResultSet resultSet = userStatement.executeQuery()) {
resultSet.next();
LocalDateTime date = null;
if(resultSet.getTimestamp(5) != null) {
date = resultSet.getTimestamp(5).toLocalDateTime();
}
System.out.println("Message : {\n" +
" id=" + resultSet.getInt(1) + ",\n" +
" " + findUserById(resultSet.getLong(2)) + ",\n" +
" " + findRoomById(resultSet.getLong(3)) + ",\n" +
" text=\"" + resultSet.getString(4) + "\",\n" +
" dateTime=" + date + "\n" +
"}");
return Optional.of(new Message(resultSet.getLong(1), findUserById(resultSet.getLong(2)), findRoomById(resultSet.getLong(3)),
resultSet.getString(4), date));
} catch (SQLException sqlException) {
throw new SQLException(sqlException);
}
}
| package edu.school21.chat.models.Repository;
public class MessageRepositoryJdbcImpl implements MessageRepository {
private static Connection connection;
public MessageRepositoryJdbcImpl(DataSource dataSource) throws SQLException {
MessageRepositoryJdbcImpl.connection = dataSource.getConnection();
}
@Override
public Optional<Message> findById(Long id) throws SQLException {
try(PreparedStatement userStatement = connection.prepareStatement("SELECT * FROM chat.message WHERE messageid = " + id);
ResultSet resultSet = userStatement.executeQuery()) {
resultSet.next();
LocalDateTime date = null;
if(resultSet.getTimestamp(5) != null) {
date = resultSet.getTimestamp(5).toLocalDateTime();
}
System.out.println("Message : {\n" +
" id=" + resultSet.getInt(1) + ",\n" +
" " + findUserById(resultSet.getLong(2)) + ",\n" +
" " + findRoomById(resultSet.getLong(3)) + ",\n" +
" text=\"" + resultSet.getString(4) + "\",\n" +
" dateTime=" + date + "\n" +
"}");
return Optional.of(new Message(resultSet.getLong(1), findUserById(resultSet.getLong(2)), findRoomById(resultSet.getLong(3)),
resultSet.getString(4), date));
} catch (SQLException sqlException) {
throw new SQLException(sqlException);
}
}
| private User findUserById(Long id) throws SQLException { | 2 | 2023-12-17 05:34:09+00:00 | 4k |
Qzimyion/BucketEm | src/main/java/com/qzimyion/bucketem/Bucketem.java | [
{
"identifier": "DispenserBehaviorRegistry",
"path": "src/main/java/com/qzimyion/bucketem/dispenser/DispenserBehaviorRegistry.java",
"snippet": "public class DispenserBehaviorRegistry {\n\n public static void registerDispenserBehavior(){\n //Buckets\n DispenserBlock.registerBehavior(STR... | import com.qzimyion.bucketem.dispenser.DispenserBehaviorRegistry;
import com.qzimyion.bucketem.items.ModItemGroups;
import com.qzimyion.bucketem.items.ModItems;
import com.qzimyion.bucketem.potions.ModPotionsRegistry;
import com.qzimyion.bucketem.potions.StatusEffects.ModStatusEffectsRegistry;
import net.fabricmc.api.ModInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 2,240 | package com.qzimyion.bucketem;
public class Bucketem implements ModInitializer {
public static final String MOD_ID = "bucketem";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItems.registerItems();
ModItemGroups.registerItemGroups();
ModEvents.registerEvents();
DispenserBehaviorRegistry.registerDispenserBehavior();
ModStatusEffectsRegistry.registerStatusEffects(); | package com.qzimyion.bucketem;
public class Bucketem implements ModInitializer {
public static final String MOD_ID = "bucketem";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItems.registerItems();
ModItemGroups.registerItemGroups();
ModEvents.registerEvents();
DispenserBehaviorRegistry.registerDispenserBehavior();
ModStatusEffectsRegistry.registerStatusEffects(); | ModPotionsRegistry.registerPotions(); | 3 | 2023-12-16 08:12:37+00:00 | 4k |
devOS-Sanity-Edition/blocky-bass | src/main/java/one/devos/nautical/blocky_bass/BlockyBassClient.java | [
{
"identifier": "BlockyBassBlockEntityRenderer",
"path": "src/main/java/one/devos/nautical/blocky_bass/block/BlockyBassBlockEntityRenderer.java",
"snippet": "public class BlockyBassBlockEntityRenderer implements BlockEntityRenderer<BlockyBassBlockEntity> {\n\tprivate final BlockyBassModel model;\n\n\tpu... | import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.rendering.v1.EntityModelLayerRegistry;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import one.devos.nautical.blocky_bass.block.BlockyBassBlockEntityRenderer;
import one.devos.nautical.blocky_bass.block.BlockyBassModel; | 1,953 | package one.devos.nautical.blocky_bass;
public class BlockyBassClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
BlockEntityRenderers.register(BlockyBass.BLOCK_ENTITY, BlockyBassBlockEntityRenderer::new); | package one.devos.nautical.blocky_bass;
public class BlockyBassClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
BlockEntityRenderers.register(BlockyBass.BLOCK_ENTITY, BlockyBassBlockEntityRenderer::new); | EntityModelLayerRegistry.registerModelLayer(BlockyBassModel.LAYER_LOCATION, BlockyBassModel::createBodyLayer); | 1 | 2023-12-18 05:18:17+00:00 | 4k |
lpyleo/disk-back-end | file-web/src/main/java/com/disk/file/controller/DeptFiletransferController.java | [
{
"identifier": "RestResult",
"path": "file-web/src/main/java/com/disk/file/common/RestResult.java",
"snippet": "@Data\npublic class RestResult<T> {\n private Boolean success = true;\n private Integer code;\n private String message;\n private T data;\n\n // 自定义返回数据\n public RestResult ... | import com.disk.file.common.RestResult;
import com.disk.file.dto.DownloadDeptFileDTO;
import com.disk.file.dto.DownloadFileDTO;
import com.disk.file.dto.UploadFileDTO;
import com.disk.file.model.*;
import com.disk.file.service.*;
import com.disk.file.util.DateUtil;
import com.disk.file.util.FileUtil;
import com.disk.file.vo.UploadFileVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 1,895 | package com.disk.file.controller;
@Tag(name = "deptfiletransfer", description = "该接口为部门文件传输接口,主要用来做部门文件的上传和下载")
@RestController
@RequestMapping("/deptfiletransfer")
public class DeptFiletransferController {
@Resource
UserService userService;
@Resource
FileService fileService;
@Resource
DepartmentfileService departmentfileService;
@Resource
DeptFiletransferService deptFiletransferService;
@Operation(summary = "极速上传", description = "校验文件MD5判断文件是否存在,如果存在直接上传成功并返回skipUpload=true,如果不存在返回skipUpload=false需要再次调用该接口的POST方法", tags = {"deptfiletransfer"})
@GetMapping(value = "/uploadfile")
@ResponseBody | package com.disk.file.controller;
@Tag(name = "deptfiletransfer", description = "该接口为部门文件传输接口,主要用来做部门文件的上传和下载")
@RestController
@RequestMapping("/deptfiletransfer")
public class DeptFiletransferController {
@Resource
UserService userService;
@Resource
FileService fileService;
@Resource
DepartmentfileService departmentfileService;
@Resource
DeptFiletransferService deptFiletransferService;
@Operation(summary = "极速上传", description = "校验文件MD5判断文件是否存在,如果存在直接上传成功并返回skipUpload=true,如果不存在返回skipUpload=false需要再次调用该接口的POST方法", tags = {"deptfiletransfer"})
@GetMapping(value = "/uploadfile")
@ResponseBody | public RestResult<UploadFileVo> uploadFileSpeed(UploadFileDTO uploadFileDto, @RequestHeader("token") String token) { | 3 | 2023-12-17 05:12:43+00:00 | 4k |
ReChronoRain/HyperCeiler | app/src/main/java/com/sevtinge/hyperceiler/ui/fragment/base/SettingsPreferenceFragment.java | [
{
"identifier": "BaseActivity",
"path": "app/src/main/java/com/sevtinge/hyperceiler/ui/base/BaseActivity.java",
"snippet": "public abstract class BaseActivity extends AppCompatActivity {\n\n protected BaseSettingsProxy mProxy;\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceS... | import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.sevtinge.hyperceiler.ui.base.BaseActivity;
import com.sevtinge.hyperceiler.utils.PrefsUtils; | 2,444 | package com.sevtinge.hyperceiler.ui.fragment.base;
public abstract class SettingsPreferenceFragment extends BasePreferenceFragment {
public String mTitle;
public String mPreferenceKey;
public int mContentResId = 0;
public int mTitleResId = 0;
private boolean mPreferenceHighlighted = false;
private final String SAVE_HIGHLIGHTED_KEY = "android:preference_highlighted";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
highlightPreferenceIfNeeded(mPreferenceKey);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mPreferenceHighlighted = savedInstanceState.getBoolean(SAVE_HIGHLIGHTED_KEY);
}
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
super.onCreatePreferences(bundle, s);
Bundle args = getArguments();
if (args != null) {
mTitle = args.getString(":fragment:show_title");
mTitleResId = args.getInt(":fragment:show_title_resid");
mPreferenceKey = args.getString(":settings:fragment_args_key");
mContentResId = args.getInt("contentResId");
}
if (mTitleResId != 0) setTitle(mTitleResId);
if (!TextUtils.isEmpty(mTitle)) setTitle(mTitle);
mContentResId = mContentResId != 0 ? mContentResId : getContentResId();
if (mContentResId != 0) {
setPreferencesFromResource(mContentResId, s);
initPrefs();
} | package com.sevtinge.hyperceiler.ui.fragment.base;
public abstract class SettingsPreferenceFragment extends BasePreferenceFragment {
public String mTitle;
public String mPreferenceKey;
public int mContentResId = 0;
public int mTitleResId = 0;
private boolean mPreferenceHighlighted = false;
private final String SAVE_HIGHLIGHTED_KEY = "android:preference_highlighted";
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
highlightPreferenceIfNeeded(mPreferenceKey);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mPreferenceHighlighted = savedInstanceState.getBoolean(SAVE_HIGHLIGHTED_KEY);
}
}
@Override
public void onCreatePreferences(Bundle bundle, String s) {
super.onCreatePreferences(bundle, s);
Bundle args = getArguments();
if (args != null) {
mTitle = args.getString(":fragment:show_title");
mTitleResId = args.getInt(":fragment:show_title_resid");
mPreferenceKey = args.getString(":settings:fragment_args_key");
mContentResId = args.getInt("contentResId");
}
if (mTitleResId != 0) setTitle(mTitleResId);
if (!TextUtils.isEmpty(mTitle)) setTitle(mTitle);
mContentResId = mContentResId != 0 ? mContentResId : getContentResId();
if (mContentResId != 0) {
setPreferencesFromResource(mContentResId, s);
initPrefs();
} | ((BaseActivity) getActivity()).setRestartView(addRestartListener()); | 0 | 2023-10-27 17:17:42+00:00 | 4k |
thebatmanfuture/fofa_search | src/main/java/org/fofaviewer/utils/DataUtil.java | [
{
"identifier": "BaseBean",
"path": "src/main/java/org/fofaviewer/bean/BaseBean.java",
"snippet": "public class BaseBean {\n}"
},
{
"identifier": "ExcelBean",
"path": "src/main/java/org/fofaviewer/bean/ExcelBean.java",
"snippet": "@Getter\n@Setter\n@EqualsAndHashCode\npublic class ExcelB... | import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Platform;
import javafx.scene.control.*;
import org.fofaviewer.bean.BaseBean;
import org.fofaviewer.bean.ExcelBean;
import org.fofaviewer.bean.TabDataBean;
import org.fofaviewer.bean.TableBean;
import org.fofaviewer.controls.SetConfiDialog;
import org.fofaviewer.main.FofaConfig;
import org.fofaviewer.main.ProxyConfig;
import org.tinylog.Logger;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 3,329 | package org.fofaviewer.utils;
public class DataUtil {
private static final RequestUtil helper = RequestUtil.getInstance();
private static final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private static final Pattern portPattern1 = Pattern.compile(":443$");
private static final Pattern portPattern2 = Pattern.compile(":80$");
/**
* 对话框配置
* @param type dialog type
* @param header dialog title
* @param content content of dialog
*/
public static Alert showAlert(Alert.AlertType type, String header, String content){
Alert alert = new Alert(type);
alert.setTitle("提示");
alert.setHeaderText(header);
alert.setContentText(content);
return alert;
}
| package org.fofaviewer.utils;
public class DataUtil {
private static final RequestUtil helper = RequestUtil.getInstance();
private static final ResourceBundle resourceBundle = ResourceBundleUtil.getResource();
private static final Pattern portPattern1 = Pattern.compile(":443$");
private static final Pattern portPattern2 = Pattern.compile(":80$");
/**
* 对话框配置
* @param type dialog type
* @param header dialog title
* @param content content of dialog
*/
public static Alert showAlert(Alert.AlertType type, String header, String content){
Alert alert = new Alert(type);
alert.setTitle("提示");
alert.setHeaderText(header);
alert.setContentText(content);
return alert;
}
| public static void exportToExcel(String fileName, String tabTitle, List<ExcelBean> totalData, List<List<String>> urls, StringBuilder errorPage) { | 1 | 2023-10-25 11:13:47+00:00 | 4k |
qguangyao/MySound | src/main/java/com/jvspiano/sound/resolver/AppoggiaturaResolverIMPL.java | [
{
"identifier": "MyNoteIMPL",
"path": "src/main/java/com/jvspiano/sound/note/MyNoteIMPL.java",
"snippet": "public class MyNoteIMPL implements MyNote {\n\n /**\n * 相对于简谱的主调\n */\n private Major major;\n /**\n * 一个节拍里面有几个tick\n */\n private String ppq;\n /**\n * 曲谱速度,bea... | import com.jvspiano.sound.note.MyNoteIMPL;
import com.jvspiano.sound.note.NoteInfo; | 3,490 | package com.jvspiano.sound.resolver;
/**
* 钢琴技法,倚音实现类
*/
public class AppoggiaturaResolverIMPL implements AppoggiaturaResolver {
/**
* 钢琴技法,倚音的实现,此处定义倚音为一前一后(在音乐领域不一定是这样的,没研究过)
* @param noteFrontString 倚音前边音符
* @param noteAfterString 倚音后边音符
* @param noteStart 音符开始的时间,相对于整首曲子
* @param myNoteIMPL 音符映射类
* @param singleNoteResolver 单个音符解析器
* @return 音符信息的数组
*/
@Override | package com.jvspiano.sound.resolver;
/**
* 钢琴技法,倚音实现类
*/
public class AppoggiaturaResolverIMPL implements AppoggiaturaResolver {
/**
* 钢琴技法,倚音的实现,此处定义倚音为一前一后(在音乐领域不一定是这样的,没研究过)
* @param noteFrontString 倚音前边音符
* @param noteAfterString 倚音后边音符
* @param noteStart 音符开始的时间,相对于整首曲子
* @param myNoteIMPL 音符映射类
* @param singleNoteResolver 单个音符解析器
* @return 音符信息的数组
*/
@Override | public NoteInfo[] appoggiatura(String noteFrontString, String noteAfterString, int noteStart, MyNoteIMPL myNoteIMPL, SingleNoteResolver singleNoteResolver) { | 0 | 2023-10-27 11:07:06+00:00 | 4k |
amithkoujalgi/ollama4j | src/main/java/io/github/amithkoujalgi/ollama4j/core/OllamaAPI.java | [
{
"identifier": "OllamaBaseException",
"path": "src/main/java/io/github/amithkoujalgi/ollama4j/core/exceptions/OllamaBaseException.java",
"snippet": "public class OllamaBaseException extends Exception {\n\n public OllamaBaseException(String s) {\n super(s);\n }\n}"
},
{
"identifier"... | import io.github.amithkoujalgi.ollama4j.core.exceptions.OllamaBaseException;
import io.github.amithkoujalgi.ollama4j.core.models.*;
import io.github.amithkoujalgi.ollama4j.core.models.request.CustomModelFileContentsRequest;
import io.github.amithkoujalgi.ollama4j.core.models.request.CustomModelFilePathRequest;
import io.github.amithkoujalgi.ollama4j.core.models.request.ModelEmbeddingsRequest;
import io.github.amithkoujalgi.ollama4j.core.models.request.ModelRequest;
import io.github.amithkoujalgi.ollama4j.core.utils.Options;
import io.github.amithkoujalgi.ollama4j.core.utils.Utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpConnectTimeoutException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 3,200 | getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 200) {
return Utils.getObjectMapper().readValue(responseBody, ModelDetail.class);
} else {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFilePath the path to model file that exists on the Ollama server.
*/
public void createModelWithFilePath(String modelName, String modelFilePath)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFilePathRequest(modelName, modelFilePath).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
// FIXME: Ollama API returns HTTP status code 200 for model creation failure cases. Correct this
// if the issue is fixed in the Ollama API server.
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFileContents the path to model file that exists on the Ollama server.
*/
public void createModelWithModelFileContents(String modelName, String modelFileContents)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFileContentsRequest(modelName, modelFileContents).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Delete a model from Ollama server.
*
* @param modelName the name of the model to be deleted.
* @param ignoreIfNotPresent ignore errors if the specified model is not present on Ollama server.
*/
public void deleteModel(String modelName, boolean ignoreIfNotPresent)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/delete";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.method("DELETE", HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 404 && responseBody.contains("model") && responseBody.contains("not found")) {
return;
}
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Generate embeddings for a given text from a model
*
* @param model name of model to generate embeddings from
* @param prompt text to generate embeddings for
* @return embeddings
*/
public List<Double> generateEmbeddings(String model, String prompt)
throws IOException, InterruptedException, OllamaBaseException {
URI uri = URI.create(this.host + "/api/embeddings"); | package io.github.amithkoujalgi.ollama4j.core;
/** The base Ollama API class. */
@SuppressWarnings("DuplicatedCode")
public class OllamaAPI {
private static final Logger logger = LoggerFactory.getLogger(OllamaAPI.class);
private final String host;
private long requestTimeoutSeconds = 3;
private boolean verbose = true;
private BasicAuth basicAuth;
/**
* Instantiates the Ollama API.
*
* @param host the host address of Ollama server
*/
public OllamaAPI(String host) {
if (host.endsWith("/")) {
this.host = host.substring(0, host.length() - 1);
} else {
this.host = host;
}
}
/**
* Set request timeout in seconds. Default is 3 seconds.
*
* @param requestTimeoutSeconds the request timeout in seconds
*/
public void setRequestTimeoutSeconds(long requestTimeoutSeconds) {
this.requestTimeoutSeconds = requestTimeoutSeconds;
}
/**
* Set/unset logging of responses
*
* @param verbose true/false
*/
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
/**
* Set basic authentication for accessing Ollama server that's behind a reverse-proxy/gateway.
*
* @param username the username
* @param password the password
*/
public void setBasicAuth(String username, String password) {
this.basicAuth = new BasicAuth(username, password);
}
/**
* API to check the reachability of Ollama server.
*
* @return true if the server is reachable, false otherwise.
*/
public boolean ping() {
String url = this.host + "/api/tags";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = null;
try {
httpRequest =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.GET()
.build();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
HttpResponse<String> response = null;
try {
response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
} catch (HttpConnectTimeoutException e) {
return false;
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
int statusCode = response.statusCode();
return statusCode == 200;
}
/**
* List available models from Ollama server.
*
* @return the list
*/
public List<Model> listModels()
throws OllamaBaseException, IOException, InterruptedException, URISyntaxException {
String url = this.host + "/api/tags";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.GET()
.build();
HttpResponse<String> response =
httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode == 200) {
return Utils.getObjectMapper()
.readValue(responseString, ListModelsResponse.class)
.getModels();
} else {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
}
/**
* Pull a model on the Ollama server from the list of <a
* href="https://ollama.ai/library">available models</a>.
*
* @param modelName the name of the model
*/
public void pullModel(String modelName)
throws OllamaBaseException, IOException, URISyntaxException, InterruptedException {
String url = this.host + "/api/pull";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<InputStream> response =
client.send(request, HttpResponse.BodyHandlers.ofInputStream());
int statusCode = response.statusCode();
InputStream responseBodyStream = response.body();
String responseString = "";
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(responseBodyStream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
ModelPullResponse modelPullResponse =
Utils.getObjectMapper().readValue(line, ModelPullResponse.class);
if (verbose) {
logger.info(modelPullResponse.getStatus());
}
}
}
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
}
/**
* Gets model details from the Ollama server.
*
* @param modelName the model
* @return the model details
*/
public ModelDetail getModelDetails(String modelName)
throws IOException, OllamaBaseException, InterruptedException, URISyntaxException {
String url = this.host + "/api/show";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 200) {
return Utils.getObjectMapper().readValue(responseBody, ModelDetail.class);
} else {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFilePath the path to model file that exists on the Ollama server.
*/
public void createModelWithFilePath(String modelName, String modelFilePath)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFilePathRequest(modelName, modelFilePath).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
// FIXME: Ollama API returns HTTP status code 200 for model creation failure cases. Correct this
// if the issue is fixed in the Ollama API server.
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Create a custom model from a model file. Read more about custom model file creation <a
* href="https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md">here</a>.
*
* @param modelName the name of the custom model to be created.
* @param modelFileContents the path to model file that exists on the Ollama server.
*/
public void createModelWithModelFileContents(String modelName, String modelFileContents)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/create";
String jsonData = new CustomModelFileContentsRequest(modelName, modelFileContents).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseString = response.body();
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseString);
}
if (responseString.contains("error")) {
throw new OllamaBaseException(responseString);
}
if (verbose) {
logger.info(responseString);
}
}
/**
* Delete a model from Ollama server.
*
* @param modelName the name of the model to be deleted.
* @param ignoreIfNotPresent ignore errors if the specified model is not present on Ollama server.
*/
public void deleteModel(String modelName, boolean ignoreIfNotPresent)
throws IOException, InterruptedException, OllamaBaseException, URISyntaxException {
String url = this.host + "/api/delete";
String jsonData = new ModelRequest(modelName).toString();
HttpRequest request =
getRequestBuilderDefault(new URI(url))
.method("DELETE", HttpRequest.BodyPublishers.ofString(jsonData, StandardCharsets.UTF_8))
.header("Accept", "application/json")
.header("Content-type", "application/json")
.build();
HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
int statusCode = response.statusCode();
String responseBody = response.body();
if (statusCode == 404 && responseBody.contains("model") && responseBody.contains("not found")) {
return;
}
if (statusCode != 200) {
throw new OllamaBaseException(statusCode + " - " + responseBody);
}
}
/**
* Generate embeddings for a given text from a model
*
* @param model name of model to generate embeddings from
* @param prompt text to generate embeddings for
* @return embeddings
*/
public List<Double> generateEmbeddings(String model, String prompt)
throws IOException, InterruptedException, OllamaBaseException {
URI uri = URI.create(this.host + "/api/embeddings"); | String jsonData = new ModelEmbeddingsRequest(model, prompt).toString(); | 3 | 2023-10-26 19:12:14+00:00 | 4k |
rweisleder/archunit-spring | src/test/java/de/rweisleder/archunit/spring/SpringComponentRulesTest.java | [
{
"identifier": "ControllerWithDependencyToConfiguration",
"path": "src/test/java/de/rweisleder/archunit/spring/testclasses/component/SpringComponents.java",
"snippet": "@Controller\npublic static class ControllerWithDependencyToConfiguration {\n @SuppressWarnings(\"unused\")\n public ControllerWi... | import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.lang.EvaluationResult;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ControllerWithoutDependency;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.RepositoryWithoutDependency;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.ServiceWithoutDependency;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToConfiguration;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToController;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToService;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithDependencyToSpringDataRepository;
import de.rweisleder.archunit.spring.testclasses.component.SpringComponents.SpringDataRepositoryWithoutDependency;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static de.rweisleder.archunit.spring.TestUtils.importClasses;
import static org.assertj.core.api.Assertions.assertThat; | 3,028 | /*
* #%L
* ArchUnit Spring Integration
* %%
* Copyright (C) 2023 Roland Weisleder
* %%
* 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.
* #L%
*/
package de.rweisleder.archunit.spring;
@SuppressWarnings("CodeBlock2Expr")
class SpringComponentRulesTest {
@Nested
class Rule_DependenciesOfControllers {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfControllers.getDescription();
assertThat(description).isEqualTo("Spring controller should only depend on other Spring components that are services or repositories");
}
@Test
void controller_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_other_controller_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToController.class.getName());
});
}
@Test
void controller_with_dependency_to_service_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToService.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_configuration_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName());
});
}
}
@Nested
class Rule_DependenciesOfServices {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfServices.getDescription();
assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories");
}
@Test
void service_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ServiceWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void service_with_dependency_to_controller_is_a_violation() {
JavaClasses classes = importClasses(ServiceWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ServiceWithDependencyToController.class.getName());
});
}
@Test
void service_with_dependency_to_other_service_is_not_a_violation() { | /*
* #%L
* ArchUnit Spring Integration
* %%
* Copyright (C) 2023 Roland Weisleder
* %%
* 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.
* #L%
*/
package de.rweisleder.archunit.spring;
@SuppressWarnings("CodeBlock2Expr")
class SpringComponentRulesTest {
@Nested
class Rule_DependenciesOfControllers {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfControllers.getDescription();
assertThat(description).isEqualTo("Spring controller should only depend on other Spring components that are services or repositories");
}
@Test
void controller_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_other_controller_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToController.class.getName());
});
}
@Test
void controller_with_dependency_to_service_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToService.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_Spring_Data_repository_is_not_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToSpringDataRepository.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void controller_with_dependency_to_configuration_is_a_violation() {
JavaClasses classes = importClasses(ControllerWithDependencyToConfiguration.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfControllers.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ControllerWithDependencyToConfiguration.class.getName());
});
}
}
@Nested
class Rule_DependenciesOfServices {
@Test
void provides_a_description() {
String description = SpringComponentRules.DependenciesOfServices.getDescription();
assertThat(description).isEqualTo("Spring services should only depend on other Spring components that are services or repositories");
}
@Test
void service_without_dependency_is_not_a_violation() {
JavaClasses classes = importClasses(ServiceWithoutDependency.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isFalse();
}
@Test
void service_with_dependency_to_controller_is_a_violation() {
JavaClasses classes = importClasses(ServiceWithDependencyToController.class);
EvaluationResult evaluationResult = SpringComponentRules.DependenciesOfServices.evaluate(classes);
assertThat(evaluationResult.hasViolation()).isTrue();
assertThat(evaluationResult.getFailureReport().getDetails()).anySatisfy(detail -> {
assertThat(detail).contains(ServiceWithDependencyToController.class.getName());
});
}
@Test
void service_with_dependency_to_other_service_is_not_a_violation() { | JavaClasses classes = importClasses(ServiceWithDependencyToService.class); | 15 | 2023-10-29 10:50:24+00:00 | 4k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.