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 |
|---|---|---|---|---|---|---|---|---|---|---|
Milosz08/screen-sharing-system | host/src/main/java/pl/polsl/screensharing/host/view/dialog/SessionDetailsDialogWindow.java | [
{
"identifier": "SessionDetailsController",
"path": "host/src/main/java/pl/polsl/screensharing/host/controller/SessionDetailsController.java",
"snippet": "@Slf4j\n@RequiredArgsConstructor\npublic class SessionDetailsController implements ConnectionHandler {\n private final HostWindow hostWindow;\n ... | import lombok.Getter;
import pl.polsl.screensharing.host.controller.SessionDetailsController;
import pl.polsl.screensharing.host.state.HostState;
import pl.polsl.screensharing.host.view.HostIcon;
import pl.polsl.screensharing.host.view.HostWindow;
import pl.polsl.screensharing.lib.AppType;
import pl.polsl.screensharing.lib.SharedConstants;
import pl.polsl.screensharing.lib.Utils;
import pl.polsl.screensharing.lib.gui.AbstractPopupDialog;
import pl.polsl.screensharing.lib.gui.GridBagDrawer;
import pl.polsl.screensharing.lib.gui.component.JAppIconButton;
import pl.polsl.screensharing.lib.gui.component.JAppPasswordTextField;
import pl.polsl.screensharing.lib.gui.component.JAppTextField;
import pl.polsl.screensharing.lib.gui.input.SimpleDocumentListener;
import pl.polsl.screensharing.lib.icon.LibIcon;
import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import java.awt.*; | 7,578 | /*
* Copyright (c) 2023 by MULTIPLE AUTHORS
* Part of the CS study course project.
*/
package pl.polsl.screensharing.host.view.dialog;
@Getter
public class SessionDetailsDialogWindow extends AbstractPopupDialog {
private final HostState hostState;
private final JPanel formPanel;
private final JPanel rightPanel;
private final JPanel rightTopButtonsPanel;
private final JPanel sessionInfoPanel;
private final TitledBorder sessionInfoTitledBorder;
private final GridBagConstraints sessionInfoGridBag;
private final EmptyBorder margin;
private final Insets gridInset;
private final JPanel ipAddressPanel;
private final JLabel ipAddressLabel;
private final JAppTextField ipAddressTextField;
private final JCheckBox isMachineIpAddress;
private final JLabel portLabel;
private final JAppTextField portTextField;
private final JPanel passwordPanel;
private final JLabel passwordLabel;
private final JAppPasswordTextField passwordTextField;
private final JCheckBox passwordTogglerCheckbox;
private final JCheckBox hasPasswordCheckbox;
private final JAppIconButton connectButton;
private final JAppIconButton cancelButton;
private final JAppIconButton saveDetailsButton;
private final SessionDetailsController controller;
private final SimpleDocumentListener documentListener;
public SessionDetailsDialogWindow(HostWindow hostWindow) {
super(AppType.HOST, 480, 210, "Session details", hostWindow, SessionDetailsDialogWindow.class);
hostState = hostWindow.getHostState();
controller = new SessionDetailsController(hostWindow, this);
documentListener = new SimpleDocumentListener(controller::resetSaveButtonState);
formPanel = new JPanel();
rightPanel = new JPanel(new BorderLayout());
rightTopButtonsPanel = new JPanel(new GridLayout(2, 1, 0, 5));
sessionInfoPanel = new JPanel(new GridBagLayout());
sessionInfoTitledBorder = new TitledBorder("Session details");
sessionInfoGridBag = new GridBagConstraints();
margin = new EmptyBorder(10, 10, 10, 10);
gridInset = new Insets(3, 3, 3, 3);
ipAddressPanel = new JPanel();
ipAddressLabel = new JLabel("IP address");
ipAddressTextField = new JAppTextField(10, 15, SharedConstants.IPV4_REGEX);
isMachineIpAddress = new JCheckBox("Get machine IP");
portLabel = new JLabel("Connection port");
portTextField = new JAppTextField(10, 6, SharedConstants.PORT_REGEX);
passwordPanel = new JPanel();
passwordLabel = new JLabel("Password (optional)");
passwordTextField = new JAppPasswordTextField(10);
passwordTogglerCheckbox = new JCheckBox("Show password");
hasPasswordCheckbox = new JCheckBox("Has Password");
connectButton = new JAppIconButton("Create", HostIcon.ADD_LINK);
cancelButton = new JAppIconButton("Cancel", LibIcon.CANCEL);
saveDetailsButton = new JAppIconButton("Save", LibIcon.SAVE);
initObservables();
ipAddressTextField.getDocument().addDocumentListener(documentListener);
portTextField.getDocument().addDocumentListener(documentListener);
passwordTextField.getDocument().addDocumentListener(documentListener);
passwordTogglerCheckbox.addActionListener(controller::togglePasswordField);
isMachineIpAddress.addActionListener(controller::toggleMachineIpAddressField);
hasPasswordCheckbox.addActionListener(controller::togglePasswordInputField);
connectButton.addActionListener(e -> controller.createSession());
cancelButton.addActionListener(e -> controller.closeWindow());
saveDetailsButton.addActionListener(controller::saveConnectionDetails);
initDialogGui(true);
}
@Override
protected void extendsDialog(JDialog dialog, JPanel rootPanel) {
sessionInfoPanel.setBorder(new CompoundBorder(sessionInfoTitledBorder, margin));
ipAddressPanel.setLayout(new BoxLayout(ipAddressPanel, BoxLayout.Y_AXIS));
ipAddressPanel.add(ipAddressTextField);
ipAddressPanel.add(isMachineIpAddress);
passwordPanel.setLayout(new BoxLayout(passwordPanel, BoxLayout.Y_AXIS));
passwordPanel.add(passwordTextField);
passwordPanel.add(passwordTogglerCheckbox);
passwordPanel.add(hasPasswordCheckbox);
final GridBagDrawer basicInfoDrawer = new GridBagDrawer(sessionInfoPanel, sessionInfoGridBag, gridInset);
basicInfoDrawer.drawGridBagLabels(ipAddressLabel, portLabel, passwordLabel);
basicInfoDrawer.drawGridBagInputs(ipAddressPanel, portTextField, passwordPanel);
formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
formPanel.add(sessionInfoPanel);
rightTopButtonsPanel.add(connectButton);
rightTopButtonsPanel.add(saveDetailsButton);
rightPanel.add(rightTopButtonsPanel, BorderLayout.NORTH);
rightPanel.add(cancelButton, BorderLayout.SOUTH);
rootPanel.add(formPanel, BorderLayout.CENTER);
rootPanel.add(rightPanel, BorderLayout.EAST);
}
private void initObservables() {
hostState.wrapAsDisposable(hostState.getSessionDetails$(), sessionDetails -> {
ipAddressTextField.setText(sessionDetails.getIsMachineIp() | /*
* Copyright (c) 2023 by MULTIPLE AUTHORS
* Part of the CS study course project.
*/
package pl.polsl.screensharing.host.view.dialog;
@Getter
public class SessionDetailsDialogWindow extends AbstractPopupDialog {
private final HostState hostState;
private final JPanel formPanel;
private final JPanel rightPanel;
private final JPanel rightTopButtonsPanel;
private final JPanel sessionInfoPanel;
private final TitledBorder sessionInfoTitledBorder;
private final GridBagConstraints sessionInfoGridBag;
private final EmptyBorder margin;
private final Insets gridInset;
private final JPanel ipAddressPanel;
private final JLabel ipAddressLabel;
private final JAppTextField ipAddressTextField;
private final JCheckBox isMachineIpAddress;
private final JLabel portLabel;
private final JAppTextField portTextField;
private final JPanel passwordPanel;
private final JLabel passwordLabel;
private final JAppPasswordTextField passwordTextField;
private final JCheckBox passwordTogglerCheckbox;
private final JCheckBox hasPasswordCheckbox;
private final JAppIconButton connectButton;
private final JAppIconButton cancelButton;
private final JAppIconButton saveDetailsButton;
private final SessionDetailsController controller;
private final SimpleDocumentListener documentListener;
public SessionDetailsDialogWindow(HostWindow hostWindow) {
super(AppType.HOST, 480, 210, "Session details", hostWindow, SessionDetailsDialogWindow.class);
hostState = hostWindow.getHostState();
controller = new SessionDetailsController(hostWindow, this);
documentListener = new SimpleDocumentListener(controller::resetSaveButtonState);
formPanel = new JPanel();
rightPanel = new JPanel(new BorderLayout());
rightTopButtonsPanel = new JPanel(new GridLayout(2, 1, 0, 5));
sessionInfoPanel = new JPanel(new GridBagLayout());
sessionInfoTitledBorder = new TitledBorder("Session details");
sessionInfoGridBag = new GridBagConstraints();
margin = new EmptyBorder(10, 10, 10, 10);
gridInset = new Insets(3, 3, 3, 3);
ipAddressPanel = new JPanel();
ipAddressLabel = new JLabel("IP address");
ipAddressTextField = new JAppTextField(10, 15, SharedConstants.IPV4_REGEX);
isMachineIpAddress = new JCheckBox("Get machine IP");
portLabel = new JLabel("Connection port");
portTextField = new JAppTextField(10, 6, SharedConstants.PORT_REGEX);
passwordPanel = new JPanel();
passwordLabel = new JLabel("Password (optional)");
passwordTextField = new JAppPasswordTextField(10);
passwordTogglerCheckbox = new JCheckBox("Show password");
hasPasswordCheckbox = new JCheckBox("Has Password");
connectButton = new JAppIconButton("Create", HostIcon.ADD_LINK);
cancelButton = new JAppIconButton("Cancel", LibIcon.CANCEL);
saveDetailsButton = new JAppIconButton("Save", LibIcon.SAVE);
initObservables();
ipAddressTextField.getDocument().addDocumentListener(documentListener);
portTextField.getDocument().addDocumentListener(documentListener);
passwordTextField.getDocument().addDocumentListener(documentListener);
passwordTogglerCheckbox.addActionListener(controller::togglePasswordField);
isMachineIpAddress.addActionListener(controller::toggleMachineIpAddressField);
hasPasswordCheckbox.addActionListener(controller::togglePasswordInputField);
connectButton.addActionListener(e -> controller.createSession());
cancelButton.addActionListener(e -> controller.closeWindow());
saveDetailsButton.addActionListener(controller::saveConnectionDetails);
initDialogGui(true);
}
@Override
protected void extendsDialog(JDialog dialog, JPanel rootPanel) {
sessionInfoPanel.setBorder(new CompoundBorder(sessionInfoTitledBorder, margin));
ipAddressPanel.setLayout(new BoxLayout(ipAddressPanel, BoxLayout.Y_AXIS));
ipAddressPanel.add(ipAddressTextField);
ipAddressPanel.add(isMachineIpAddress);
passwordPanel.setLayout(new BoxLayout(passwordPanel, BoxLayout.Y_AXIS));
passwordPanel.add(passwordTextField);
passwordPanel.add(passwordTogglerCheckbox);
passwordPanel.add(hasPasswordCheckbox);
final GridBagDrawer basicInfoDrawer = new GridBagDrawer(sessionInfoPanel, sessionInfoGridBag, gridInset);
basicInfoDrawer.drawGridBagLabels(ipAddressLabel, portLabel, passwordLabel);
basicInfoDrawer.drawGridBagInputs(ipAddressPanel, portTextField, passwordPanel);
formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
formPanel.add(sessionInfoPanel);
rightTopButtonsPanel.add(connectButton);
rightTopButtonsPanel.add(saveDetailsButton);
rightPanel.add(rightTopButtonsPanel, BorderLayout.NORTH);
rightPanel.add(cancelButton, BorderLayout.SOUTH);
rootPanel.add(formPanel, BorderLayout.CENTER);
rootPanel.add(rightPanel, BorderLayout.EAST);
}
private void initObservables() {
hostState.wrapAsDisposable(hostState.getSessionDetails$(), sessionDetails -> {
ipAddressTextField.setText(sessionDetails.getIsMachineIp() | ? Utils.getMachineAddress() : sessionDetails.getIpAddress()); | 6 | 2023-10-11 16:12:02+00:00 | 12k |
openpilot-hub/devpilot-intellij | src/main/java/com/zhongan/devpilot/integrations/llms/openai/OpenAIServiceProvider.java | [
{
"identifier": "DevPilotChatToolWindowService",
"path": "src/main/java/com/zhongan/devpilot/gui/toolwindows/chat/DevPilotChatToolWindowService.java",
"snippet": "@Service\npublic final class DevPilotChatToolWindowService {\n private final Project project;\n\n private final DevPilotChatToolWindow ... | import com.fasterxml.jackson.databind.ObjectMapper;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.project.Project;
import com.zhongan.devpilot.gui.toolwindows.chat.DevPilotChatToolWindowService;
import com.zhongan.devpilot.integrations.llms.LlmProvider;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionRequest;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionResponse;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotFailedResponse;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotMessage;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotSuccessResponse;
import com.zhongan.devpilot.settings.state.OpenAISettingsState;
import com.zhongan.devpilot.util.DevPilotMessageBundle;
import com.zhongan.devpilot.util.OkhttpUtils;
import com.zhongan.devpilot.util.UserAgentUtils;
import com.zhongan.devpilot.webview.model.MessageModel;
import java.io.IOException;
import java.util.Objects;
import java.util.function.Consumer;
import org.apache.commons.lang3.StringUtils;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.sse.EventSource; | 7,685 | package com.zhongan.devpilot.integrations.llms.openai;
@Service(Service.Level.PROJECT)
public final class OpenAIServiceProvider implements LlmProvider {
private final ObjectMapper objectMapper = new ObjectMapper();
private EventSource es;
private DevPilotChatToolWindowService toolWindowService;
private MessageModel resultModel = new MessageModel();
@Override
public String chatCompletion(Project project, DevPilotChatCompletionRequest chatCompletionRequest, Consumer<String> callback) {
var host = OpenAISettingsState.getInstance().getModelHost();
var apiKey = OpenAISettingsState.getInstance().getPrivateKey();
var service = project.getService(DevPilotChatToolWindowService.class);
this.toolWindowService = service;
if (StringUtils.isEmpty(host)) {
service.callErrorInfo("Chat completion failed: host is empty");
return "";
}
if (StringUtils.isEmpty(apiKey)) {
service.callErrorInfo("Chat completion failed: api key is empty");
return "";
}
var modelName = OpenAISettingsState.getInstance().getModelName();
if (StringUtils.isEmpty(modelName)) {
service.callErrorInfo("Chat completion failed: openai model name is empty");
return "";
}
chatCompletionRequest.setModel(modelName);
try {
var request = new Request.Builder()
.url(host + "/v1/chat/completions")
.header("User-Agent", UserAgentUtils.getUserAgent())
.header("Authorization", "Bearer " + apiKey)
.post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json")))
.build();
this.es = this.buildEventSource(request, service, callback);
} catch (Exception e) {
service.callErrorInfo("Chat completion failed: " + e.getMessage());
return "";
}
return "";
}
@Override
public void interruptSend() {
if (es != null) {
es.cancel();
// remember the broken message
if (resultModel != null && !StringUtils.isEmpty(resultModel.getContent())) {
resultModel.setStreaming(false);
toolWindowService.addMessage(resultModel);
}
toolWindowService.callWebView();
// after interrupt, reset result model
resultModel = null;
}
}
@Override
public DevPilotChatCompletionResponse chatCompletionSync(DevPilotChatCompletionRequest chatCompletionRequest) {
var host = OpenAISettingsState.getInstance().getModelHost();
var apiKey = OpenAISettingsState.getInstance().getPrivateKey();
if (StringUtils.isEmpty(host)) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: host is empty");
}
if (StringUtils.isEmpty(apiKey)) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: api key is empty");
}
var modelName = OpenAISettingsState.getInstance().getModelName();
if (StringUtils.isEmpty(modelName)) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: openai model name is empty");
}
chatCompletionRequest.setModel(modelName);
okhttp3.Response response;
try {
var request = new Request.Builder()
.url(host + "/v1/chat/completions")
.header("User-Agent", UserAgentUtils.getUserAgent())
.header("Authorization", "Bearer " + apiKey)
.post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json")))
.build();
Call call = OkhttpUtils.getClient().newCall(request);
response = call.execute();
} catch (Exception e) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: " + e.getMessage());
}
try {
return parseResult(chatCompletionRequest, response);
} catch (IOException e) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: " + e.getMessage());
}
}
private DevPilotChatCompletionResponse parseResult(DevPilotChatCompletionRequest chatCompletionRequest, okhttp3.Response response) throws IOException {
if (response == null) {
return DevPilotChatCompletionResponse.failed(DevPilotMessageBundle.get("devpilot.chatWindow.response.null"));
}
var result = Objects.requireNonNull(response.body()).string();
if (response.isSuccessful()) {
var message = objectMapper.readValue(result, DevPilotSuccessResponse.class)
.getChoices()
.get(0)
.getMessage(); | package com.zhongan.devpilot.integrations.llms.openai;
@Service(Service.Level.PROJECT)
public final class OpenAIServiceProvider implements LlmProvider {
private final ObjectMapper objectMapper = new ObjectMapper();
private EventSource es;
private DevPilotChatToolWindowService toolWindowService;
private MessageModel resultModel = new MessageModel();
@Override
public String chatCompletion(Project project, DevPilotChatCompletionRequest chatCompletionRequest, Consumer<String> callback) {
var host = OpenAISettingsState.getInstance().getModelHost();
var apiKey = OpenAISettingsState.getInstance().getPrivateKey();
var service = project.getService(DevPilotChatToolWindowService.class);
this.toolWindowService = service;
if (StringUtils.isEmpty(host)) {
service.callErrorInfo("Chat completion failed: host is empty");
return "";
}
if (StringUtils.isEmpty(apiKey)) {
service.callErrorInfo("Chat completion failed: api key is empty");
return "";
}
var modelName = OpenAISettingsState.getInstance().getModelName();
if (StringUtils.isEmpty(modelName)) {
service.callErrorInfo("Chat completion failed: openai model name is empty");
return "";
}
chatCompletionRequest.setModel(modelName);
try {
var request = new Request.Builder()
.url(host + "/v1/chat/completions")
.header("User-Agent", UserAgentUtils.getUserAgent())
.header("Authorization", "Bearer " + apiKey)
.post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json")))
.build();
this.es = this.buildEventSource(request, service, callback);
} catch (Exception e) {
service.callErrorInfo("Chat completion failed: " + e.getMessage());
return "";
}
return "";
}
@Override
public void interruptSend() {
if (es != null) {
es.cancel();
// remember the broken message
if (resultModel != null && !StringUtils.isEmpty(resultModel.getContent())) {
resultModel.setStreaming(false);
toolWindowService.addMessage(resultModel);
}
toolWindowService.callWebView();
// after interrupt, reset result model
resultModel = null;
}
}
@Override
public DevPilotChatCompletionResponse chatCompletionSync(DevPilotChatCompletionRequest chatCompletionRequest) {
var host = OpenAISettingsState.getInstance().getModelHost();
var apiKey = OpenAISettingsState.getInstance().getPrivateKey();
if (StringUtils.isEmpty(host)) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: host is empty");
}
if (StringUtils.isEmpty(apiKey)) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: api key is empty");
}
var modelName = OpenAISettingsState.getInstance().getModelName();
if (StringUtils.isEmpty(modelName)) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: openai model name is empty");
}
chatCompletionRequest.setModel(modelName);
okhttp3.Response response;
try {
var request = new Request.Builder()
.url(host + "/v1/chat/completions")
.header("User-Agent", UserAgentUtils.getUserAgent())
.header("Authorization", "Bearer " + apiKey)
.post(RequestBody.create(objectMapper.writeValueAsString(chatCompletionRequest), MediaType.parse("application/json")))
.build();
Call call = OkhttpUtils.getClient().newCall(request);
response = call.execute();
} catch (Exception e) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: " + e.getMessage());
}
try {
return parseResult(chatCompletionRequest, response);
} catch (IOException e) {
return DevPilotChatCompletionResponse.failed("Chat completion failed: " + e.getMessage());
}
}
private DevPilotChatCompletionResponse parseResult(DevPilotChatCompletionRequest chatCompletionRequest, okhttp3.Response response) throws IOException {
if (response == null) {
return DevPilotChatCompletionResponse.failed(DevPilotMessageBundle.get("devpilot.chatWindow.response.null"));
}
var result = Objects.requireNonNull(response.body()).string();
if (response.isSuccessful()) {
var message = objectMapper.readValue(result, DevPilotSuccessResponse.class)
.getChoices()
.get(0)
.getMessage(); | var devPilotMessage = new DevPilotMessage(); | 5 | 2023-11-29 06:37:51+00:00 | 12k |
Gaia3D/mago-3d-tiler | tiler/src/main/java/com/gaia3d/process/preprocess/GaiaTranslator.java | [
{
"identifier": "GaiaBoundingBox",
"path": "core/src/main/java/com/gaia3d/basic/geometry/GaiaBoundingBox.java",
"snippet": "@Slf4j\n@Setter\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class GaiaBoundingBox {\n private double minX, minY, minZ;\n private double maxX, maxY, maxZ;\n p... | import com.gaia3d.basic.geometry.GaiaBoundingBox;
import com.gaia3d.basic.structure.GaiaNode;
import com.gaia3d.basic.structure.GaiaScene;
import com.gaia3d.basic.types.FormatType;
import com.gaia3d.converter.kml.KmlInfo;
import com.gaia3d.process.ProcessOptions;
import com.gaia3d.process.tileprocess.tile.TileInfo;
import com.gaia3d.util.GlobeUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.CommandLine;
import org.joml.Matrix4d;
import org.joml.Vector3d;
import org.locationtech.proj4j.CoordinateReferenceSystem;
import org.locationtech.proj4j.ProjCoordinate; | 7,434 | package com.gaia3d.process.preprocess;
@Slf4j
@AllArgsConstructor
public class GaiaTranslator implements PreProcess {
private final CoordinateReferenceSystem source;
private final CommandLine command;
@Override
public TileInfo run(TileInfo tileInfo) {
String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName());
FormatType formatType = FormatType.fromExtension(inputExtension);
/*if (formatType == FormatType.KML) {
return tileInfo;
}*/
/*if (source == null && tileInfo != null) {
return tileInfo;
}*/
| package com.gaia3d.process.preprocess;
@Slf4j
@AllArgsConstructor
public class GaiaTranslator implements PreProcess {
private final CoordinateReferenceSystem source;
private final CommandLine command;
@Override
public TileInfo run(TileInfo tileInfo) {
String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName());
FormatType formatType = FormatType.fromExtension(inputExtension);
/*if (formatType == FormatType.KML) {
return tileInfo;
}*/
/*if (source == null && tileInfo != null) {
return tileInfo;
}*/
| GaiaScene gaiaScene = tileInfo.getScene(); | 2 | 2023-11-30 01:59:44+00:00 | 12k |
xuemingqi/x-cloud | x-auth/src/main/java/com/x/auth/service/impl/LoginServiceImpl.java | [
{
"identifier": "JwtConfig",
"path": "x-auth/src/main/java/com/x/auth/common/jwt/JwtConfig.java",
"snippet": "@RefreshScope\n@Configuration\npublic class JwtConfig {\n\n /**\n * 加密字符串\n */\n public static String sign;\n\n /**\n * 签发机构\n */\n public static String iss;\n\n /... | import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Snowflake;
import com.x.auth.common.jwt.JwtConfig;
import com.x.auth.common.jwt.JwtUtil;
import com.x.auth.common.jwt.UserInfoClaims;
import com.x.auth.common.property.LoginProperty;
import com.x.auth.domain.VerificationCodeDo;
import com.x.auth.service.LoginService;
import com.x.common.constants.CommonConstant;
import com.x.common.enums.ResponseCodeEnum;
import com.x.common.response.BaseResult;
import com.x.common.response.ResultUtil;
import com.x.common.utils.ServerUtil;
import com.x.config.redis.util.RedisUtil;
import com.x.contact.api.UserApi;
import com.x.contact.dto.UserAuthDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit; | 9,672 | package com.x.auth.service.impl;
/**
* @author : xuemingqi
* @since : 2023/1/10 14:04
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class LoginServiceImpl implements LoginService {
private final Snowflake snowflake;
private final RedisUtil redisUtil;
private final UserApi userApi;
private final JwtUtil jwtUtil;
private final LoginProperty loginProperty;
@Override
public BaseResult<?> login(String mobile, String password) {
//用户密码是否正确
BaseResult<Long> checkResult = userApi.userAuth(UserAuthDto.builder()
.mobile(mobile)
.password(password)
.build());
if (!ResponseCodeEnum.SUCCESS.getCode().equals(checkResult.getCode())) {
return fail(mobile);
}
//生成token
String token = jwtUtil.createToken(UserInfoClaims.builder()
.userId(checkResult.getData().toString())
.mobile(mobile)
.build());
String redisKey = CommonConstant.TOKEN_KEY + token;
//redis记录
redisUtil.set(redisKey, mobile, JwtConfig.expiresTime, TimeUnit.MINUTES);
//清除之前错误记录
redisUtil.del(CommonConstant.LOGIN_FAIL + mobile);
return ResultUtil.buildResultSuccess(token);
}
@Override
public BaseResult<?> getVerificationCode() {
//画验证码
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(160, 60, 4, 80);
//验证码id
Long id = snowflake.nextId();
//验证码code
String code = lineCaptcha.getCode();
//redis记录
redisUtil.set(CommonConstant.VERIFICATION_CODE_ID + id, code, 1, TimeUnit.MINUTES);
log.info("code:{},codeId:{}", code, id); | package com.x.auth.service.impl;
/**
* @author : xuemingqi
* @since : 2023/1/10 14:04
*/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class LoginServiceImpl implements LoginService {
private final Snowflake snowflake;
private final RedisUtil redisUtil;
private final UserApi userApi;
private final JwtUtil jwtUtil;
private final LoginProperty loginProperty;
@Override
public BaseResult<?> login(String mobile, String password) {
//用户密码是否正确
BaseResult<Long> checkResult = userApi.userAuth(UserAuthDto.builder()
.mobile(mobile)
.password(password)
.build());
if (!ResponseCodeEnum.SUCCESS.getCode().equals(checkResult.getCode())) {
return fail(mobile);
}
//生成token
String token = jwtUtil.createToken(UserInfoClaims.builder()
.userId(checkResult.getData().toString())
.mobile(mobile)
.build());
String redisKey = CommonConstant.TOKEN_KEY + token;
//redis记录
redisUtil.set(redisKey, mobile, JwtConfig.expiresTime, TimeUnit.MINUTES);
//清除之前错误记录
redisUtil.del(CommonConstant.LOGIN_FAIL + mobile);
return ResultUtil.buildResultSuccess(token);
}
@Override
public BaseResult<?> getVerificationCode() {
//画验证码
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(160, 60, 4, 80);
//验证码id
Long id = snowflake.nextId();
//验证码code
String code = lineCaptcha.getCode();
//redis记录
redisUtil.set(CommonConstant.VERIFICATION_CODE_ID + id, code, 1, TimeUnit.MINUTES);
log.info("code:{},codeId:{}", code, id); | return ResultUtil.buildResultSuccess(VerificationCodeDo.builder() | 4 | 2023-11-27 08:23:38+00:00 | 12k |
okx/OKBund | aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/gas/impl/GasEstimatorDefaultImpl.java | [
{
"identifier": "IChain",
"path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/IChain.java",
"snippet": "public interface IChain {\n\n long getChainId();\n\n boolean isEip1559();\n\n Web3jDebug getWeb3j();\n\n}"
},
{
"identifier": "TransactionUtil",
"path": "aa-infra/... | import com.google.common.collect.Lists;
import com.okcoin.dapp.bundler.infra.chain.IChain;
import com.okcoin.dapp.bundler.infra.chain.TransactionUtil;
import com.okcoin.dapp.bundler.infra.chain.constant.ChainIdConstant;
import com.okcoin.dapp.bundler.infra.chain.constant.Web3Constant;
import com.okcoin.dapp.bundler.infra.chain.exception.ChainException;
import com.okcoin.dapp.bundler.pool.domain.UserOperationDO;
import com.okcoin.dapp.bundler.pool.domain.error.SimulateHandleOpResultOKX;
import com.okcoin.dapp.bundler.pool.entrypoint.Entrypoint;
import com.okcoin.dapp.bundler.pool.exception.AAException;
import com.okcoin.dapp.bundler.pool.exception.AAExceptionEnum;
import com.okcoin.dapp.bundler.pool.gasprice.GasPriceInfo;
import com.okcoin.dapp.bundler.pool.gasprice.GasService;
import com.okcoin.dapp.bundler.pool.simulation.EntryPointSimulationsFactory;
import com.okcoin.dapp.bundler.pool.simulation.IEntryPointSimulations;
import com.okcoin.dapp.bundler.pool.util.MathUtil;
import com.okcoin.dapp.bundler.rest.config.RestConfig;
import com.okcoin.dapp.bundler.rest.constant.GasConstant;
import com.okcoin.dapp.bundler.rest.gas.IGasEstimator;
import com.okcoin.dapp.bundler.rest.gas.UserOperationGasDO;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import static com.okcoin.dapp.bundler.rest.constant.GasConstant.*; | 9,890 | package com.okcoin.dapp.bundler.rest.gas.impl;
@Service
@Setter
public class GasEstimatorDefaultImpl implements IGasEstimator {
@Autowired
private EntryPointSimulationsFactory entryPointSimulationsFactory;
@Autowired
private RestConfig restConfig;
@Autowired
private GasService gasService;
@Override
public boolean fit(IChain chain) {
return ChainIdConstant.OP_MAIN != chain.getChainId() && ChainIdConstant.ARB_MAIN != chain.getChainId();
}
public UserOperationGasDO estimateGasFromEvm(UserOperationDO uop) {
IChain chain = uop.getChain();
BigInteger maxFeePerGas = uop.getMaxFeePerGas();
BigInteger maxPriorityFeePerGas = uop.getMaxPriorityFeePerGas();
BigInteger preVerificationGas = uop.getPreVerificationGas();
BigInteger verificationGasLimit = uop.getVerificationGasLimit();
BigInteger callGasLimit = uop.getCallGasLimit();
String callData = uop.getCallData();
String paymasterAndData = uop.getPaymasterAndData();
uop.setPreVerificationGas(preVerificationGas.compareTo(BigInteger.ZERO) == 0 ? PRE_VERIFICATION_GAS_MIN : preVerificationGas);
uop.setVerificationGasLimit(verificationGasLimit.compareTo(BigInteger.ZERO) == 0 ? VERIFICATION_GAS_LIMIT_MIN : verificationGasLimit);
uop.setCallGasLimit(callGasLimit.compareTo(BigInteger.ZERO) == 0 ? CALL_GAS_LIMIT_MIN : callGasLimit);
if (Web3Constant.HEX_PREFIX.equals(callData)) {
uop.setCallGasLimit(BigInteger.ZERO);
}
GasPriceInfo gasPriceInfo = gasService.getGasPriceInfoWithCache(chain);
BigInteger maxFeePerGasMin = gasPriceInfo.resolveMaxFeePerGas();
BigInteger maxPriorityFeePerGasMin = gasPriceInfo.getMaxPriorityFeePerGas();
uop.setMaxFeePerGas(maxFeePerGas.compareTo(BigInteger.ZERO) == 0 ? maxFeePerGasMin : maxFeePerGas);
if (chain.isEip1559()) {
uop.setMaxPriorityFeePerGas(maxPriorityFeePerGas.compareTo(BigInteger.ZERO) == 0 ? maxPriorityFeePerGasMin : maxPriorityFeePerGas);
} else {
uop.setMaxPriorityFeePerGas(maxPriorityFeePerGas.compareTo(BigInteger.ZERO) == 0 ? maxFeePerGasMin : maxPriorityFeePerGas);
}
IEntryPointSimulations entryPointSimulations = entryPointSimulationsFactory.get(uop.getEntryPoint());
SimulateHandleOpResultOKX simulateHandleOpResult = entryPointSimulations.simulateHandleOp(uop, true);
verificationGasLimit = simulateHandleOpResult.getVerificationGasUsed();
callGasLimit = simulateHandleOpResult.getCallGasUsed();
preVerificationGas = simulateHandleOpResult.getPreVerificationGas();
BigInteger postOpGas = simulateHandleOpResult.getPostOpGasUsed();
long validAfter = simulateHandleOpResult.getValidAfter();
long validUntil = simulateHandleOpResult.getValidUntil();
if (Web3Constant.HEX_PREFIX.equals(paymasterAndData)) {
verificationGasLimit = verificationGasLimit.add(postOpGas);
}
if (Web3Constant.HEX_PREFIX.equals(callData)) {
verificationGasLimit = verificationGasLimit.add(callGasLimit);
postOpGas = postOpGas.add(callGasLimit);
callGasLimit = BigInteger.ZERO;
}
return new UserOperationGasDO(preVerificationGas, MathUtil.max(verificationGasLimit, postOpGas), callGasLimit, validAfter, validUntil);
}
public BigInteger estimateCallGasLimitFromNode(UserOperationDO uop) {
if (!restConfig.isOpenEstimateGasFromNode() || !Web3Constant.HEX_PREFIX.equals(uop.getInitCode()) || Web3Constant.HEX_PREFIX.equals(uop.getCallData())) {
return BigInteger.ZERO;
}
try {
return TransactionUtil.estimateGas(uop.getEntryPoint(), uop.getSender(), uop.getCallData(), uop.getChain());
} catch (ChainException e) { | package com.okcoin.dapp.bundler.rest.gas.impl;
@Service
@Setter
public class GasEstimatorDefaultImpl implements IGasEstimator {
@Autowired
private EntryPointSimulationsFactory entryPointSimulationsFactory;
@Autowired
private RestConfig restConfig;
@Autowired
private GasService gasService;
@Override
public boolean fit(IChain chain) {
return ChainIdConstant.OP_MAIN != chain.getChainId() && ChainIdConstant.ARB_MAIN != chain.getChainId();
}
public UserOperationGasDO estimateGasFromEvm(UserOperationDO uop) {
IChain chain = uop.getChain();
BigInteger maxFeePerGas = uop.getMaxFeePerGas();
BigInteger maxPriorityFeePerGas = uop.getMaxPriorityFeePerGas();
BigInteger preVerificationGas = uop.getPreVerificationGas();
BigInteger verificationGasLimit = uop.getVerificationGasLimit();
BigInteger callGasLimit = uop.getCallGasLimit();
String callData = uop.getCallData();
String paymasterAndData = uop.getPaymasterAndData();
uop.setPreVerificationGas(preVerificationGas.compareTo(BigInteger.ZERO) == 0 ? PRE_VERIFICATION_GAS_MIN : preVerificationGas);
uop.setVerificationGasLimit(verificationGasLimit.compareTo(BigInteger.ZERO) == 0 ? VERIFICATION_GAS_LIMIT_MIN : verificationGasLimit);
uop.setCallGasLimit(callGasLimit.compareTo(BigInteger.ZERO) == 0 ? CALL_GAS_LIMIT_MIN : callGasLimit);
if (Web3Constant.HEX_PREFIX.equals(callData)) {
uop.setCallGasLimit(BigInteger.ZERO);
}
GasPriceInfo gasPriceInfo = gasService.getGasPriceInfoWithCache(chain);
BigInteger maxFeePerGasMin = gasPriceInfo.resolveMaxFeePerGas();
BigInteger maxPriorityFeePerGasMin = gasPriceInfo.getMaxPriorityFeePerGas();
uop.setMaxFeePerGas(maxFeePerGas.compareTo(BigInteger.ZERO) == 0 ? maxFeePerGasMin : maxFeePerGas);
if (chain.isEip1559()) {
uop.setMaxPriorityFeePerGas(maxPriorityFeePerGas.compareTo(BigInteger.ZERO) == 0 ? maxPriorityFeePerGasMin : maxPriorityFeePerGas);
} else {
uop.setMaxPriorityFeePerGas(maxPriorityFeePerGas.compareTo(BigInteger.ZERO) == 0 ? maxFeePerGasMin : maxPriorityFeePerGas);
}
IEntryPointSimulations entryPointSimulations = entryPointSimulationsFactory.get(uop.getEntryPoint());
SimulateHandleOpResultOKX simulateHandleOpResult = entryPointSimulations.simulateHandleOp(uop, true);
verificationGasLimit = simulateHandleOpResult.getVerificationGasUsed();
callGasLimit = simulateHandleOpResult.getCallGasUsed();
preVerificationGas = simulateHandleOpResult.getPreVerificationGas();
BigInteger postOpGas = simulateHandleOpResult.getPostOpGasUsed();
long validAfter = simulateHandleOpResult.getValidAfter();
long validUntil = simulateHandleOpResult.getValidUntil();
if (Web3Constant.HEX_PREFIX.equals(paymasterAndData)) {
verificationGasLimit = verificationGasLimit.add(postOpGas);
}
if (Web3Constant.HEX_PREFIX.equals(callData)) {
verificationGasLimit = verificationGasLimit.add(callGasLimit);
postOpGas = postOpGas.add(callGasLimit);
callGasLimit = BigInteger.ZERO;
}
return new UserOperationGasDO(preVerificationGas, MathUtil.max(verificationGasLimit, postOpGas), callGasLimit, validAfter, validUntil);
}
public BigInteger estimateCallGasLimitFromNode(UserOperationDO uop) {
if (!restConfig.isOpenEstimateGasFromNode() || !Web3Constant.HEX_PREFIX.equals(uop.getInitCode()) || Web3Constant.HEX_PREFIX.equals(uop.getCallData())) {
return BigInteger.ZERO;
}
try {
return TransactionUtil.estimateGas(uop.getEntryPoint(), uop.getSender(), uop.getCallData(), uop.getChain());
} catch (ChainException e) { | throw new AAException(e.getData(), AAExceptionEnum.USER_OPERATION_REVERTED, e.getMsg()); | 9 | 2023-11-27 10:54:49+00:00 | 12k |
seraxis/lr2oraja-endlessdream | core/src/bms/player/beatoraja/skin/SkinGraph.java | [
{
"identifier": "MainState",
"path": "core/src/bms/player/beatoraja/MainState.java",
"snippet": "public abstract class MainState {\n\n\tpublic final MainController main;\n\n\t/**\n\t * スキン\n\t */\n\tprivate Skin skin;\n\n\tprivate Stage stage;\n\t\n\tpublic final TimerManager timer;\n\t\n\tpublic final ... | import bms.player.beatoraja.MainState;
import bms.player.beatoraja.skin.Skin.SkinObjectRenderer;
import bms.player.beatoraja.skin.property.FloatProperty;
import bms.player.beatoraja.skin.property.FloatPropertyFactory;
import bms.player.beatoraja.skin.property.TimerProperty;
import com.badlogic.gdx.graphics.g2d.TextureRegion; | 7,395 | package bms.player.beatoraja.skin;
/**
* スキンオブジェクト:グラフ
*
* @author exch
*/
public class SkinGraph extends SkinObject {
/**
* イメージ
*/
private SkinSource source;
/**
* グラフ値参照先
*/
private final FloatProperty ref;
/**
* グラフの伸びる向き(1:下, それ以外:右)
*/
private int direction = 1;
private final TextureRegion current = new TextureRegion();
private TextureRegion currentImage;
private float currentValue;
public SkinGraph(int imageid, int id) {
source = new SkinSourceReference(imageid);
ref = FloatPropertyFactory.getFloatProperty(id);
}
public SkinGraph(int imageid, FloatProperty ref) {
source = new SkinSourceReference(imageid);
this.ref = ref;
}
public SkinGraph(int imageid, int id, int min, int max) {
source = new SkinSourceReference(imageid);
ref = new RateProperty(id, min, max);
}
public SkinGraph(TextureRegion[] image, int timer, int cycle, int id) {
source = new SkinSourceImage(image, timer, cycle);
ref = FloatPropertyFactory.getFloatProperty(id);
}
public SkinGraph(TextureRegion[] image, int timer, int cycle, FloatProperty ref) {
source = new SkinSourceImage(image, timer, cycle);
this.ref = ref;
}
public SkinGraph(TextureRegion[] image, int timer, int cycle, int id, int min, int max) {
source = new SkinSourceImage(image, timer, cycle);
ref = new RateProperty(id, min, max);
}
| package bms.player.beatoraja.skin;
/**
* スキンオブジェクト:グラフ
*
* @author exch
*/
public class SkinGraph extends SkinObject {
/**
* イメージ
*/
private SkinSource source;
/**
* グラフ値参照先
*/
private final FloatProperty ref;
/**
* グラフの伸びる向き(1:下, それ以外:右)
*/
private int direction = 1;
private final TextureRegion current = new TextureRegion();
private TextureRegion currentImage;
private float currentValue;
public SkinGraph(int imageid, int id) {
source = new SkinSourceReference(imageid);
ref = FloatPropertyFactory.getFloatProperty(id);
}
public SkinGraph(int imageid, FloatProperty ref) {
source = new SkinSourceReference(imageid);
this.ref = ref;
}
public SkinGraph(int imageid, int id, int min, int max) {
source = new SkinSourceReference(imageid);
ref = new RateProperty(id, min, max);
}
public SkinGraph(TextureRegion[] image, int timer, int cycle, int id) {
source = new SkinSourceImage(image, timer, cycle);
ref = FloatPropertyFactory.getFloatProperty(id);
}
public SkinGraph(TextureRegion[] image, int timer, int cycle, FloatProperty ref) {
source = new SkinSourceImage(image, timer, cycle);
this.ref = ref;
}
public SkinGraph(TextureRegion[] image, int timer, int cycle, int id, int min, int max) {
source = new SkinSourceImage(image, timer, cycle);
ref = new RateProperty(id, min, max);
}
| public SkinGraph(TextureRegion[] image, TimerProperty timer, int cycle, int id) { | 4 | 2023-12-02 23:41:17+00:00 | 12k |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | android/src/main/java/com/shatteredpixel/shatteredpixeldungeon/android/AndroidPlatformSupport.java | [
{
"identifier": "SPDSettings",
"path": "core/src/main/java/com/shatteredpixel/shatteredpixeldungeon/SPDSettings.java",
"snippet": "public class SPDSettings extends GameSettings {\n\t\n\t//Version info\n\t\n\tpublic static final String KEY_VERSION = \"version\";\n\t\n\tpublic static void version( in... | import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.view.View;
import android.view.WindowManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.android.AndroidGraphics;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.PixmapPacker;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.shatteredpixel.shatteredpixeldungeon.SPDSettings;
import com.shatteredpixel.shatteredpixeldungeon.scenes.PixelScene;
import com.watabou.noosa.Game;
import com.watabou.utils.PlatformSupport;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 10,725 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2023 Evan Debenham
*
* 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 <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.android;
public class AndroidPlatformSupport extends PlatformSupport {
public void updateDisplaySize(){
if (SPDSettings.landscape() != null) {
AndroidLauncher.instance.setRequestedOrientation( SPDSettings.landscape() ?
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE :
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT );
}
GLSurfaceView view = (GLSurfaceView) ((AndroidGraphics)Gdx.graphics).getView();
if (view.getMeasuredWidth() == 0 || view.getMeasuredHeight() == 0)
return;
Game.dispWidth = view.getMeasuredWidth();
Game.dispHeight = view.getMeasuredHeight();
boolean fullscreen = Build.VERSION.SDK_INT < Build.VERSION_CODES.N
|| !AndroidLauncher.instance.isInMultiWindowMode();
if (fullscreen && SPDSettings.landscape() != null
&& (Game.dispWidth >= Game.dispHeight) != SPDSettings.landscape()){
int tmp = Game.dispWidth;
Game.dispWidth = Game.dispHeight;
Game.dispHeight = tmp;
}
float dispRatio = Game.dispWidth / (float)Game.dispHeight;
| /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2023 Evan Debenham
*
* 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 <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon.android;
public class AndroidPlatformSupport extends PlatformSupport {
public void updateDisplaySize(){
if (SPDSettings.landscape() != null) {
AndroidLauncher.instance.setRequestedOrientation( SPDSettings.landscape() ?
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE :
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT );
}
GLSurfaceView view = (GLSurfaceView) ((AndroidGraphics)Gdx.graphics).getView();
if (view.getMeasuredWidth() == 0 || view.getMeasuredHeight() == 0)
return;
Game.dispWidth = view.getMeasuredWidth();
Game.dispHeight = view.getMeasuredHeight();
boolean fullscreen = Build.VERSION.SDK_INT < Build.VERSION_CODES.N
|| !AndroidLauncher.instance.isInMultiWindowMode();
if (fullscreen && SPDSettings.landscape() != null
&& (Game.dispWidth >= Game.dispHeight) != SPDSettings.landscape()){
int tmp = Game.dispWidth;
Game.dispWidth = Game.dispHeight;
Game.dispHeight = tmp;
}
float dispRatio = Game.dispWidth / (float)Game.dispHeight;
| float renderWidth = dispRatio > 1 ? PixelScene.MIN_WIDTH_L : PixelScene.MIN_WIDTH_P; | 1 | 2023-11-27 05:56:58+00:00 | 12k |
Tofaa2/EntityLib | src/main/java/me/tofaa/entitylib/MetaConverterRegistry.java | [
{
"identifier": "EntityMeta",
"path": "src/main/java/me/tofaa/entitylib/meta/EntityMeta.java",
"snippet": "public class EntityMeta implements EntityMetadataProvider {\n\n public static final byte OFFSET = 0;\n public static final byte MAX_OFFSET = OFFSET + 8;\n\n private final static byte ON_FI... | import com.github.retrooper.packetevents.protocol.entity.type.EntityType;
import me.tofaa.entitylib.meta.EntityMeta;
import me.tofaa.entitylib.meta.Metadata;
import me.tofaa.entitylib.meta.display.BlockDisplayMeta;
import me.tofaa.entitylib.meta.display.ItemDisplayMeta;
import me.tofaa.entitylib.meta.display.TextDisplayMeta;
import me.tofaa.entitylib.meta.mobs.*;
import me.tofaa.entitylib.meta.mobs.DonkeyMeta;
import me.tofaa.entitylib.meta.mobs.cuboid.MagmaCubeMeta;
import me.tofaa.entitylib.meta.mobs.cuboid.SlimeMeta;
import me.tofaa.entitylib.meta.mobs.golem.IronGolemMeta;
import me.tofaa.entitylib.meta.mobs.golem.ShulkerMeta;
import me.tofaa.entitylib.meta.mobs.golem.SnowGolemMeta;
import me.tofaa.entitylib.meta.mobs.horse.*;
import me.tofaa.entitylib.meta.mobs.monster.*;
import me.tofaa.entitylib.meta.mobs.monster.piglin.PiglinBruteMeta;
import me.tofaa.entitylib.meta.mobs.monster.piglin.PiglinMeta;
import me.tofaa.entitylib.meta.mobs.monster.raider.*;
import me.tofaa.entitylib.meta.mobs.monster.skeleton.SkeletonMeta;
import me.tofaa.entitylib.meta.mobs.monster.skeleton.StrayMeta;
import me.tofaa.entitylib.meta.mobs.monster.skeleton.WitherSkeletonMeta;
import me.tofaa.entitylib.meta.mobs.monster.zombie.*;
import me.tofaa.entitylib.meta.mobs.passive.*;
import me.tofaa.entitylib.meta.mobs.water.*;
import me.tofaa.entitylib.meta.mobs.minecart.*;
import me.tofaa.entitylib.meta.mobs.tameable.CatMeta;
import me.tofaa.entitylib.meta.mobs.tameable.ParrotMeta;
import me.tofaa.entitylib.meta.mobs.tameable.WolfMeta;
import me.tofaa.entitylib.meta.mobs.villager.VillagerMeta;
import me.tofaa.entitylib.meta.mobs.villager.WanderingTraderMeta;
import me.tofaa.entitylib.meta.other.*;
import me.tofaa.entitylib.meta.projectile.*;
import me.tofaa.entitylib.meta.types.PlayerMeta;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import static com.github.retrooper.packetevents.protocol.entity.type.EntityTypes.*; | 8,846 | package me.tofaa.entitylib;
@SuppressWarnings("unchecked")
final class MetaConverterRegistry {
private final Map<EntityType, BiFunction<Integer, Metadata, EntityMeta>> converters = new HashMap<>();
private final Map<EntityType, Class<? extends EntityMeta>> metaClasses = new HashMap<>();
MetaConverterRegistry() {
put(SNIFFER, SnifferMeta.class, SnifferMeta::new);
put(INTERACTION, InteractionMeta.class, InteractionMeta::new);
put(BLOCK_DISPLAY, BlockDisplayMeta.class, BlockDisplayMeta::new); | package me.tofaa.entitylib;
@SuppressWarnings("unchecked")
final class MetaConverterRegistry {
private final Map<EntityType, BiFunction<Integer, Metadata, EntityMeta>> converters = new HashMap<>();
private final Map<EntityType, Class<? extends EntityMeta>> metaClasses = new HashMap<>();
MetaConverterRegistry() {
put(SNIFFER, SnifferMeta.class, SnifferMeta::new);
put(INTERACTION, InteractionMeta.class, InteractionMeta::new);
put(BLOCK_DISPLAY, BlockDisplayMeta.class, BlockDisplayMeta::new); | put(ITEM_DISPLAY, ItemDisplayMeta.class, ItemDisplayMeta::new); | 3 | 2023-11-27 02:17:41+00:00 | 12k |
WiIIiam278/HuskClaims | common/src/main/java/net/william278/huskclaims/command/TrustCommand.java | [
{
"identifier": "HuskClaims",
"path": "common/src/main/java/net/william278/huskclaims/HuskClaims.java",
"snippet": "public interface HuskClaims extends Task.Supplier, ConfigProvider, DatabaseProvider, GsonProvider, UserManager,\n ClaimManager, GroupManager, TrustTagManager, ListenerProvider, User... | import java.util.Optional;
import java.util.UUID;
import net.william278.huskclaims.HuskClaims;
import net.william278.huskclaims.claim.Claim;
import net.william278.huskclaims.claim.ClaimWorld;
import net.william278.huskclaims.trust.TrustLevel;
import net.william278.huskclaims.trust.Trustable;
import net.william278.huskclaims.user.OnlineUser;
import net.william278.huskclaims.user.User;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List; | 8,538 | /*
* This file is part of HuskClaims, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* 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 net.william278.huskclaims.command;
public class TrustCommand extends InClaimCommand implements TrustableTabCompletable {
private final TrustLevel level;
protected TrustCommand(@NotNull TrustLevel level, @NotNull HuskClaims plugin) {
super(
level.getCommandAliases(),
getUsageText(plugin.getSettings()),
TrustLevel.Privilege.MANAGE_TRUSTEES,
plugin
);
this.level = level;
}
@Override
public void execute(@NotNull OnlineUser executor, @NotNull ClaimWorld world, @NotNull Claim claim,
@NotNull String[] args) {
final List<String> toTrust = parseStringList(args, 0);
if (toTrust.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return;
}
toTrust.forEach(name -> setTrust(executor, name, world, claim));
}
// Resolve the trustable and check the executor has access
private void setTrust(@NotNull OnlineUser executor, @NotNull String name,
@NotNull ClaimWorld world, @NotNull Claim claim) {
resolveTrustable(executor, name, claim)
.flatMap(t -> checkUserHasAccess(executor, t, world, claim) ? Optional.of(t) : Optional.empty())
.ifPresent(t -> setTrust(executor, t, world, claim));
}
// Set the trust level | /*
* This file is part of HuskClaims, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <will27528@gmail.com>
* Copyright (c) contributors
*
* 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 net.william278.huskclaims.command;
public class TrustCommand extends InClaimCommand implements TrustableTabCompletable {
private final TrustLevel level;
protected TrustCommand(@NotNull TrustLevel level, @NotNull HuskClaims plugin) {
super(
level.getCommandAliases(),
getUsageText(plugin.getSettings()),
TrustLevel.Privilege.MANAGE_TRUSTEES,
plugin
);
this.level = level;
}
@Override
public void execute(@NotNull OnlineUser executor, @NotNull ClaimWorld world, @NotNull Claim claim,
@NotNull String[] args) {
final List<String> toTrust = parseStringList(args, 0);
if (toTrust.isEmpty()) {
plugin.getLocales().getLocale("error_invalid_syntax", getUsage())
.ifPresent(executor::sendMessage);
return;
}
toTrust.forEach(name -> setTrust(executor, name, world, claim));
}
// Resolve the trustable and check the executor has access
private void setTrust(@NotNull OnlineUser executor, @NotNull String name,
@NotNull ClaimWorld world, @NotNull Claim claim) {
resolveTrustable(executor, name, claim)
.flatMap(t -> checkUserHasAccess(executor, t, world, claim) ? Optional.of(t) : Optional.empty())
.ifPresent(t -> setTrust(executor, t, world, claim));
}
// Set the trust level | private void setTrust(@NotNull OnlineUser executor, @NotNull Trustable trustable, | 4 | 2023-11-28 01:09:43+00:00 | 12k |
Manzzx/multi-channel-message-reach | metax-web/src/main/java/com/metax/web/service/impl/MessageTemplateServiceImpl.java | [
{
"identifier": "SecurityContextHolder",
"path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/context/SecurityContextHolder.java",
"snippet": "public class SecurityContextHolder\n{\n private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new Transmitt... | import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.metax.common.core.context.SecurityContextHolder;
import com.metax.web.domain.MessageTemplate;
import com.metax.web.domain.dingding.DingDingRobotParam;
import com.metax.web.dto.MessageTemplateDto;
import com.metax.web.dto.content.DingDingRobotContentModel;
import com.metax.web.dto.content.FeiShuRobotContentModel;
import com.metax.web.dto.content.PushContentModel;
import com.metax.web.dto.content.WeChatServiceAccountContentModel;
import com.metax.web.mapper.MessageTemplateMapper;
import com.metax.web.util.DataUtil;
import com.metax.web.xxljob.service.XxlJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.metax.web.service.IMessageTemplateService;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static com.metax.common.core.constant.SendMessageTypeConstants.*;
import static com.metax.common.core.constant.GeTuiConstants.*;
import static com.metax.common.core.constant.GeTuiConstants.CLICK_TYPE_PAYLOAD_CUSTOM;
import static com.metax.common.core.constant.MetaxDataConstants.*; | 10,733 | package com.metax.web.service.impl;
/**
* 消息模板Service业务层处理
*
* @author hanabi
* @date 2023-09-08
*/
@Service
public class MessageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplate> implements IMessageTemplateService {
@Autowired
private MessageTemplateMapper messageTemplateMapper;
@Autowired
private XxlJobService xxlJobService;
@Autowired | package com.metax.web.service.impl;
/**
* 消息模板Service业务层处理
*
* @author hanabi
* @date 2023-09-08
*/
@Service
public class MessageTemplateServiceImpl extends ServiceImpl<MessageTemplateMapper, MessageTemplate> implements IMessageTemplateService {
@Autowired
private MessageTemplateMapper messageTemplateMapper;
@Autowired
private XxlJobService xxlJobService;
@Autowired | private DataUtil dataUtil; | 9 | 2023-12-04 05:10:13+00:00 | 12k |
ydb-platform/yoj-project | repository/src/test/java/tech/ydb/yoj/repository/db/testcaller/TestDbTxCaller.java | [
{
"identifier": "IsolationLevel",
"path": "repository/src/main/java/tech/ydb/yoj/repository/db/IsolationLevel.java",
"snippet": "public enum IsolationLevel {\n /**\n * All transactions are serialized one-by-one. If the DB detects a write collision among\n * several concurrent transactions, on... | import lombok.RequiredArgsConstructor;
import tech.ydb.yoj.repository.db.IsolationLevel;
import tech.ydb.yoj.repository.db.Repository;
import tech.ydb.yoj.repository.db.RepositoryTransaction;
import tech.ydb.yoj.repository.db.StdTxManager;
import tech.ydb.yoj.repository.db.StdTxManagerTest;
import tech.ydb.yoj.repository.db.Tx;
import tech.ydb.yoj.repository.db.TxOptions;
import tech.ydb.yoj.repository.db.cache.TransactionLocal;
import tech.ydb.yoj.repository.testcaller.TestTxCaller;
import java.util.Set;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | 8,471 | package tech.ydb.yoj.repository.db.testcaller;
/**
* Part of {@link StdTxManagerTest}.
* This is a copy of {@link TestTxCaller}
* for testing calls from different packages.
*/
@RequiredArgsConstructor
public class TestDbTxCaller {
private final boolean useNewTxNameGeneration;
private final String explicitName;
private final Set<String> skipCallerPackages;
public TestDbTxCaller(boolean useNewTxNameGeneration, String explicitName) {
this(useNewTxNameGeneration, explicitName, Set.of());
}
public String getTxName() {
var repo = mock(Repository.class);
var rt = mock(RepositoryTransaction.class);
when(rt.getTransactionLocal()).thenReturn(new TransactionLocal(TxOptions.create(IsolationLevel.SERIALIZABLE_READ_WRITE)));
when(repo.startTransaction(any(TxOptions.class))).thenReturn(rt);
| package tech.ydb.yoj.repository.db.testcaller;
/**
* Part of {@link StdTxManagerTest}.
* This is a copy of {@link TestTxCaller}
* for testing calls from different packages.
*/
@RequiredArgsConstructor
public class TestDbTxCaller {
private final boolean useNewTxNameGeneration;
private final String explicitName;
private final Set<String> skipCallerPackages;
public TestDbTxCaller(boolean useNewTxNameGeneration, String explicitName) {
this(useNewTxNameGeneration, explicitName, Set.of());
}
public String getTxName() {
var repo = mock(Repository.class);
var rt = mock(RepositoryTransaction.class);
when(rt.getTransactionLocal()).thenReturn(new TransactionLocal(TxOptions.create(IsolationLevel.SERIALIZABLE_READ_WRITE)));
when(repo.startTransaction(any(TxOptions.class))).thenReturn(rt);
| var txGenerationBackup = StdTxManager.useNewTxNameGeneration; | 3 | 2023-12-05 15:57:58+00:00 | 12k |
Vera-Firefly/PojavLauncher-Experimental-Edition | app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/SearchModFragment.java | [
{
"identifier": "ModItemAdapter",
"path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/modloaders/modpacks/ModItemAdapter.java",
"snippet": "public class ModItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements TaskCountListener {\n private static final ModItem[] MOD_IT... | import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.math.MathUtils;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.modloaders.modpacks.ModItemAdapter;
import net.kdt.pojavlaunch.modloaders.modpacks.api.CommonApi;
import net.kdt.pojavlaunch.modloaders.modpacks.api.ModpackApi;
import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters;
import net.kdt.pojavlaunch.profiles.VersionSelectorDialog;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; | 7,951 | package net.kdt.pojavlaunch.fragments;
public class SearchModFragment extends Fragment implements ModItemAdapter.SearchResultCallback {
public static final String TAG = "SearchModFragment";
private View mOverlay;
private float mOverlayTopCache; // Padding cache reduce resource lookup
private final RecyclerView.OnScrollListener mOverlayPositionListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
mOverlay.setY(MathUtils.clamp(mOverlay.getY() - dy, -mOverlay.getHeight(), mOverlayTopCache));
}
};
private EditText mSearchEditText;
private ImageButton mFilterButton;
private RecyclerView mRecyclerview;
private ModItemAdapter mModItemAdapter;
private ProgressBar mSearchProgressBar;
private TextView mStatusTextView;
private ColorStateList mDefaultTextColor;
private ModpackApi modpackApi;
private final SearchFilters mSearchFilters;
public SearchModFragment(){
super(R.layout.fragment_mod_search);
mSearchFilters = new SearchFilters();
mSearchFilters.isModpack = true;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
modpackApi = new CommonApi(context.getString(R.string.curseforge_api_key));
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
// You can only access resources after attaching to current context
mModItemAdapter = new ModItemAdapter(getResources(), modpackApi, this);
ProgressKeeper.addTaskCountListener(mModItemAdapter);
mOverlayTopCache = getResources().getDimension(R.dimen.fragment_padding_medium);
mOverlay = view.findViewById(R.id.search_mod_overlay);
mSearchEditText = view.findViewById(R.id.search_mod_edittext);
mSearchProgressBar = view.findViewById(R.id.search_mod_progressbar);
mRecyclerview = view.findViewById(R.id.search_mod_list);
mStatusTextView = view.findViewById(R.id.search_mod_status_text);
mFilterButton = view.findViewById(R.id.search_mod_filter);
mDefaultTextColor = mStatusTextView.getTextColors();
mRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerview.setAdapter(mModItemAdapter);
mRecyclerview.addOnScrollListener(mOverlayPositionListener);
mSearchEditText.setOnEditorActionListener((v, actionId, event) -> {
mSearchProgressBar.setVisibility(View.VISIBLE);
mSearchFilters.name = mSearchEditText.getText().toString();
mModItemAdapter.performSearchQuery(mSearchFilters);
return true;
});
mOverlay.post(()->{
int overlayHeight = mOverlay.getHeight();
mRecyclerview.setPadding(mRecyclerview.getPaddingLeft(),
mRecyclerview.getPaddingTop() + overlayHeight,
mRecyclerview.getPaddingRight(),
mRecyclerview.getPaddingBottom());
});
mFilterButton.setOnClickListener(v -> displayFilterDialog());
}
@Override
public void onDestroyView() {
super.onDestroyView();
ProgressKeeper.removeTaskCountListener(mModItemAdapter);
mRecyclerview.removeOnScrollListener(mOverlayPositionListener);
}
@Override
public void onSearchFinished() {
mSearchProgressBar.setVisibility(View.GONE);
mStatusTextView.setVisibility(View.GONE);
}
@Override
public void onSearchError(int error) {
mSearchProgressBar.setVisibility(View.GONE);
mStatusTextView.setVisibility(View.VISIBLE);
switch (error) {
case ERROR_INTERNAL:
mStatusTextView.setTextColor(Color.RED);
mStatusTextView.setText(R.string.search_modpack_error);
break;
case ERROR_NO_RESULTS:
mStatusTextView.setTextColor(mDefaultTextColor);
mStatusTextView.setText(R.string.search_modpack_no_result);
break;
}
}
private void displayFilterDialog() {
AlertDialog dialog = new AlertDialog.Builder(requireContext())
.setView(R.layout.dialog_mod_filters)
.create();
// setup the view behavior
dialog.setOnShowListener(dialogInterface -> {
TextView mSelectedVersion = dialog.findViewById(R.id.search_mod_selected_mc_version_textview);
Button mSelectVersionButton = dialog.findViewById(R.id.search_mod_mc_version_button);
Button mApplyButton = dialog.findViewById(R.id.search_mod_apply_filters);
assert mSelectVersionButton != null;
assert mSelectedVersion != null;
assert mApplyButton != null;
// Setup the expendable list behavior | package net.kdt.pojavlaunch.fragments;
public class SearchModFragment extends Fragment implements ModItemAdapter.SearchResultCallback {
public static final String TAG = "SearchModFragment";
private View mOverlay;
private float mOverlayTopCache; // Padding cache reduce resource lookup
private final RecyclerView.OnScrollListener mOverlayPositionListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
mOverlay.setY(MathUtils.clamp(mOverlay.getY() - dy, -mOverlay.getHeight(), mOverlayTopCache));
}
};
private EditText mSearchEditText;
private ImageButton mFilterButton;
private RecyclerView mRecyclerview;
private ModItemAdapter mModItemAdapter;
private ProgressBar mSearchProgressBar;
private TextView mStatusTextView;
private ColorStateList mDefaultTextColor;
private ModpackApi modpackApi;
private final SearchFilters mSearchFilters;
public SearchModFragment(){
super(R.layout.fragment_mod_search);
mSearchFilters = new SearchFilters();
mSearchFilters.isModpack = true;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
modpackApi = new CommonApi(context.getString(R.string.curseforge_api_key));
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
// You can only access resources after attaching to current context
mModItemAdapter = new ModItemAdapter(getResources(), modpackApi, this);
ProgressKeeper.addTaskCountListener(mModItemAdapter);
mOverlayTopCache = getResources().getDimension(R.dimen.fragment_padding_medium);
mOverlay = view.findViewById(R.id.search_mod_overlay);
mSearchEditText = view.findViewById(R.id.search_mod_edittext);
mSearchProgressBar = view.findViewById(R.id.search_mod_progressbar);
mRecyclerview = view.findViewById(R.id.search_mod_list);
mStatusTextView = view.findViewById(R.id.search_mod_status_text);
mFilterButton = view.findViewById(R.id.search_mod_filter);
mDefaultTextColor = mStatusTextView.getTextColors();
mRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
mRecyclerview.setAdapter(mModItemAdapter);
mRecyclerview.addOnScrollListener(mOverlayPositionListener);
mSearchEditText.setOnEditorActionListener((v, actionId, event) -> {
mSearchProgressBar.setVisibility(View.VISIBLE);
mSearchFilters.name = mSearchEditText.getText().toString();
mModItemAdapter.performSearchQuery(mSearchFilters);
return true;
});
mOverlay.post(()->{
int overlayHeight = mOverlay.getHeight();
mRecyclerview.setPadding(mRecyclerview.getPaddingLeft(),
mRecyclerview.getPaddingTop() + overlayHeight,
mRecyclerview.getPaddingRight(),
mRecyclerview.getPaddingBottom());
});
mFilterButton.setOnClickListener(v -> displayFilterDialog());
}
@Override
public void onDestroyView() {
super.onDestroyView();
ProgressKeeper.removeTaskCountListener(mModItemAdapter);
mRecyclerview.removeOnScrollListener(mOverlayPositionListener);
}
@Override
public void onSearchFinished() {
mSearchProgressBar.setVisibility(View.GONE);
mStatusTextView.setVisibility(View.GONE);
}
@Override
public void onSearchError(int error) {
mSearchProgressBar.setVisibility(View.GONE);
mStatusTextView.setVisibility(View.VISIBLE);
switch (error) {
case ERROR_INTERNAL:
mStatusTextView.setTextColor(Color.RED);
mStatusTextView.setText(R.string.search_modpack_error);
break;
case ERROR_NO_RESULTS:
mStatusTextView.setTextColor(mDefaultTextColor);
mStatusTextView.setText(R.string.search_modpack_no_result);
break;
}
}
private void displayFilterDialog() {
AlertDialog dialog = new AlertDialog.Builder(requireContext())
.setView(R.layout.dialog_mod_filters)
.create();
// setup the view behavior
dialog.setOnShowListener(dialogInterface -> {
TextView mSelectedVersion = dialog.findViewById(R.id.search_mod_selected_mc_version_textview);
Button mSelectVersionButton = dialog.findViewById(R.id.search_mod_mc_version_button);
Button mApplyButton = dialog.findViewById(R.id.search_mod_apply_filters);
assert mSelectVersionButton != null;
assert mSelectedVersion != null;
assert mApplyButton != null;
// Setup the expendable list behavior | mSelectVersionButton.setOnClickListener(v -> VersionSelectorDialog.open(v.getContext(), true, (id, snapshot)-> mSelectedVersion.setText(id))); | 4 | 2023-12-01 16:16:12+00:00 | 12k |
kawashirov/distant-horizons | forge/src/main/java/com/seibel/distanthorizons/forge/mixins/client/MixinLevelRenderer.java | [
{
"identifier": "McObjectConverter",
"path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/McObjectConverter.java",
"snippet": "public class McObjectConverter\n{\n\tprivate static int bufferIndex(int x, int y)\n\t{\n\t\treturn y * 4 + x;\n\t}\n\t/** Taken from Minecraft's com.mojang.m... | import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Matrix4f;
import net.minecraft.client.Camera;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.LightTexture;
import org.joml.Matrix4f;
import com.seibel.distanthorizons.common.wrappers.McObjectConverter;
import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper;
import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper;
import com.seibel.distanthorizons.core.config.Config;
import com.seibel.distanthorizons.core.api.internal.ClientApi;
import com.seibel.distanthorizons.coreapi.util.math.Mat4f;
import net.minecraft.client.Camera;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.world.level.lighting.LevelLightEngine;
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.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.nio.FloatBuffer;
import org.lwjgl.opengl.GL15; | 8,912 | /*
* This file is part of the Distant Horizons mod
* licensed under the GNU LGPL v3 License.
*
* Copyright (C) 2020-2023 James Seibel
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.seibel.distanthorizons.forge.mixins.client;
#if PRE_MC_1_19_4
#else
#endif
import com.seibel.distanthorizons.common.rendering.SeamlessOverdraw;
#if PRE_MC_1_17_1
#endif
/**
* This class is used to mix in my rendering code
* before Minecraft starts rendering blocks.
* If this wasn't done, and we used Forge's
* render last event, the LODs would render on top
* of the normal terrain. <br><br>
*
* This is also the mixin for rendering the clouds
*
* @author coolGi
* @author James Seibel
* @version 12-31-2021
*/
@Mixin(LevelRenderer.class)
public class MixinLevelRenderer
{
@Shadow
private ClientLevel level;
@Unique
private static float previousPartialTicks = 0;
// TODO: Is there any reason why this is here? Can it be deleted?
public MixinLevelRenderer()
{
throw new NullPointerException("Null cannot be cast to non-null type.");
}
#if PRE_MC_1_17_1
@Inject(at = @At("RETURN"), method = "renderSky(Lcom/mojang/blaze3d/vertex/PoseStack;F)V")
private void renderSky(PoseStack matrixStackIn, float partialTicks, CallbackInfo callback)
#else
@Inject(method = "renderClouds", at = @At("HEAD"), cancellable = true)
public void renderClouds(PoseStack poseStack, Matrix4f projectionMatrix, float partialTicks, double cameraX, double cameraY, double cameraZ, CallbackInfo ci)
#endif
{
// get the partial ticks since renderBlockLayer doesn't
// have access to them
previousPartialTicks = partialTicks;
}
// TODO: Can we move this to forge's client proxy similarly to how fabric does it
#if PRE_MC_1_17_1
@Inject(at = @At("HEAD"),
method = "renderChunkLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDD)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack matrixStackIn, double xIn, double yIn, double zIn, CallbackInfo callback)
#elif PRE_MC_1_19_4
@Inject(at = @At("HEAD"),
method = "renderChunkLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDDLcom/mojang/math/Matrix4f;)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack modelViewMatrixStack, double cameraXBlockPos, double cameraYBlockPos, double cameraZBlockPos, Matrix4f projectionMatrix, CallbackInfo callback)
#elif PRE_MC_1_20_2
@Inject(at = @At("HEAD"),
method = "renderChunkLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDDLorg/joml/Matrix4f;)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack modelViewMatrixStack, double cameraXBlockPos, double cameraYBlockPos, double cameraZBlockPos, Matrix4f projectionMatrix, CallbackInfo callback)
#else
@Inject(at = @At("HEAD"),
method = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDDLorg/joml/Matrix4f;)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack modelViewMatrixStack, double camX, double camY, double camZ, Matrix4f projectionMatrix, CallbackInfo callback)
#endif
{
// get MC's model view and projection matrices
#if MC_1_16_5
// get the matrices from the OpenGL fixed pipeline
float[] mcProjMatrixRaw = new float[16];
GL15.glGetFloatv(GL15.GL_PROJECTION_MATRIX, mcProjMatrixRaw);
Mat4f mcProjectionMatrix = new Mat4f(mcProjMatrixRaw);
mcProjectionMatrix.transpose();
| /*
* This file is part of the Distant Horizons mod
* licensed under the GNU LGPL v3 License.
*
* Copyright (C) 2020-2023 James Seibel
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.seibel.distanthorizons.forge.mixins.client;
#if PRE_MC_1_19_4
#else
#endif
import com.seibel.distanthorizons.common.rendering.SeamlessOverdraw;
#if PRE_MC_1_17_1
#endif
/**
* This class is used to mix in my rendering code
* before Minecraft starts rendering blocks.
* If this wasn't done, and we used Forge's
* render last event, the LODs would render on top
* of the normal terrain. <br><br>
*
* This is also the mixin for rendering the clouds
*
* @author coolGi
* @author James Seibel
* @version 12-31-2021
*/
@Mixin(LevelRenderer.class)
public class MixinLevelRenderer
{
@Shadow
private ClientLevel level;
@Unique
private static float previousPartialTicks = 0;
// TODO: Is there any reason why this is here? Can it be deleted?
public MixinLevelRenderer()
{
throw new NullPointerException("Null cannot be cast to non-null type.");
}
#if PRE_MC_1_17_1
@Inject(at = @At("RETURN"), method = "renderSky(Lcom/mojang/blaze3d/vertex/PoseStack;F)V")
private void renderSky(PoseStack matrixStackIn, float partialTicks, CallbackInfo callback)
#else
@Inject(method = "renderClouds", at = @At("HEAD"), cancellable = true)
public void renderClouds(PoseStack poseStack, Matrix4f projectionMatrix, float partialTicks, double cameraX, double cameraY, double cameraZ, CallbackInfo ci)
#endif
{
// get the partial ticks since renderBlockLayer doesn't
// have access to them
previousPartialTicks = partialTicks;
}
// TODO: Can we move this to forge's client proxy similarly to how fabric does it
#if PRE_MC_1_17_1
@Inject(at = @At("HEAD"),
method = "renderChunkLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDD)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack matrixStackIn, double xIn, double yIn, double zIn, CallbackInfo callback)
#elif PRE_MC_1_19_4
@Inject(at = @At("HEAD"),
method = "renderChunkLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDDLcom/mojang/math/Matrix4f;)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack modelViewMatrixStack, double cameraXBlockPos, double cameraYBlockPos, double cameraZBlockPos, Matrix4f projectionMatrix, CallbackInfo callback)
#elif PRE_MC_1_20_2
@Inject(at = @At("HEAD"),
method = "renderChunkLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDDLorg/joml/Matrix4f;)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack modelViewMatrixStack, double cameraXBlockPos, double cameraYBlockPos, double cameraZBlockPos, Matrix4f projectionMatrix, CallbackInfo callback)
#else
@Inject(at = @At("HEAD"),
method = "Lnet/minecraft/client/renderer/LevelRenderer;renderSectionLayer(Lnet/minecraft/client/renderer/RenderType;Lcom/mojang/blaze3d/vertex/PoseStack;DDDLorg/joml/Matrix4f;)V",
cancellable = true)
private void renderChunkLayer(RenderType renderType, PoseStack modelViewMatrixStack, double camX, double camY, double camZ, Matrix4f projectionMatrix, CallbackInfo callback)
#endif
{
// get MC's model view and projection matrices
#if MC_1_16_5
// get the matrices from the OpenGL fixed pipeline
float[] mcProjMatrixRaw = new float[16];
GL15.glGetFloatv(GL15.GL_PROJECTION_MATRIX, mcProjMatrixRaw);
Mat4f mcProjectionMatrix = new Mat4f(mcProjMatrixRaw);
mcProjectionMatrix.transpose();
| Mat4f mcModelViewMatrix = McObjectConverter.Convert(matrixStackIn.last().pose()); | 0 | 2023-12-04 11:41:46+00:00 | 12k |
hmcts/juror-sql-support-library | src/main/java/uk/gov/hmcts/juror/support/sql/generators/JurorPoolGeneratorUtil.java | [
{
"identifier": "ExcusableCode",
"path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/ExcusableCode.java",
"snippet": "@Getter\npublic enum ExcusableCode {\n\n CRIMINAL_RECORD(\"K\"),\n DECEASED(\"D\"),\n OVER_69(\"V\"),\n RECENTLY_SERVED(\"S\"),\n THE_FORCES(\"F\"),\n MEDICAL_... | import uk.gov.hmcts.juror.support.generation.generators.value.FixedValueGeneratorImpl;
import uk.gov.hmcts.juror.support.generation.generators.value.LocalDateGeneratorImpl;
import uk.gov.hmcts.juror.support.generation.generators.value.NullValueGeneratorImpl;
import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl;
import uk.gov.hmcts.juror.support.sql.entity.ExcusableCode;
import uk.gov.hmcts.juror.support.sql.entity.Juror;
import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator;
import uk.gov.hmcts.juror.support.sql.entity.JurorStatus;
import uk.gov.hmcts.juror.support.sql.entity.PoolRequest;
import uk.gov.hmcts.juror.support.sql.service.SqlSupportService;
import java.time.LocalDate;
import java.util.Arrays; | 7,450 | package uk.gov.hmcts.juror.support.sql.generators;
public class JurorPoolGeneratorUtil {
public static JurorPoolGenerator summoned(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.SUMMONED);
}
public static JurorPoolGenerator responded(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.RESPONDED);
}
public static JurorPoolGenerator panel(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.PANEL);
}
public static JurorPoolGenerator juror(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.JUROR);
}
public static JurorPoolGenerator excused(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator disqualified(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator deferred(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED);
//Next date set to date you are deferred too?? -- check
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>(
Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList()));
jurorPoolGenerator.setDeferralDate(new LocalDateGeneratorImpl(
LocalDate.now().minusDays(200),
LocalDate.now()));
//Is active is set to false if you are moved to a new pool else this is still true if you are awaiting new pool
return jurorPoolGenerator;
}
public static JurorPoolGenerator reassigned(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.REASSIGNED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setIsActive(new FixedValueGeneratorImpl<>(false));
return jurorPoolGenerator;
}
public static JurorPoolGenerator transferred(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.TRANSFERRED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setTransferDate(
new LocalDateGeneratorImpl(
LocalDate.now().minusDays(200),
LocalDate.now())
);
return jurorPoolGenerator;
}
public static JurorPoolGenerator additionalInfo(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.ADDITIONAL_INFO);
}
public static JurorPoolGenerator failedToAttend(boolean isCourtOwned) {
JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.FAILED_TO_ATTEND);
generator.setNoAttendances(new FixedValueGeneratorImpl<>(0));
generator.setNoAttended(new FixedValueGeneratorImpl<>(0));
return generator;
}
public static JurorPoolGenerator completed(boolean isCourtOwned) {
JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.COMPLETED);
generator.setNextDate(new NullValueGeneratorImpl<>());
return generator;
}
private static JurorPoolGenerator createStandard(boolean isCourtOwned, JurorStatus jurorStatus) {
JurorPoolGenerator generator = new JurorPoolGenerator();
generator.setStatus(new FixedValueGeneratorImpl<>(jurorStatus.getId()));
if (isCourtOwned) {
generator.setOwner(new RandomFromCollectionGeneratorImpl<>(SqlSupportService.getCourtOwners()));
} else {
generator.setOwner(new FixedValueGeneratorImpl<>("400"));
}
return generator;
}
| package uk.gov.hmcts.juror.support.sql.generators;
public class JurorPoolGeneratorUtil {
public static JurorPoolGenerator summoned(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.SUMMONED);
}
public static JurorPoolGenerator responded(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.RESPONDED);
}
public static JurorPoolGenerator panel(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.PANEL);
}
public static JurorPoolGenerator juror(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.JUROR);
}
public static JurorPoolGenerator excused(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator disqualified(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator deferred(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED);
//Next date set to date you are deferred too?? -- check
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>(
Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList()));
jurorPoolGenerator.setDeferralDate(new LocalDateGeneratorImpl(
LocalDate.now().minusDays(200),
LocalDate.now()));
//Is active is set to false if you are moved to a new pool else this is still true if you are awaiting new pool
return jurorPoolGenerator;
}
public static JurorPoolGenerator reassigned(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.REASSIGNED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setIsActive(new FixedValueGeneratorImpl<>(false));
return jurorPoolGenerator;
}
public static JurorPoolGenerator transferred(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.TRANSFERRED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setTransferDate(
new LocalDateGeneratorImpl(
LocalDate.now().minusDays(200),
LocalDate.now())
);
return jurorPoolGenerator;
}
public static JurorPoolGenerator additionalInfo(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.ADDITIONAL_INFO);
}
public static JurorPoolGenerator failedToAttend(boolean isCourtOwned) {
JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.FAILED_TO_ATTEND);
generator.setNoAttendances(new FixedValueGeneratorImpl<>(0));
generator.setNoAttended(new FixedValueGeneratorImpl<>(0));
return generator;
}
public static JurorPoolGenerator completed(boolean isCourtOwned) {
JurorPoolGenerator generator = createStandard(isCourtOwned, JurorStatus.COMPLETED);
generator.setNextDate(new NullValueGeneratorImpl<>());
return generator;
}
private static JurorPoolGenerator createStandard(boolean isCourtOwned, JurorStatus jurorStatus) {
JurorPoolGenerator generator = new JurorPoolGenerator();
generator.setStatus(new FixedValueGeneratorImpl<>(jurorStatus.getId()));
if (isCourtOwned) {
generator.setOwner(new RandomFromCollectionGeneratorImpl<>(SqlSupportService.getCourtOwners()));
} else {
generator.setOwner(new FixedValueGeneratorImpl<>("400"));
}
return generator;
}
| public static JurorPoolGenerator create(Juror juror, PoolRequest pool) { | 1 | 2023-12-01 11:38:42+00:00 | 12k |
vvbbnn00/JavaWeb-CanteenSystem | JavaBackend/src/main/java/cn/vvbbnn00/canteen/controller/rest/UserResource.java | [
{
"identifier": "UserChangePasswordRequest",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dto/request/UserChangePasswordRequest.java",
"snippet": "@Data\n@JavaBean\npublic class UserChangePasswordRequest {\n @NotBlank(message = \"旧密码不能为空\")\n private String oldPassword;\n\n @NotBlank(... | import cn.vvbbnn00.canteen.annotation.CheckRole;
import cn.vvbbnn00.canteen.dto.request.UserChangePasswordRequest;
import cn.vvbbnn00.canteen.dto.request.UserListRequest;
import cn.vvbbnn00.canteen.dto.response.BasicDataResponse;
import cn.vvbbnn00.canteen.dto.response.BasicListResponse;
import cn.vvbbnn00.canteen.dto.response.BasicResponse;
import cn.vvbbnn00.canteen.model.User;
import cn.vvbbnn00.canteen.service.UserService;
import cn.vvbbnn00.canteen.util.RequestValidatorUtils;
import jakarta.enterprise.context.RequestScoped;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.SecurityContext; | 7,367 | package cn.vvbbnn00.canteen.controller.rest;
@Path("/user")
@RequestScoped
public class UserResource {
@Context
SecurityContext securityContext;
UserService userService = new UserService();
@POST
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
@CheckRole("admin")
public BasicListResponse restListUser( | package cn.vvbbnn00.canteen.controller.rest;
@Path("/user")
@RequestScoped
public class UserResource {
@Context
SecurityContext securityContext;
UserService userService = new UserService();
@POST
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
@CheckRole("admin")
public BasicListResponse restListUser( | UserListRequest userListRequest | 1 | 2023-12-01 04:55:12+00:00 | 12k |
SuperRicky14/TpaPlusPlus | src/main/java/net/superricky/tpaplusplus/Main.java | [
{
"identifier": "Config",
"path": "src/main/java/net/superricky/tpaplusplus/util/configuration/Config.java",
"snippet": "public class Config {\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static fin... | import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.superricky.tpaplusplus.util.configuration.Config;
import net.superricky.tpaplusplus.util.configuration.Messages; | 9,879 | package net.superricky.tpaplusplus;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(Main.MOD_ID)
public class Main {
// Our mod id
public static final String MOD_ID = "tpaplusplus";
public static final String MOD_VERSION = "1.3-1.20.x-BETA-3";
public Main() {
MinecraftForge.EVENT_BUS.register(this);
// Instantiate the mod's messages | package net.superricky.tpaplusplus;
// The value here should match an entry in the META-INF/mods.toml file
@Mod(Main.MOD_ID)
public class Main {
// Our mod id
public static final String MOD_ID = "tpaplusplus";
public static final String MOD_VERSION = "1.3-1.20.x-BETA-3";
public Main() {
MinecraftForge.EVENT_BUS.register(this);
// Instantiate the mod's messages | ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Messages.SPEC, "tpaplusplus-messages.toml"); | 1 | 2023-12-02 05:41:24+00:00 | 12k |
shawn-sheep/Activity_Diary | app/src/main/java/de/rampro/activitydiary/helpers/LocationHelper.java | [
{
"identifier": "ActivityDiaryApplication",
"path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java",
"snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtili... | import android.os.Looper;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import de.rampro.activitydiary.ActivityDiaryApplication;
import de.rampro.activitydiary.db.ActivityDiaryContract;
import de.rampro.activitydiary.ui.settings.SettingsActivity;
import android.Manifest;
import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle; | 9,989 | /*
* ActivityDiary
*
* Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de
*
* 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 de.rampro.activitydiary.helpers;
public class LocationHelper extends AsyncQueryHandler implements LocationListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = LocationHelper.class.getName();
public static final LocationHelper helper = new LocationHelper();
private static final long MIN_TIME_DEF = 5; // for now every 5 minutes
private static final long MIN_TIME_FACTOR = 1000 * 60;
private static final float MIN_DISTANCE_DEF = 50.0f;
private long minTime;
private float minDist;
private String setting;
private Location currentLocation;
LocationManager locationManager = (LocationManager) ActivityDiaryApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext());
public LocationHelper() {
super(ActivityDiaryApplication.getAppContext().getContentResolver());
currentLocation = new Location("DiaryLocation");
updatePreferences();
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
public Location getCurrentLocation(){
return currentLocation;
}
void updateLocation() {
if (setting.equals("off")) {
// do nothing
} else {
int permissionCheckFine = PackageManager.PERMISSION_DENIED;
int permissionCheckCoarse = PackageManager.PERMISSION_DENIED;
if(setting.equals("gps") && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
permissionCheckFine = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(),
Manifest.permission.ACCESS_FINE_LOCATION);
permissionCheckCoarse = permissionCheckFine;
}else if(locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)){
permissionCheckCoarse = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
}
if(permissionCheckFine == PackageManager.PERMISSION_GRANTED){
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper());
}else if(permissionCheckCoarse == PackageManager.PERMISSION_GRANTED){
String locationProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper());
}
}
}
/**
* Called when the location has changed.
* <p>
* <p> There are no restrictions on the use of the supplied Location object.
*
* @param location The new location, as a Location object.
*/
@Override
public void onLocationChanged(Location location) {
ContentValues values = new ContentValues();
currentLocation = location; | /*
* ActivityDiary
*
* Copyright (C) 2018 Raphael Mack http://www.raphael-mack.de
*
* 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 de.rampro.activitydiary.helpers;
public class LocationHelper extends AsyncQueryHandler implements LocationListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = LocationHelper.class.getName();
public static final LocationHelper helper = new LocationHelper();
private static final long MIN_TIME_DEF = 5; // for now every 5 minutes
private static final long MIN_TIME_FACTOR = 1000 * 60;
private static final float MIN_DISTANCE_DEF = 50.0f;
private long minTime;
private float minDist;
private String setting;
private Location currentLocation;
LocationManager locationManager = (LocationManager) ActivityDiaryApplication.getAppContext().getSystemService(Context.LOCATION_SERVICE);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext());
public LocationHelper() {
super(ActivityDiaryApplication.getAppContext().getContentResolver());
currentLocation = new Location("DiaryLocation");
updatePreferences();
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
}
public Location getCurrentLocation(){
return currentLocation;
}
void updateLocation() {
if (setting.equals("off")) {
// do nothing
} else {
int permissionCheckFine = PackageManager.PERMISSION_DENIED;
int permissionCheckCoarse = PackageManager.PERMISSION_DENIED;
if(setting.equals("gps") && locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
permissionCheckFine = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(),
Manifest.permission.ACCESS_FINE_LOCATION);
permissionCheckCoarse = permissionCheckFine;
}else if(locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)){
permissionCheckCoarse = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(),
Manifest.permission.ACCESS_COARSE_LOCATION);
}
if(permissionCheckFine == PackageManager.PERMISSION_GRANTED){
String locationProvider = LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper());
}else if(permissionCheckCoarse == PackageManager.PERMISSION_GRANTED){
String locationProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(locationProvider, minTime, minDist, this, Looper.getMainLooper());
}
}
}
/**
* Called when the location has changed.
* <p>
* <p> There are no restrictions on the use of the supplied Location object.
*
* @param location The new location, as a Location object.
*/
@Override
public void onLocationChanged(Location location) {
ContentValues values = new ContentValues();
currentLocation = location; | values.put(ActivityDiaryContract.DiaryLocation.TIMESTAMP, location.getTime()); | 1 | 2023-12-02 12:36:40+00:00 | 12k |
RabbitHareLu/K-Tools | frontend/src/main/java/com/ktools/frontend/frame/JDBCConnectionFrame.java | [
{
"identifier": "KToolsContext",
"path": "warehouse/src/main/java/com/ktools/warehouse/KToolsContext.java",
"snippet": "@Getter\npublic class KToolsContext {\n\n private static volatile KToolsContext INSTANCE;\n\n private final MybatisContext mybatisContext;\n\n private final Properties propert... | import com.ktools.warehouse.KToolsContext;
import com.ktools.frontend.action.CancelDisposeFrameAction;
import com.ktools.frontend.action.TestConnectionAction;
import com.ktools.frontend.action.TreeJDBCNodeAction;
import com.ktools.warehouse.api.DataSourceApi;
import com.ktools.frontend.common.utils.BoxUtil;
import com.ktools.frontend.component.ImageLoad;
import com.ktools.frontend.component.Tree;
import com.ktools.warehouse.exception.KToolException;
import com.ktools.warehouse.manager.datasource.model.KDataSourceMetadata;
import com.ktools.warehouse.mybatis.entity.TreeEntity;
import com.ktools.frontend.panel.AdvancedPanel;
import com.ktools.frontend.panel.RegularPanel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.util.Objects; | 7,662 | package com.ktools.frontend.frame;
/**
* @author lsl
* @version 1.0
* @date 2023年12月18日 17:34
*/
@Slf4j
@Data
public class JDBCConnectionFrame extends JFrame {
public static boolean openFlag = true;
private static final int WIDTH = 600;
private static final int HEIGHT = 700;
private KDataSourceMetadata kDataSourceMetadata;
private TreeEntity treeEntity;
private TreePath treePath;
private RegularPanel regularPanel;
private AdvancedPanel advancedPanel;
private JTextField nameField;
private JTextField commentField;
public JDBCConnectionFrame() {
Tree instance = Tree.getInstance();
this.treePath = instance.getCurrentTreePath();
this.treeEntity = instance.getCurrentTreeEntity(treePath);
try {
this.kDataSourceMetadata = KToolsContext.getInstance().getApi(DataSourceApi.class).getMetadata(treeEntity.getNodeType());
} catch (KToolException e) {
throw new RuntimeException(e);
}
setTitle("编辑" + kDataSourceMetadata.getName() + "连接");
frameStartInit();
initEdit();
frameEndInit();
}
public JDBCConnectionFrame(KDataSourceMetadata kDataSourceMetadata) {
Tree instance = Tree.getInstance();
this.kDataSourceMetadata = kDataSourceMetadata;
this.treePath = instance.getCurrentTreePath();
setTitle("新建" + kDataSourceMetadata.getName() + "连接");
frameStartInit();
initNew();
frameEndInit();
}
private void frameStartInit() {
openFlag = false;
setIconImage(ImageLoad.getInstance().buildIcon(kDataSourceMetadata.getLogo()).getImage());
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
closeAction();
}
private void frameEndInit() {
setVisible(true);
}
private void initEdit() {
if (Objects.nonNull(treeEntity)) {
Box publicBox = Box.createVerticalBox();
BoxUtil.addVerticalStrut(publicBox, 30);
nameField = initSubBox(publicBox, "名称: ");
nameField.setText(treeEntity.getNodeName());
BoxUtil.addVerticalStrut(publicBox, 30);
commentField = initSubBox(publicBox, "注释: ");
commentField.setText(treeEntity.getNodeComment());
BoxUtil.addVerticalStrut(publicBox, 30);
add(publicBox, BorderLayout.NORTH);
Box tabBox = Box.createHorizontalBox();
BoxUtil.addHorizontalStrut(tabBox, 30);
JTabbedPane tabbedPane = new JTabbedPane();
regularPanel = new RegularPanel(treeEntity);
advancedPanel = new AdvancedPanel(treeEntity, kDataSourceMetadata);
tabbedPane.addTab("常规", null, regularPanel, "常规");
tabbedPane.addTab("高级", null, advancedPanel, "高级");
tabBox.add(tabbedPane);
BoxUtil.addHorizontalStrut(tabBox, 30);
add(tabBox, BorderLayout.CENTER);
Box southBox = Box.createVerticalBox();
Box buttonBox = Box.createHorizontalBox();
BoxUtil.addHorizontalStrut(buttonBox, 30);
JButton testButton = new JButton("测试连接");
testButton.addActionListener(new TestConnectionAction(this));
buttonBox.add(testButton);
buttonBox.add(Box.createHorizontalGlue());
JButton okButton = new JButton("确认");
okButton.setBackground(new Color(53, 116, 240));
okButton.addActionListener(new TreeJDBCNodeAction(this));
buttonBox.add(okButton);
BoxUtil.addHorizontalStrut(buttonBox, 20);
JButton cancelButton = new JButton("取消"); | package com.ktools.frontend.frame;
/**
* @author lsl
* @version 1.0
* @date 2023年12月18日 17:34
*/
@Slf4j
@Data
public class JDBCConnectionFrame extends JFrame {
public static boolean openFlag = true;
private static final int WIDTH = 600;
private static final int HEIGHT = 700;
private KDataSourceMetadata kDataSourceMetadata;
private TreeEntity treeEntity;
private TreePath treePath;
private RegularPanel regularPanel;
private AdvancedPanel advancedPanel;
private JTextField nameField;
private JTextField commentField;
public JDBCConnectionFrame() {
Tree instance = Tree.getInstance();
this.treePath = instance.getCurrentTreePath();
this.treeEntity = instance.getCurrentTreeEntity(treePath);
try {
this.kDataSourceMetadata = KToolsContext.getInstance().getApi(DataSourceApi.class).getMetadata(treeEntity.getNodeType());
} catch (KToolException e) {
throw new RuntimeException(e);
}
setTitle("编辑" + kDataSourceMetadata.getName() + "连接");
frameStartInit();
initEdit();
frameEndInit();
}
public JDBCConnectionFrame(KDataSourceMetadata kDataSourceMetadata) {
Tree instance = Tree.getInstance();
this.kDataSourceMetadata = kDataSourceMetadata;
this.treePath = instance.getCurrentTreePath();
setTitle("新建" + kDataSourceMetadata.getName() + "连接");
frameStartInit();
initNew();
frameEndInit();
}
private void frameStartInit() {
openFlag = false;
setIconImage(ImageLoad.getInstance().buildIcon(kDataSourceMetadata.getLogo()).getImage());
setSize(WIDTH, HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setResizable(false);
closeAction();
}
private void frameEndInit() {
setVisible(true);
}
private void initEdit() {
if (Objects.nonNull(treeEntity)) {
Box publicBox = Box.createVerticalBox();
BoxUtil.addVerticalStrut(publicBox, 30);
nameField = initSubBox(publicBox, "名称: ");
nameField.setText(treeEntity.getNodeName());
BoxUtil.addVerticalStrut(publicBox, 30);
commentField = initSubBox(publicBox, "注释: ");
commentField.setText(treeEntity.getNodeComment());
BoxUtil.addVerticalStrut(publicBox, 30);
add(publicBox, BorderLayout.NORTH);
Box tabBox = Box.createHorizontalBox();
BoxUtil.addHorizontalStrut(tabBox, 30);
JTabbedPane tabbedPane = new JTabbedPane();
regularPanel = new RegularPanel(treeEntity);
advancedPanel = new AdvancedPanel(treeEntity, kDataSourceMetadata);
tabbedPane.addTab("常规", null, regularPanel, "常规");
tabbedPane.addTab("高级", null, advancedPanel, "高级");
tabBox.add(tabbedPane);
BoxUtil.addHorizontalStrut(tabBox, 30);
add(tabBox, BorderLayout.CENTER);
Box southBox = Box.createVerticalBox();
Box buttonBox = Box.createHorizontalBox();
BoxUtil.addHorizontalStrut(buttonBox, 30);
JButton testButton = new JButton("测试连接");
testButton.addActionListener(new TestConnectionAction(this));
buttonBox.add(testButton);
buttonBox.add(Box.createHorizontalGlue());
JButton okButton = new JButton("确认");
okButton.setBackground(new Color(53, 116, 240));
okButton.addActionListener(new TreeJDBCNodeAction(this));
buttonBox.add(okButton);
BoxUtil.addHorizontalStrut(buttonBox, 20);
JButton cancelButton = new JButton("取消"); | cancelButton.addActionListener(new CancelDisposeFrameAction()); | 1 | 2023-11-30 03:26:25+00:00 | 12k |
ChrisGenti/VPL | velocity/src/main/java/com/github/chrisgenti/vpl/velocity/VPLPlugin.java | [
{
"identifier": "PluginCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/PluginCommand.java",
"snippet": "public interface PluginCommand extends SimpleCommand {\n String name();\n\n default String usage() { return \"/\" + this.name(); };\n}"
},
{
"identi... | import com.github.chrisgenti.vpl.velocity.commands.PluginCommand;
import com.github.chrisgenti.vpl.velocity.commands.admin.VPLCommand;
import com.github.chrisgenti.vpl.velocity.commands.user.PremiumCommand;
import com.github.chrisgenti.vpl.velocity.configurations.config.ConfigFile;
import com.github.chrisgenti.vpl.velocity.configurations.language.LanguageFile;
import com.github.chrisgenti.vpl.velocity.data.DataProvider;
import com.github.chrisgenti.vpl.velocity.data.mysql.MySQLProvider;
import com.github.chrisgenti.vpl.velocity.listeners.Listener;
import com.github.chrisgenti.vpl.velocity.listeners.chat.ChatListener;
import com.github.chrisgenti.vpl.velocity.listeners.command.CommandListener;
import com.github.chrisgenti.vpl.velocity.listeners.disconnect.DisconnectListener;
import com.github.chrisgenti.vpl.velocity.listeners.login.PreLoginListener;
import com.github.chrisgenti.vpl.velocity.listeners.login.post.PostLoginListener;
import com.github.chrisgenti.vpl.velocity.listeners.message.PluginMessageListener;
import com.github.chrisgenti.vpl.velocity.listeners.profile.ProfileRequestListener;
import com.github.chrisgenti.vpl.velocity.listeners.server.InitialServerListener;
import com.github.chrisgenti.vpl.velocity.listeners.tab.TabCompleteListener;
import com.github.chrisgenti.vpl.velocity.players.PlayerManager;
import com.github.chrisgenti.vpl.velocity.servers.ServerManager;
import com.github.chrisgenti.vpl.velocity.tasks.PluginTask;
import com.github.chrisgenti.vpl.velocity.tasks.register.RegisterTask;
import com.google.inject.Inject;
import com.velocitypowered.api.command.CommandManager;
import com.velocitypowered.api.command.CommandMeta;
import com.velocitypowered.api.command.CommandSource;
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 com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.messages.LegacyChannelIdentifier;
import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier;
import lombok.Getter;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.slf4j.Logger;
import java.io.File;
import java.nio.file.Path;
import java.util.Arrays; | 10,283 | package com.github.chrisgenti.vpl.velocity;
@Plugin(
id = "vpl",
name = "VPL",
version = "1.0.0",
description = "",
authors = {"ChrisGenti"}
) @Getter
public class VPLPlugin {
public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create("vpl", "main");
public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier("vpl:main");
@Inject private ProxyServer proxy;
@Inject private Logger logger;
@Inject private EventManager eventManager;
@Inject @DataDirectory Path directory;
private ConfigFile configFile;
private LanguageFile languageFile;
private PlayerManager playerManager;
private ServerManager serverManager;
private DataProvider provider;
private PluginTask registerTask;
@Subscribe
public void onInitialization(ProxyInitializeEvent event) {
/*
* FILES
*/
this.configFile = new ConfigFile(directory.toFile(), "config.toml");
this.languageFile = new LanguageFile(new File(directory.toFile(), "lang"), configFile.LANGUAGE);
/*
* SETUP MESSAGE
*/
this.sendMessage(
"<reset>", "<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>"
);
/*
* MANAGERS
*/
this.playerManager = new PlayerManager();
this.serverManager = new ServerManager(this);
/*
* PROVIDERS
*/
this.provider = new MySQLProvider(this, configFile.CREDENTIALS);
this.provider.init();
/*
* COMMANDS
*/
this.registerCommands(
new VPLCommand(this), new PremiumCommand(this)
);
/*
* LISTENERS
*/
this.registerListeners(
new PluginMessageListener(this),
new ChatListener(this), new CommandListener(this), new TabCompleteListener(this), | package com.github.chrisgenti.vpl.velocity;
@Plugin(
id = "vpl",
name = "VPL",
version = "1.0.0",
description = "",
authors = {"ChrisGenti"}
) @Getter
public class VPLPlugin {
public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create("vpl", "main");
public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier("vpl:main");
@Inject private ProxyServer proxy;
@Inject private Logger logger;
@Inject private EventManager eventManager;
@Inject @DataDirectory Path directory;
private ConfigFile configFile;
private LanguageFile languageFile;
private PlayerManager playerManager;
private ServerManager serverManager;
private DataProvider provider;
private PluginTask registerTask;
@Subscribe
public void onInitialization(ProxyInitializeEvent event) {
/*
* FILES
*/
this.configFile = new ConfigFile(directory.toFile(), "config.toml");
this.languageFile = new LanguageFile(new File(directory.toFile(), "lang"), configFile.LANGUAGE);
/*
* SETUP MESSAGE
*/
this.sendMessage(
"<reset>", "<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>"
);
/*
* MANAGERS
*/
this.playerManager = new PlayerManager();
this.serverManager = new ServerManager(this);
/*
* PROVIDERS
*/
this.provider = new MySQLProvider(this, configFile.CREDENTIALS);
this.provider.init();
/*
* COMMANDS
*/
this.registerCommands(
new VPLCommand(this), new PremiumCommand(this)
);
/*
* LISTENERS
*/
this.registerListeners(
new PluginMessageListener(this),
new ChatListener(this), new CommandListener(this), new TabCompleteListener(this), | new PreLoginListener(this), new ProfileRequestListener(this), new InitialServerListener(this), new PostLoginListener(this), new DisconnectListener(this) | 10 | 2023-11-28 10:12:04+00:00 | 12k |
Ethylene9160/Chess | src/chess/web/Receiver.java | [
{
"identifier": "WebPanel",
"path": "src/chess/panels/WebPanel.java",
"snippet": "public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener {\n public final static String SIGN_SPLIT = \"&\", LINE_SPLIT = \"#\";\n public final static char SIGN_SPLIT_CHAR = '&', L... | import chess.panels.WebPanel;
import chess.util.CloseUtil;
import javax.swing.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket; | 9,288 | package chess.web;
/**
* 专供网络对局使用。
*/
public class Receiver implements Runnable{
protected DataInputStream inputStream;
protected boolean flag = true; | package chess.web;
/**
* 专供网络对局使用。
*/
public class Receiver implements Runnable{
protected DataInputStream inputStream;
protected boolean flag = true; | protected WebPanel webPanel; | 0 | 2023-12-01 02:33:32+00:00 | 12k |
ynewmark/vector-lang | compiler/src/main/java/org/vectorlang/compiler/parser/Parser.java | [
{
"identifier": "AssignStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/AssignStatement.java",
"snippet": "public class AssignStatement extends Statement {\n\n private final String leftHand;\n private final Expression rightHand;\n\n public AssignStatement(String leftHand,... | import java.util.ArrayList;
import java.util.List;
import org.vectorlang.compiler.ast.AssignStatement;
import org.vectorlang.compiler.ast.BinaryExpression;
import org.vectorlang.compiler.ast.BinaryOperator;
import org.vectorlang.compiler.ast.BlockStatement;
import org.vectorlang.compiler.ast.CallExpression;
import org.vectorlang.compiler.ast.CodeBase;
import org.vectorlang.compiler.ast.DeclareStatement;
import org.vectorlang.compiler.ast.Expression;
import org.vectorlang.compiler.ast.ForStatement;
import org.vectorlang.compiler.ast.FunctionStatement;
import org.vectorlang.compiler.ast.GroupingExpression;
import org.vectorlang.compiler.ast.IdentifierExpression;
import org.vectorlang.compiler.ast.IfStatement;
import org.vectorlang.compiler.ast.IndexExpression;
import org.vectorlang.compiler.ast.LiteralExpression;
import org.vectorlang.compiler.ast.PrintStatement;
import org.vectorlang.compiler.ast.ReturnStatement;
import org.vectorlang.compiler.ast.Statement;
import org.vectorlang.compiler.ast.UnaryExpression;
import org.vectorlang.compiler.ast.UnaryOperator;
import org.vectorlang.compiler.ast.VectorExpression;
import org.vectorlang.compiler.ast.WhileStatement;
import org.vectorlang.compiler.compiler.BaseType;
import org.vectorlang.compiler.compiler.Type; | 7,257 | expression = new BinaryExpression(expression, equality.apply(state), BinaryOperator.AND);
}
return expression;
}
private Expression equality(ParserState state) {
Expression expression = comparison.apply(state);
while (state.matches(new TokenType[]{TokenType.EQUALS_EQUALS, TokenType.BANG_EQUALS})) {
BinaryOperator operator = switch (state.previous().type()) {
case EQUALS_EQUALS -> BinaryOperator.EQUAL;
case BANG_EQUALS -> BinaryOperator.NOT_EQUAL;
default -> null;
};
expression = new BinaryExpression(expression, comparison.apply(state), operator);
}
return expression;
}
private GroupingExpression groupingExpression(ParserState state) {
state.consume(TokenType.OPEN_PAREN);
Expression expr = expression.apply(state);
state.consume(TokenType.CLOSE_PAREN);
return new GroupingExpression(expr);
}
private VectorExpression vectorExpression(ParserState state) {
List<Expression> expressions = new ArrayList<>();
state.consume(TokenType.OPEN_BRACKET);
do {
expressions.add(expression.apply(state));
} while (state.matches(TokenType.COMMA));
state.consume(TokenType.CLOSE_BRACKET);
return new VectorExpression(expressions.toArray(new Expression[0]));
}
private ForStatement forStatement(ParserState state) {
state.consume(TokenType.FOR);
state.consume(TokenType.OPEN_PAREN);
Statement initial = statement.apply(state);
Expression condition = expression.apply(state);
state.consume(TokenType.SEMICOLON);
Statement each = assignStatement2.apply(state);
state.consume(TokenType.CLOSE_PAREN);
Statement body = statement.apply(state);
return new ForStatement(condition, initial, each, body);
}
private WhileStatement whileStatement(ParserState state) {
state.consume(TokenType.WHILE);
state.consume(TokenType.OPEN_PAREN);
Expression condition = expression.apply(state);
state.consume(TokenType.CLOSE_PAREN);
Statement body = statement.apply(state);
return new WhileStatement(condition, body);
}
private AssignStatement assignStatement(ParserState state, boolean semicolon) {
state.consume(TokenType.IDENTIFIER);
String name = state.previous().value();
Expression expr = null;
if (state.matches(TokenType.EQUALS)) {
expr = expression.apply(state);
} else if (state.matches(TokenType.PLUS_PLUS)) {
expr = new BinaryExpression(
new IdentifierExpression(name),
new LiteralExpression(1), BinaryOperator.ADD
);
} else if (state.matches(TokenType.MINUS_MINUS)) {
expr = new BinaryExpression(
new IdentifierExpression(name),
new LiteralExpression(1), BinaryOperator.SUBTRACT
);
} else {
BinaryOperator operator = null;
if (state.matches(TokenType.PLUS_EQUALs)) {
operator = BinaryOperator.ADD;
} else if (state.matches(TokenType.MINUS_EQUALS)) {
operator = BinaryOperator.SUBTRACT;
} else if (state.matches(TokenType.STAR_EQUALS)) {
operator = BinaryOperator.MULTIPLY;
} else if (state.matches(TokenType.SLASH_EQUALS)) {
operator = BinaryOperator.DIVIDE;
} else if (state.matches(TokenType.BAR_EQUALS)) {
operator = BinaryOperator.OR;
} else if (state.matches(TokenType.AMPERSAND_EQUALS)) {
operator = BinaryOperator.AND;
} else {
return null;
}
expr = new BinaryExpression(
new IdentifierExpression(name),
expression.apply(state), operator);
}
if (semicolon) {
state.consume(TokenType.SEMICOLON);
}
return new AssignStatement(name, expr);
}
private Statement statement(ParserState state) {
if (state.matches(TokenType.OPEN_BRACE)) {
List<Statement> statements = new ArrayList<>();
while (!state.matches(TokenType.CLOSE_BRACE)) {
statements.add(statement.apply(state));
}
return new BlockStatement(statements.toArray(new Statement[0]));
} else if (state.matches(TokenType.PRINT)) {
Expression expr = expression.apply(state);
state.consume(TokenType.SEMICOLON);
return new PrintStatement(expr);
} else if (state.matches(new TokenType[]{TokenType.LET, TokenType.CONST})) {
boolean constant = state.previous().type() == TokenType.CONST;
state.consume(TokenType.IDENTIFIER);
String name = state.previous().value();
Expression expr = null;
if (state.matches(TokenType.EQUALS)) {
expr = expression.apply(state);
}
Type type = type(state);
state.consume(TokenType.SEMICOLON); | package org.vectorlang.compiler.parser;
public class Parser {
private ParseRule<Expression> literalExpression, identifierExpression, value, unary, indexedValue,
factor, term, comparison, equality, and, or, groupingExpression, vectorExpression, expression;
private ParseRule<Statement> forStatement, whileStatement, assignStatement, assignStatement2, statement;
private ParseRule<FunctionStatement> function;
public Parser() {
literalExpression = new ParseRule<>(this::literalExpression, TokenType.SEMICOLON);
identifierExpression = new ParseRule<>(this::identifierExpression, TokenType.SEMICOLON);
value = new ParseRule<>(this::value, TokenType.SEMICOLON);
unary = new ParseRule<>(this::unary, TokenType.SEMICOLON);
indexedValue = new ParseRule<>(this::indexedValue, TokenType.SEMICOLON);
factor = new ParseRule<>(this::factor, TokenType.SEMICOLON);
term = new ParseRule<>(this::term, TokenType.SEMICOLON);
comparison = new ParseRule<>(this::comparison, TokenType.SEMICOLON);
equality = new ParseRule<>(this::equality, TokenType.SEMICOLON);
and = new ParseRule<>(this::and, TokenType.SEMICOLON);
or = new ParseRule<>(this::or, TokenType.SEMICOLON);
groupingExpression = new ParseRule<>(this::groupingExpression, TokenType.SEMICOLON);
vectorExpression = new ParseRule<>(this::vectorExpression, TokenType.SEMICOLON);
expression = or;
forStatement = new ParseRule<>(this::forStatement, TokenType.CLOSE_BRACE);
whileStatement = new ParseRule<>(this::whileStatement, TokenType.CLOSE_BRACE);
assignStatement = new ParseRule<>((ParserState state) -> assignStatement(state, true), TokenType.SEMICOLON);
assignStatement2 = new ParseRule<>((ParserState state) -> assignStatement(state, false), TokenType.SEMICOLON);
statement = new ParseRule<>(this::statement, TokenType.CLOSE_BRACE);
function = new ParseRule<>(this::function, TokenType.CLOSE_BRACE);
}
private LiteralExpression literalExpression(ParserState state) {
if (state.matches(TokenType.TRUE)) {
return new LiteralExpression(true);
} else if (state.matches(TokenType.FALSE)) {
return new LiteralExpression(false);
} else if (state.matches(TokenType.INT_LITERAL)) {
return new LiteralExpression(Integer.parseInt(state.previous().value()));
} else if (state.matches(TokenType.FLOAT_LITERAL)) {
return new LiteralExpression(Double.parseDouble(state.previous().value()));
} else {
return null;
}
}
private Expression identifierExpression(ParserState state) {
state.consume(TokenType.IDENTIFIER);
String name = state.previous().value();
if (state.matches(TokenType.OPEN_PAREN)) {
boolean flag = false;
List<Expression> expressions = new ArrayList<>();
while (!state.matches(TokenType.CLOSE_PAREN)) {
if (flag) {
state.consume(TokenType.COMMA);
}
expressions.add(expression.apply(state));
flag = true;
}
return new CallExpression(name, expressions.toArray(new Expression[0]), null);
}
return new IdentifierExpression(name);
}
private Expression value(ParserState state) {
if (state.peek().type() == TokenType.OPEN_PAREN) {
return groupingExpression.apply(state);
} else if (state.peek().type() == TokenType.IDENTIFIER) {
return identifierExpression.apply(state);
} else if (state.peek().type() == TokenType.OPEN_BRACKET) {
return vectorExpression.apply(state);
} else {
return literalExpression.apply(state);
}
}
private Expression indexedValue(ParserState state) {
Expression expr = value.apply(state);
while (state.matches(TokenType.OPEN_BRACKET)) {
Expression index = expression.apply(state);
expr = new IndexExpression(expr, index);
state.consume(TokenType.CLOSE_BRACKET);
}
return expr;
}
private Expression unary(ParserState state) {
if (state.matches(TokenType.BANG)) {
return new UnaryExpression(unary.apply(state), UnaryOperator.NEGATE);
} else if (state.matches(TokenType.DASH)) {
return new UnaryExpression(unary.apply(state), UnaryOperator.INVERSE);
} else {
return indexedValue.apply(state);
}
}
private Expression factor(ParserState state) {
Expression expression = unary.apply(state);
while (state.matches(new TokenType[]{TokenType.STAR, TokenType.SLASH, TokenType.DOT_STAR, TokenType.DOT_SLASH})) {
BinaryOperator operator = switch (state.previous().type()) {
case STAR -> BinaryOperator.MULTIPLY;
case SLASH -> BinaryOperator.DIVIDE;
case DOT_STAR -> BinaryOperator.DOT_MULTIPLY;
case DOT_SLASH -> BinaryOperator.DOT_DIVIDE;
case DOT_DOT -> BinaryOperator.CONCAT;
default -> null;
};
expression = new BinaryExpression(expression, unary.apply(state), operator);
}
return expression;
}
private Expression term(ParserState state) {
Expression expression = factor.apply(state);
while (state.matches(new TokenType[]{TokenType.PLUS, TokenType.DASH, TokenType.DOT_PLUS, TokenType.DOT_DASH})) {
BinaryOperator operator = switch (state.previous().type()) {
case PLUS -> BinaryOperator.ADD;
case DASH -> BinaryOperator.SUBTRACT;
case DOT_PLUS -> BinaryOperator.DOT_ADD;
case DOT_DASH -> BinaryOperator.DOT_SUBTRACT;
default -> null;
};
expression = new BinaryExpression(expression, factor.apply(state), operator);
}
return expression;
}
private Expression comparison(ParserState state) {
Expression expression = term.apply(state);
while (state.matches(new TokenType[]{TokenType.LEFT_ARROW, TokenType.LEFT_ARROW_EQUALS, TokenType.RIGHT_ARROW, TokenType.RIGHT_ARROW_EQUALS})) {
BinaryOperator operator = switch (state.previous().type()) {
case LEFT_ARROW -> BinaryOperator.LESS_THAN;
case RIGHT_ARROW -> BinaryOperator.GREATER_THAN;
case LEFT_ARROW_EQUALS -> BinaryOperator.EQUAL_LESS_THAN;
case RIGHT_ARROW_EQUALS -> BinaryOperator.EQUAL_GREATER_THAN;
default -> null;
};
expression = new BinaryExpression(expression, term.apply(state), operator);
}
return expression;
}
private Expression or(ParserState state) {
Expression expression = and.apply(state);
while (state.matches(TokenType.BAR)) {
expression = new BinaryExpression(expression, and.apply(state), BinaryOperator.OR);
}
return expression;
}
private Expression and(ParserState state) {
Expression expression = equality.apply(state);
while (state.matches(TokenType.AMPERSAND)) {
expression = new BinaryExpression(expression, equality.apply(state), BinaryOperator.AND);
}
return expression;
}
private Expression equality(ParserState state) {
Expression expression = comparison.apply(state);
while (state.matches(new TokenType[]{TokenType.EQUALS_EQUALS, TokenType.BANG_EQUALS})) {
BinaryOperator operator = switch (state.previous().type()) {
case EQUALS_EQUALS -> BinaryOperator.EQUAL;
case BANG_EQUALS -> BinaryOperator.NOT_EQUAL;
default -> null;
};
expression = new BinaryExpression(expression, comparison.apply(state), operator);
}
return expression;
}
private GroupingExpression groupingExpression(ParserState state) {
state.consume(TokenType.OPEN_PAREN);
Expression expr = expression.apply(state);
state.consume(TokenType.CLOSE_PAREN);
return new GroupingExpression(expr);
}
private VectorExpression vectorExpression(ParserState state) {
List<Expression> expressions = new ArrayList<>();
state.consume(TokenType.OPEN_BRACKET);
do {
expressions.add(expression.apply(state));
} while (state.matches(TokenType.COMMA));
state.consume(TokenType.CLOSE_BRACKET);
return new VectorExpression(expressions.toArray(new Expression[0]));
}
private ForStatement forStatement(ParserState state) {
state.consume(TokenType.FOR);
state.consume(TokenType.OPEN_PAREN);
Statement initial = statement.apply(state);
Expression condition = expression.apply(state);
state.consume(TokenType.SEMICOLON);
Statement each = assignStatement2.apply(state);
state.consume(TokenType.CLOSE_PAREN);
Statement body = statement.apply(state);
return new ForStatement(condition, initial, each, body);
}
private WhileStatement whileStatement(ParserState state) {
state.consume(TokenType.WHILE);
state.consume(TokenType.OPEN_PAREN);
Expression condition = expression.apply(state);
state.consume(TokenType.CLOSE_PAREN);
Statement body = statement.apply(state);
return new WhileStatement(condition, body);
}
private AssignStatement assignStatement(ParserState state, boolean semicolon) {
state.consume(TokenType.IDENTIFIER);
String name = state.previous().value();
Expression expr = null;
if (state.matches(TokenType.EQUALS)) {
expr = expression.apply(state);
} else if (state.matches(TokenType.PLUS_PLUS)) {
expr = new BinaryExpression(
new IdentifierExpression(name),
new LiteralExpression(1), BinaryOperator.ADD
);
} else if (state.matches(TokenType.MINUS_MINUS)) {
expr = new BinaryExpression(
new IdentifierExpression(name),
new LiteralExpression(1), BinaryOperator.SUBTRACT
);
} else {
BinaryOperator operator = null;
if (state.matches(TokenType.PLUS_EQUALs)) {
operator = BinaryOperator.ADD;
} else if (state.matches(TokenType.MINUS_EQUALS)) {
operator = BinaryOperator.SUBTRACT;
} else if (state.matches(TokenType.STAR_EQUALS)) {
operator = BinaryOperator.MULTIPLY;
} else if (state.matches(TokenType.SLASH_EQUALS)) {
operator = BinaryOperator.DIVIDE;
} else if (state.matches(TokenType.BAR_EQUALS)) {
operator = BinaryOperator.OR;
} else if (state.matches(TokenType.AMPERSAND_EQUALS)) {
operator = BinaryOperator.AND;
} else {
return null;
}
expr = new BinaryExpression(
new IdentifierExpression(name),
expression.apply(state), operator);
}
if (semicolon) {
state.consume(TokenType.SEMICOLON);
}
return new AssignStatement(name, expr);
}
private Statement statement(ParserState state) {
if (state.matches(TokenType.OPEN_BRACE)) {
List<Statement> statements = new ArrayList<>();
while (!state.matches(TokenType.CLOSE_BRACE)) {
statements.add(statement.apply(state));
}
return new BlockStatement(statements.toArray(new Statement[0]));
} else if (state.matches(TokenType.PRINT)) {
Expression expr = expression.apply(state);
state.consume(TokenType.SEMICOLON);
return new PrintStatement(expr);
} else if (state.matches(new TokenType[]{TokenType.LET, TokenType.CONST})) {
boolean constant = state.previous().type() == TokenType.CONST;
state.consume(TokenType.IDENTIFIER);
String name = state.previous().value();
Expression expr = null;
if (state.matches(TokenType.EQUALS)) {
expr = expression.apply(state);
}
Type type = type(state);
state.consume(TokenType.SEMICOLON); | return new DeclareStatement(constant, name, expr, type); | 6 | 2023-11-30 04:22:36+00:00 | 12k |
tuxiaobei-scu/Draw-and-guess | entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java | [
{
"identifier": "MainAbility",
"path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java",
"snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get... | import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;
import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC;
import com.tuxiaobei.drawandguess.MainAbility;
import com.tuxiaobei.drawandguess.ResourceTable;
import com.tuxiaobei.drawandguess.bean.AnswerItem;
import com.tuxiaobei.drawandguess.bean.MyPoint;
import com.tuxiaobei.drawandguess.component.ChangeName;
import com.tuxiaobei.drawandguess.component.DeviceSelectDialog;
import com.tuxiaobei.drawandguess.component.DrawPoint;
import com.tuxiaobei.drawandguess.component.WordSelectDialog;
import com.tuxiaobei.drawandguess.game.Guesser;
import com.tuxiaobei.drawandguess.game.MainGame;
import com.tuxiaobei.drawandguess.provider.AnswerItemProvider;
import com.tuxiaobei.drawandguess.util.GsonUtil;
import com.tuxiaobei.drawandguess.util.LogUtils;
import com.tuxiaobei.drawandguess.util.Tools;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.bundle.IBundleManager;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | 9,786 | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tuxiaobei.drawandguess.slice;
/**
* MainAbilitySlice
*
* @since 2021-04-06
*/
public class MainAbilitySlice extends AbilitySlice {
private static final String TAG = MainAbilitySlice.class.getName();
private static final int PERMISSION_CODE = 20201203;
private static final int DELAY_TIME = 10;
private static final String STORE_ID_KEY = "storeId";
private static final String POINTS_KEY = "points";
private static final String ANS_KEY = "ans";
private static final String COLOR_INDEX_KEY = "colorIndex";
private static final String IS_FORM_LOCAL_KEY = "isFormLocal";
private static String storeId;
private DependentLayout canvas;
private Image transform;
private Image change_name;
private KvManager kvManager;
private SingleKvStore pointsSingleKvStore;
private SingleKvStore ansSingleKvStore;
private SingleKvStore nameSingleKvStore;
private Text title;
private DrawPoint drawl;
private Image play;
private Button back;
private Text show_score;
private Guesser guesser;
private Text tip;
private Button submit;
private TextField ans;
private MainGame main_game;
private ListContainer ans_list;
private final List<AnswerItem> ansData = new ArrayList<>();
private AnswerItemProvider answerItemProvider;
private String deviceId;
private String local_name;
private boolean isLocal;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main); | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tuxiaobei.drawandguess.slice;
/**
* MainAbilitySlice
*
* @since 2021-04-06
*/
public class MainAbilitySlice extends AbilitySlice {
private static final String TAG = MainAbilitySlice.class.getName();
private static final int PERMISSION_CODE = 20201203;
private static final int DELAY_TIME = 10;
private static final String STORE_ID_KEY = "storeId";
private static final String POINTS_KEY = "points";
private static final String ANS_KEY = "ans";
private static final String COLOR_INDEX_KEY = "colorIndex";
private static final String IS_FORM_LOCAL_KEY = "isFormLocal";
private static String storeId;
private DependentLayout canvas;
private Image transform;
private Image change_name;
private KvManager kvManager;
private SingleKvStore pointsSingleKvStore;
private SingleKvStore ansSingleKvStore;
private SingleKvStore nameSingleKvStore;
private Text title;
private DrawPoint drawl;
private Image play;
private Button back;
private Text show_score;
private Guesser guesser;
private Text tip;
private Button submit;
private TextField ans;
private MainGame main_game;
private ListContainer ans_list;
private final List<AnswerItem> ansData = new ArrayList<>();
private AnswerItemProvider answerItemProvider;
private String deviceId;
private String local_name;
private boolean isLocal;
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main); | storeId = STORE_ID_KEY + Tools.getRandom(); | 13 | 2023-12-03 13:36:00+00:00 | 12k |
godheaven/klib-data-jdbc | src/test/java/cl/kanopus/jdbc/impl/DAOTestImpl.java | [
{
"identifier": "Engine",
"path": "src/main/java/cl/kanopus/jdbc/impl/engine/Engine.java",
"snippet": "public enum Engine {\n ORACLE,\n POSTGRES,\n SQLSERVER\n}"
},
{
"identifier": "Mapping",
"path": "src/main/java/cl/kanopus/jdbc/entity/Mapping.java",
"snippet": "public abstrac... | import cl.kanopus.jdbc.impl.engine.Engine;
import cl.kanopus.jdbc.entity.Mapping;
import cl.kanopus.jdbc.example.entity.TestData;
import cl.kanopus.jdbc.util.SQLQueryDynamic;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
| 9,191 | package cl.kanopus.jdbc.impl;
/**
*
* @author godheaven
*/
@Repository
public class DAOTestImpl extends AbstractDAO<TestData, Long> implements DAOTest {
@Autowired
@Qualifier("jdbcTemplateTest")
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
protected NamedParameterJdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Override
protected Engine getEngine() {
return Engine.POSTGRES;
}
@Override
public Integer queryForInteger(String sql, HashMap<String, ?> params) {
return super.queryForInteger(sql, params);
}
@Override
public Long queryForLong(String sql, HashMap<String, ?> params) {
return super.queryForLong(sql, params);
}
@Override
public String queryForString(String sql, HashMap<String, ?> params) {
return super.queryForString(sql, params);
}
@Override
public List<TestData> find(String sql, HashMap<String, ?> params) {
return super.find(sql, params);
}
@Override
public List find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz) {
return super.find(sql, params, clazz);
}
@Override
public List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz, int limit, int offset) {
return super.find(sql, params, clazz, limit, offset);
}
@Override
public List<String> findStrings(String sql, HashMap<String, ?> params) {
return super.findStrings(sql, params);
}
@Override
public List<Long> findLongs(String sql, HashMap<String, ?> params) {
return super.findLongs(sql, params);
}
@Override
| package cl.kanopus.jdbc.impl;
/**
*
* @author godheaven
*/
@Repository
public class DAOTestImpl extends AbstractDAO<TestData, Long> implements DAOTest {
@Autowired
@Qualifier("jdbcTemplateTest")
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
protected NamedParameterJdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Override
protected Engine getEngine() {
return Engine.POSTGRES;
}
@Override
public Integer queryForInteger(String sql, HashMap<String, ?> params) {
return super.queryForInteger(sql, params);
}
@Override
public Long queryForLong(String sql, HashMap<String, ?> params) {
return super.queryForLong(sql, params);
}
@Override
public String queryForString(String sql, HashMap<String, ?> params) {
return super.queryForString(sql, params);
}
@Override
public List<TestData> find(String sql, HashMap<String, ?> params) {
return super.find(sql, params);
}
@Override
public List find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz) {
return super.find(sql, params, clazz);
}
@Override
public List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz, int limit, int offset) {
return super.find(sql, params, clazz, limit, offset);
}
@Override
public List<String> findStrings(String sql, HashMap<String, ?> params) {
return super.findStrings(sql, params);
}
@Override
public List<Long> findLongs(String sql, HashMap<String, ?> params) {
return super.findLongs(sql, params);
}
@Override
| public List<?> find(SQLQueryDynamic sqlQuery) {
| 3 | 2023-11-27 18:25:00+00:00 | 12k |
andre111/voxedit | src/client/java/me/andre111/voxedit/client/gui/screen/NBTEditorScreen.java | [
{
"identifier": "Textures",
"path": "src/client/java/me/andre111/voxedit/client/gui/Textures.java",
"snippet": "@Environment(value=EnvType.CLIENT)\npublic class Textures {\n public static final Identifier SLOT = new Identifier(\"container/slot\");\n public static final Identifier AIR = new Identif... | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.function.Supplier;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import me.andre111.voxedit.client.gui.Textures;
import me.andre111.voxedit.client.gui.widget.ModListWidget;
import me.andre111.voxedit.client.network.ClientNetworking;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.Element;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder;
import net.minecraft.client.gui.tooltip.Tooltip;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.DirectionalLayoutWidget;
import net.minecraft.client.gui.widget.DirectionalLayoutWidget.DisplayAxis;
import net.minecraft.client.gui.widget.EmptyWidget;
import net.minecraft.nbt.AbstractNbtList;
import net.minecraft.nbt.AbstractNbtNumber;
import net.minecraft.nbt.NbtByte;
import net.minecraft.nbt.NbtByteArray;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtDouble;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtFloat;
import net.minecraft.nbt.NbtInt;
import net.minecraft.nbt.NbtIntArray;
import net.minecraft.nbt.NbtList;
import net.minecraft.nbt.NbtLong;
import net.minecraft.nbt.NbtLongArray;
import net.minecraft.nbt.NbtShort;
import net.minecraft.nbt.NbtString;
import net.minecraft.nbt.StringNbtReader;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.OrderedText;
import net.minecraft.text.Style;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier; | 8,290 | c.remove(selected.key);
if(newElement != null) c.put(selected.key, newElement);
reload();
}
if(parent instanceof AbstractNbtList l) {
int index = Integer.parseInt(selected.key);
l.remove(index);
if(newElement != null && (l.getHeldType() == newElement.getType() || l.getHeldType() == NbtElement.END_TYPE)) l.add(index, newElement);
reload();
}
}
private void reload() {
//TODO: try to restore selection if possible
selected = null;
rootList.reload();
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
boolean value = super.mouseClicked(mouseX, mouseY, button);
if(!value) setSelected(null);
doNotChangeSelection = false;
return value;
}
private void setSelected(NBTEditorListEntry selected) {
if(this.doNotChangeSelection) return;
this.selected = selected;
this.doNotChangeSelection = true;
updateButtons();
}
private void updateButtons() {
cutButton.active = selected != null && selected.element instanceof NbtCompound;
copyButton.active = selected == null || selected.element instanceof NbtCompound;
pasteButton.active = CAN_ADD_COMPOUND.test(selected != null ? selected.element : root) && getClipboardCompound() != null;
editButton.active = selected != null && (selected.element instanceof AbstractNbtNumber || selected.element instanceof NbtString);
renameButton.active = selected != null && selected.hasName;
deleteButton.active = selected != null;
for(var addButton : addButtons) addButton.active = addButton.canAddTo.test(selected != null ? selected.element : root);
}
@SuppressWarnings("unchecked")
private void addElement(Predicate<NbtElement> canAddTo, Supplier<NbtElement> creator) {
NbtElement parent = selected != null ? selected.element : root;
if(canAddTo.test(parent)) {
if(parent instanceof NbtCompound compound) {
InputScreen.getString(this, Text.translatable("voxedit.screen.nbtEditor.input.tagName"), "", (tagName) -> {
if(!compound.contains(tagName)) {
compound.put(tagName, creator.get());
reload();
}
});
} else if(parent instanceof AbstractNbtList list) {
list.add(creator.get());
reload();
}
}
}
private final Predicate<NbtElement> CAN_ADD_COMPOUND = getCanAddPredicate(NbtElement.COMPOUND_TYPE);
private Predicate<NbtElement> getCanAddPredicate(byte type) {
return (parent) -> {
if(parent instanceof NbtCompound) return true;
if(parent instanceof NbtByteArray) return type == NbtElement.BYTE_TYPE;
if(parent instanceof NbtIntArray) return type == NbtElement.INT_TYPE;
if(parent instanceof NbtLongArray) return type == NbtElement.LONG_TYPE;
if(parent instanceof NbtList list) {
return list.getHeldType() == NbtElement.END_TYPE || list.getHeldType() == type;
}
return false;
};
}
private NbtCompound getClipboardCompound() {
try {
return StringNbtReader.parse(client.keyboard.getClipboard());
} catch (CommandSyntaxException e) {
return null;
}
}
@Override
public void close() {
super.close();
ClientNetworking.sendNBTEditorResult(null);
}
@Environment(value=EnvType.CLIENT)
private class IconButtonWidget extends ButtonWidget {
private final Identifier icon;
protected IconButtonWidget(Text tooltip, Identifier icon, PressAction action) {
super(0, 0, 20, 20, Text.empty(), action, (s) -> Text.empty().copy());
this.icon = icon;
setTooltip(Tooltip.of(tooltip));
}
@Override
protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
super.renderWidget(context, mouseX, mouseY, delta);
context.drawGuiTexture(icon, getX()+(getWidth()-8)/2, getY()+(getHeight()-8)/2, 8, 8);
}
}
@Environment(value=EnvType.CLIENT)
private class AddNBTElementButtonWidget extends IconButtonWidget {
private final Predicate<NbtElement> canAddTo;
protected AddNBTElementButtonWidget(String type, Identifier icon, Predicate<NbtElement> canAddTo, Supplier<NbtElement> creator) {
super(Text.translatable("voxedit.screen.nbtEditor.action.add."+type), icon, (b) -> NBTEditorScreen.this.addElement(canAddTo, creator));
this.canAddTo = canAddTo;
}
}
@Environment(value=EnvType.CLIENT) | /*
* Copyright (c) 2023 André Schweiger
*
* 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 me.andre111.voxedit.client.gui.screen;
@Environment(value=EnvType.CLIENT)
public class NBTEditorScreen extends Screen {
private final NbtCompound root;
private boolean initialised;
private ButtonWidget cutButton;
private ButtonWidget copyButton;
private ButtonWidget pasteButton;
private ButtonWidget editButton;
private ButtonWidget renameButton;
private ButtonWidget deleteButton;
private List<AddNBTElementButtonWidget> addButtons;
private NBTEditorList rootList;
private NBTEditorListEntry selected;
private boolean doNotChangeSelection;
public NBTEditorScreen(NbtCompound root) {
super(Text.translatable("voxedit.screen.nbtEditor"));
this.root = root;
this.initialised = false;
}
@Override
protected void init() {
if(initialised) return;
initialised = true;
DirectionalLayoutWidget buttonContainer = new DirectionalLayoutWidget(0, 2, DisplayAxis.HORIZONTAL);
buttonContainer.spacing(2);
cutButton = buttonContainer.add(addDrawableChild(new IconButtonWidget(Text.translatable("voxedit.screen.nbtEditor.action.cut"), Textures.EDITOR_CUT, (button) -> {
if(selected != null) {
client.keyboard.setClipboard(selected.element.asString());
replaceSelected(null);
}
})));
copyButton = buttonContainer.add(addDrawableChild(new IconButtonWidget(Text.translatable("voxedit.screen.nbtEditor.action.copy"), Textures.EDITOR_COPY, (button) -> {
client.keyboard.setClipboard(selected != null ? selected.element.asString() : root.asString());
})));
pasteButton = buttonContainer.add(addDrawableChild(new IconButtonWidget(Text.translatable("voxedit.screen.nbtEditor.action.paste"), Textures.EDITOR_PASTE, (button) -> {
NbtCompound compound = getClipboardCompound();
if(compound != null) addElement(CAN_ADD_COMPOUND, () -> compound);
})));
buttonContainer.add(new EmptyWidget(3, 0));
editButton = buttonContainer.add(addDrawableChild(new IconButtonWidget(Text.translatable("voxedit.screen.nbtEditor.action.edit"), Textures.EDITOR_EDIT, (button) -> {
if(selected != null) {
if(selected.element instanceof NbtByte nbtByte) {
InputScreen.getNumber(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtByte.byteValue(), Byte::parseByte, (newValue) -> replaceSelected(NbtByte.of(newValue)));
} else if(selected.element instanceof NbtShort nbtShort) {
InputScreen.getNumber(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtShort.shortValue(), Short::parseShort, (newValue) -> replaceSelected(NbtShort.of(newValue)));
} else if(selected.element instanceof NbtInt nbtInt) {
InputScreen.getNumber(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtInt.intValue(), Integer::parseInt, (newValue) -> replaceSelected(NbtInt.of(newValue)));
} else if(selected.element instanceof NbtLong nbtLong) {
InputScreen.getNumber(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtLong.longValue(), Long::parseLong, (newValue) -> replaceSelected(NbtLong.of(newValue)));
} else if(selected.element instanceof NbtFloat nbtFloat) {
InputScreen.getNumber(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtFloat.floatValue(), Float::parseFloat, (newValue) -> replaceSelected(NbtFloat.of(newValue)));
} else if(selected.element instanceof NbtDouble nbtDouble) {
InputScreen.getNumber(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtDouble.doubleValue(), Double::parseDouble, (newValue) -> replaceSelected(NbtDouble.of(newValue)));
} else if(selected.element instanceof NbtString nbtString) {
InputScreen.getString(this, Text.translatable("voxedit.screen.nbtEditor.input.value"), nbtString.asString(), (newValue) -> replaceSelected(NbtString.of(newValue)));
}
}
})));
renameButton = buttonContainer.add(addDrawableChild(new IconButtonWidget(Text.translatable("voxedit.screen.nbtEditor.action.rename"), Textures.EDITOR_RENAME, (button) -> {
if(selected != null && selected.hasName) {
NbtCompound parent = (NbtCompound) selected.parent;
InputScreen.getString(this, Text.translatable("voxedit.screen.nbtEditor.input.tagName"), selected.key, (newName) -> {
parent.remove(selected.key);
parent.put(newName, selected.element);
reload();
});
}
})));
deleteButton = buttonContainer.add(addDrawableChild(new IconButtonWidget(Text.translatable("voxedit.screen.nbtEditor.action.delete"), Textures.EDITOR_DELETE, (button) -> {
replaceSelected(null);
})));
buttonContainer.add(new EmptyWidget(3, 0));
addButtons = new ArrayList<>();
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("byte", Textures.NBT_BYTE, getCanAddPredicate(NbtElement.BYTE_TYPE), () -> NbtByte.of((byte) 0)))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("short", Textures.NBT_SHORT, getCanAddPredicate(NbtElement.SHORT_TYPE), () -> NbtShort.of((short) 0)))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("int", Textures.NBT_INT, getCanAddPredicate(NbtElement.INT_TYPE), () -> NbtInt.of(0)))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("long", Textures.NBT_LONG, getCanAddPredicate(NbtElement.LONG_TYPE), () -> NbtLong.of(0)))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("float", Textures.NBT_FLOAT, getCanAddPredicate(NbtElement.FLOAT_TYPE), () -> NbtFloat.of(0)))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("double", Textures.NBT_DOUBLE, getCanAddPredicate(NbtElement.DOUBLE_TYPE), () -> NbtDouble.of(0)))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("string", Textures.NBT_STRING, getCanAddPredicate(NbtElement.STRING_TYPE), () -> NbtString.of("")))));
buttonContainer.add(new EmptyWidget(3, 0));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("byteArray", Textures.NBT_ARRAY, getCanAddPredicate(NbtElement.BYTE_ARRAY_TYPE), () -> new NbtByteArray(new byte[] {})))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("intArray", Textures.NBT_ARRAY, getCanAddPredicate(NbtElement.INT_ARRAY_TYPE), () -> new NbtIntArray(new int[] {})))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("longArray", Textures.NBT_ARRAY, getCanAddPredicate(NbtElement.LONG_ARRAY_TYPE), () -> new NbtLongArray(new long[] {})))));
buttonContainer.add(new EmptyWidget(3, 0));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("list", Textures.NBT_LIST, getCanAddPredicate(NbtElement.LIST_TYPE), () -> new NbtList()))));
addButtons.add(buttonContainer.add(addDrawableChild(new AddNBTElementButtonWidget("compound", Textures.NBT_COMPOUND, getCanAddPredicate(NbtElement.COMPOUND_TYPE), () -> new NbtCompound()))));
buttonContainer.refreshPositions();
buttonContainer.setX((width-buttonContainer.getWidth())/2);
rootList = addDrawableChild(new NBTEditorList(root, width, height-40-2*4, 6));
addDrawableChild(ButtonWidget.builder(ScreenTexts.DONE, button -> {
ClientNetworking.sendNBTEditorResult(root);
close();
}).dimensions(width / 2 - 155, height - 20-2, 150, 20).build());
addDrawableChild(ButtonWidget.builder(ScreenTexts.CANCEL, button -> {
close();
}).dimensions(width / 2 + 5, height - 20-2, 150, 20).build());
updateButtons();
}
@Override
protected void initTabNavigation() {
}
@SuppressWarnings("unchecked")
private void replaceSelected(NbtElement newElement) {
if(selected == null) return;
NbtElement parent = selected.parent;
if(parent instanceof NbtCompound c) {
c.remove(selected.key);
if(newElement != null) c.put(selected.key, newElement);
reload();
}
if(parent instanceof AbstractNbtList l) {
int index = Integer.parseInt(selected.key);
l.remove(index);
if(newElement != null && (l.getHeldType() == newElement.getType() || l.getHeldType() == NbtElement.END_TYPE)) l.add(index, newElement);
reload();
}
}
private void reload() {
//TODO: try to restore selection if possible
selected = null;
rootList.reload();
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
boolean value = super.mouseClicked(mouseX, mouseY, button);
if(!value) setSelected(null);
doNotChangeSelection = false;
return value;
}
private void setSelected(NBTEditorListEntry selected) {
if(this.doNotChangeSelection) return;
this.selected = selected;
this.doNotChangeSelection = true;
updateButtons();
}
private void updateButtons() {
cutButton.active = selected != null && selected.element instanceof NbtCompound;
copyButton.active = selected == null || selected.element instanceof NbtCompound;
pasteButton.active = CAN_ADD_COMPOUND.test(selected != null ? selected.element : root) && getClipboardCompound() != null;
editButton.active = selected != null && (selected.element instanceof AbstractNbtNumber || selected.element instanceof NbtString);
renameButton.active = selected != null && selected.hasName;
deleteButton.active = selected != null;
for(var addButton : addButtons) addButton.active = addButton.canAddTo.test(selected != null ? selected.element : root);
}
@SuppressWarnings("unchecked")
private void addElement(Predicate<NbtElement> canAddTo, Supplier<NbtElement> creator) {
NbtElement parent = selected != null ? selected.element : root;
if(canAddTo.test(parent)) {
if(parent instanceof NbtCompound compound) {
InputScreen.getString(this, Text.translatable("voxedit.screen.nbtEditor.input.tagName"), "", (tagName) -> {
if(!compound.contains(tagName)) {
compound.put(tagName, creator.get());
reload();
}
});
} else if(parent instanceof AbstractNbtList list) {
list.add(creator.get());
reload();
}
}
}
private final Predicate<NbtElement> CAN_ADD_COMPOUND = getCanAddPredicate(NbtElement.COMPOUND_TYPE);
private Predicate<NbtElement> getCanAddPredicate(byte type) {
return (parent) -> {
if(parent instanceof NbtCompound) return true;
if(parent instanceof NbtByteArray) return type == NbtElement.BYTE_TYPE;
if(parent instanceof NbtIntArray) return type == NbtElement.INT_TYPE;
if(parent instanceof NbtLongArray) return type == NbtElement.LONG_TYPE;
if(parent instanceof NbtList list) {
return list.getHeldType() == NbtElement.END_TYPE || list.getHeldType() == type;
}
return false;
};
}
private NbtCompound getClipboardCompound() {
try {
return StringNbtReader.parse(client.keyboard.getClipboard());
} catch (CommandSyntaxException e) {
return null;
}
}
@Override
public void close() {
super.close();
ClientNetworking.sendNBTEditorResult(null);
}
@Environment(value=EnvType.CLIENT)
private class IconButtonWidget extends ButtonWidget {
private final Identifier icon;
protected IconButtonWidget(Text tooltip, Identifier icon, PressAction action) {
super(0, 0, 20, 20, Text.empty(), action, (s) -> Text.empty().copy());
this.icon = icon;
setTooltip(Tooltip.of(tooltip));
}
@Override
protected void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {
super.renderWidget(context, mouseX, mouseY, delta);
context.drawGuiTexture(icon, getX()+(getWidth()-8)/2, getY()+(getHeight()-8)/2, 8, 8);
}
}
@Environment(value=EnvType.CLIENT)
private class AddNBTElementButtonWidget extends IconButtonWidget {
private final Predicate<NbtElement> canAddTo;
protected AddNBTElementButtonWidget(String type, Identifier icon, Predicate<NbtElement> canAddTo, Supplier<NbtElement> creator) {
super(Text.translatable("voxedit.screen.nbtEditor.action.add."+type), icon, (b) -> NBTEditorScreen.this.addElement(canAddTo, creator));
this.canAddTo = canAddTo;
}
}
@Environment(value=EnvType.CLIENT) | private class NBTEditorList extends ModListWidget<NBTEditorListEntry> { | 1 | 2023-12-01 15:12:26+00:00 | 12k |
victor-vilar/coleta | backend/src/main/java/com/victorvilar/projetoempresa/services/ContractService.java | [
{
"identifier": "ContractCreateDto",
"path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/contract/ContractCreateDto.java",
"snippet": "public class ContractCreateDto {\n\n\n\n @NotBlank(message =\"The contract must have a number\")\n private String number;\n\n @NotNull(message = \... | import com.victorvilar.projetoempresa.dto.contract.ContractCreateDto;
import com.victorvilar.projetoempresa.dto.contract.ContractResponseDto;
import com.victorvilar.projetoempresa.dto.contract.ContractUpdateDto;
import com.victorvilar.projetoempresa.dto.contract.ItemContractCreateDto;
import com.victorvilar.projetoempresa.domain.Customer;
import com.victorvilar.projetoempresa.enums.ContractStatus;
import com.victorvilar.projetoempresa.exceptions.CustomerNotFoundException;
import com.victorvilar.projetoempresa.exceptions.ContractNotFoundException;
import com.victorvilar.projetoempresa.domain.Contract;
import com.victorvilar.projetoempresa.domain.ItemContract;
import com.victorvilar.projetoempresa.exceptions.ItemContractNotFoundException;
import com.victorvilar.projetoempresa.mappers.ContractMapper;
import com.victorvilar.projetoempresa.mappers.ItemContractMapper;
import com.victorvilar.projetoempresa.repository.ContractRepository;
import com.victorvilar.projetoempresa.repository.CustomerRepository;
import com.victorvilar.projetoempresa.repository.ItemContractRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.transaction.Transactional;
import java.util.List; | 8,934 | package com.victorvilar.projetoempresa.services;
@Service
public class ContractService {
private final ContractRepository contractRepository;
private final ItemContractRepository itemContractRepository;
private final CustomerRepository customerRepository;
private final CustomerService customerService;
private final ContractMapper contractMapper;
private final ItemContractMapper itemContractMapper;
@Autowired
public ContractService (ContractRepository repository,
CustomerService customerService,
ItemContractRepository itemContractRepository,
ContractMapper contractMapper,
ItemContractMapper itemContractMapper,
CustomerRepository customerRepository){
this.contractRepository = repository;
this.customerService = customerService;
this.itemContractRepository = itemContractRepository;
this.contractMapper = contractMapper;
this.itemContractMapper = itemContractMapper;
this.customerRepository = customerRepository;
}
/**
* get all contracts
* @return
*/ | package com.victorvilar.projetoempresa.services;
@Service
public class ContractService {
private final ContractRepository contractRepository;
private final ItemContractRepository itemContractRepository;
private final CustomerRepository customerRepository;
private final CustomerService customerService;
private final ContractMapper contractMapper;
private final ItemContractMapper itemContractMapper;
@Autowired
public ContractService (ContractRepository repository,
CustomerService customerService,
ItemContractRepository itemContractRepository,
ContractMapper contractMapper,
ItemContractMapper itemContractMapper,
CustomerRepository customerRepository){
this.contractRepository = repository;
this.customerService = customerService;
this.itemContractRepository = itemContractRepository;
this.contractMapper = contractMapper;
this.itemContractMapper = itemContractMapper;
this.customerRepository = customerRepository;
}
/**
* get all contracts
* @return
*/ | public List<ContractResponseDto> getAll() { | 1 | 2023-12-02 21:29:33+00:00 | 12k |
GiulianoVianna/Prototipo-Ferramenta-de-Backup-em-Java | src/main/java/com/mycompany/ferramentadebackup/view/FerramentaDeBackupView.java | [
{
"identifier": "BancoDeDadosDAO",
"path": "src/main/java/com/mycompany/ferramentadebackup/dao/BancoDeDadosDAO.java",
"snippet": "public class BancoDeDadosDAO {\n\n // URL de conexão com o banco de dados SQLite\n String url = \"jdbc:sqlite:dados_backup.db\";\n\n // Lista para armazenar objetos ... | import com.mycompany.ferramentadebackup.dao.BancoDeDadosDAO;
import com.mycompany.ferramentadebackup.dto.BancoDeDadosDTO;
import com.mycompany.ferramentadebackup.compactadorzip.CompactadorZip;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.table.DefaultTableModel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Optional; | 9,301 | habilitarCampos(false, false, false, false, false, false);
popularTabelaAgendamentoBackup();
} catch (Exception e) {
// Captura e exibe qualquer exceção que possa ocorrer
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao atualizar o agendamento d buckup: "
+ e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Exclui um agendamento de backup com base no ID fornecido.
*
* Este método exclui um agendamento de backup com base no ID obtido a partir do campo de texto `txtID`.
* Após a exclusão, os campos são limpos e a tabela de agendamentos é atualizada.
*
* @throws NumberFormatException Se ocorrer um erro na conversão de texto para número.
*/
private void excluirAgendamentoBackup() {
try {
int ID = Integer.parseInt(txtID.getText());
BancoDeDadosDTO objBancoDeDadosDTO = new BancoDeDadosDTO();
objBancoDeDadosDTO.setId(ID);
BancoDeDadosDAO objBancoDeDadosDao = new BancoDeDadosDAO();
objBancoDeDadosDao.excluir(objBancoDeDadosDTO);
configurarBotoes(false, false, true, false, false, true, false, false);
habilitarCampos(false, false, false, false, false, false);
popularTabelaAgendamentoBackup();
limparCampos();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro - " + e, "Informação", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Formata a exibição do componente JSpinner para exibir horas no formato "HH:mm".
*
* Este método configura o formato de exibição do componente JSpinner `jsHora` para exibir horas no formato "HH:mm".
* Isso torna a entrada e exibição de horas mais amigável para o usuário.
*/
private void formatarJSpinner() {
JSpinner.DateEditor editor = new JSpinner.DateEditor(jsHora, "HH:mm");
jsHora.setEditor(editor);
}
// Criar uma instância da classe BancoDeDadosDAO
BancoDeDadosDAO bancoDeDadosDAO = new BancoDeDadosDAO();
// Tempo em milissegundos (45 segundos)
int delay = 50000;
/**
* Um ActionListener que executa ações em resposta a eventos ActionEvent.
*
* Este ActionListener, chamado de `taskPerformer`, é configurado para ser executado em resposta a eventos ActionEvent.
* Quando acionado, ele verifica se a data e hora atual atendem a determinados critérios com base no objeto `bancoDeDadosDAO`.
* Se os critérios forem atendidos, ele inicia uma nova Thread para realizar as seguintes ações:
* 1. Chama o método `backup()` para realizar uma operação de backup.
* 2. Verifica se o `bancoDeDadosDAO` indica que o PC deve ser desligado e, se sim, chama o método `desligarPC()`.
*
* Esse ActionListener é usado para agendar a execução das ações com base em eventos e condições específicas.
*/
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (bancoDeDadosDAO.verificarDataHoraAtual()) {
new Thread(() -> {
backup();
if (bancoDeDadosDAO.verificarDesligarPC()) {
desligarPC();
}
}).start();
}
}
};
/**
* Realiza o backup dos arquivos ou diretórios especificados.
* <p>
* Este método obtém os caminhos de origem e destino do banco de dados e, em
* seguida, chama o método {@code compactarParaZip} para compactar o arquivo
* ou diretório de origem no arquivo ZIP de destino. O nome do arquivo ZIP é
* formado a partir do nome do backup e do destino.
* </p>
*
* <p>
* <b>Nota:</b> Este método assume que os caminhos de origem e destino, bem
* como o nome do backup, estão corretamente definidos no banco de dados e
* são acessíveis.</p>
*
* <p>
* Em caso de falha na compactação, as exceções são capturadas e registradas
* no console.</p>
*
*/
public void backup() {
BancoDeDadosDAO dao = new BancoDeDadosDAO();
BancoDeDadosDTO dto = dao.verificarDataHoraAtualArquivos();
SimpleDateFormat sdf = new SimpleDateFormat("-dd-MM-yyyy-HH_mm_ss");
try {
String destinoZip = dto.getDiretorioDestino() + File.separator + dto.getNomeBackup() + sdf.format(new Date()) + ".zip";
System.out.println("Origem: " + dto.getDiretorioOrigem());
System.out.println("Destino ZIP: " + destinoZip);
| package com.mycompany.ferramentadebackup.view;
/**
*
* @author Giuliano Vianna
*/
public class FerramentaDeBackupView extends javax.swing.JFrame {
/**
* Creates new form frmFerramentaDeBackupView
*/
public FerramentaDeBackupView() {
initComponents();
verificarBancoDeDados();
iconeJanela();
popularTabelaAgendamentoBackup();
// Centraliza a janela
this.setLocationRelativeTo(null);
formatarJSpinner();
new Timer(delay, taskPerformer).start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
jLabel1 = new javax.swing.JLabel();
txtArquivoDiretorio = new javax.swing.JTextField();
btnSelecionarArquivoDiretorio = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
txtDiretorio = new javax.swing.JTextField();
btnSelecionarDiretorioDestino = new javax.swing.JButton();
jdData = new com.toedter.calendar.JDateChooser();
jLabel3 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jtTabela = new javax.swing.JTable();
rdbPC = new javax.swing.JRadioButton();
jPanel1 = new javax.swing.JPanel();
btnNovo = new javax.swing.JButton();
btnSalvar = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
btnEditar = new javax.swing.JButton();
btnExcluir = new javax.swing.JButton();
btnAtualizar = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
txtID = new javax.swing.JTextField();
txtNomeBackup = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jsHora = new javax.swing.JSpinner();
jLabel6 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Ferramenta de Backup");
setResizable(false);
jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel1.setText("Arquivo ou Diretório");
txtArquivoDiretorio.setEditable(false);
txtArquivoDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
txtArquivoDiretorio.setEnabled(false);
btnSelecionarArquivoDiretorio.setBackground(new java.awt.Color(153, 0, 255));
btnSelecionarArquivoDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
btnSelecionarArquivoDiretorio.setForeground(new java.awt.Color(255, 255, 255));
btnSelecionarArquivoDiretorio.setText("Selecionar");
btnSelecionarArquivoDiretorio.setEnabled(false);
btnSelecionarArquivoDiretorio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSelecionarArquivoDiretorioActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel2.setText("Diretório de Destino");
txtDiretorio.setEditable(false);
txtDiretorio.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
txtDiretorio.setEnabled(false);
btnSelecionarDiretorioDestino.setBackground(new java.awt.Color(153, 0, 255));
btnSelecionarDiretorioDestino.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
btnSelecionarDiretorioDestino.setForeground(new java.awt.Color(255, 255, 255));
btnSelecionarDiretorioDestino.setText("Selecionar");
btnSelecionarDiretorioDestino.setEnabled(false);
btnSelecionarDiretorioDestino.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSelecionarDiretorioDestinoActionPerformed(evt);
}
});
jdData.setDateFormatString("dd'/'MM'/'yy");
jdData.setEnabled(false);
jdData.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel3.setText("Data");
jtTabela.setFont(new java.awt.Font("Segoe UI", 0, 13)); // NOI18N
jtTabela.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null},
{null, null, null, null, null, null, null}
},
new String [] {
"ID", "Nome Backup", "Arquivo/Diretório de Origem", "Diretório de Destino", "Data", "Hora", "Desligar PC"
}
));
jtTabela.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jtTabela.setShowGrid(false);
jtTabela.setShowVerticalLines(true);
jScrollPane1.setViewportView(jtTabela);
if (jtTabela.getColumnModel().getColumnCount() > 0) {
jtTabela.getColumnModel().getColumn(0).setMinWidth(80);
jtTabela.getColumnModel().getColumn(0).setPreferredWidth(80);
jtTabela.getColumnModel().getColumn(0).setMaxWidth(80);
jtTabela.getColumnModel().getColumn(1).setMinWidth(200);
jtTabela.getColumnModel().getColumn(2).setMinWidth(420);
jtTabela.getColumnModel().getColumn(2).setPreferredWidth(420);
jtTabela.getColumnModel().getColumn(2).setMaxWidth(420);
jtTabela.getColumnModel().getColumn(3).setMinWidth(420);
jtTabela.getColumnModel().getColumn(3).setPreferredWidth(420);
jtTabela.getColumnModel().getColumn(3).setMaxWidth(420);
jtTabela.getColumnModel().getColumn(4).setMinWidth(80);
jtTabela.getColumnModel().getColumn(4).setPreferredWidth(80);
jtTabela.getColumnModel().getColumn(4).setMaxWidth(80);
jtTabela.getColumnModel().getColumn(5).setMinWidth(80);
jtTabela.getColumnModel().getColumn(5).setPreferredWidth(80);
jtTabela.getColumnModel().getColumn(5).setMaxWidth(80);
jtTabela.getColumnModel().getColumn(6).setMinWidth(80);
jtTabela.getColumnModel().getColumn(6).setPreferredWidth(80);
jtTabela.getColumnModel().getColumn(6).setMaxWidth(80);
}
rdbPC.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
rdbPC.setForeground(new java.awt.Color(153, 0, 255));
rdbPC.setText("Desligar o PC ao finalizar o backup");
rdbPC.setEnabled(false);
btnNovo.setBackground(new java.awt.Color(153, 0, 255));
btnNovo.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
btnNovo.setForeground(new java.awt.Color(255, 255, 255));
btnNovo.setText("Novo");
btnNovo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNovoActionPerformed(evt);
}
});
btnSalvar.setBackground(new java.awt.Color(153, 0, 255));
btnSalvar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
btnSalvar.setForeground(new java.awt.Color(255, 255, 255));
btnSalvar.setText("Salvar");
btnSalvar.setEnabled(false);
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
btnCancelar.setBackground(new java.awt.Color(153, 0, 255));
btnCancelar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
btnCancelar.setForeground(new java.awt.Color(255, 255, 255));
btnCancelar.setText("Cancelar");
btnCancelar.setEnabled(false);
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
btnEditar.setBackground(new java.awt.Color(153, 0, 255));
btnEditar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
btnEditar.setForeground(new java.awt.Color(255, 255, 255));
btnEditar.setText("Editar");
btnEditar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEditarActionPerformed(evt);
}
});
btnExcluir.setBackground(new java.awt.Color(153, 0, 255));
btnExcluir.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
btnExcluir.setForeground(new java.awt.Color(255, 255, 255));
btnExcluir.setText("Excluir");
btnExcluir.setEnabled(false);
btnExcluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExcluirActionPerformed(evt);
}
});
btnAtualizar.setBackground(new java.awt.Color(153, 0, 255));
btnAtualizar.setFont(new java.awt.Font("Segoe UI", 0, 16)); // NOI18N
btnAtualizar.setForeground(new java.awt.Color(255, 255, 255));
btnAtualizar.setText("Atualizar");
btnAtualizar.setEnabled(false);
btnAtualizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAtualizarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(15, Short.MAX_VALUE)
.addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAtualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(25, Short.MAX_VALUE))
);
jLabel4.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel4.setText("ID");
txtID.setEditable(false);
txtID.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
txtID.setForeground(new java.awt.Color(255, 255, 255));
txtID.setEnabled(false);
txtNomeBackup.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
txtNomeBackup.setEnabled(false);
jLabel5.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel5.setText("Horas");
jsHora.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jsHora.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.HOUR_OF_DAY)
);
jsHora.setToolTipText("");
jsHora.setEnabled(false);
jLabel6.setFont(new java.awt.Font("Segoe UI", 0, 14)); // NOI18N
jLabel6.setText("Nome do Backup");
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("Edit");
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 1374, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(txtArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSelecionarArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(txtDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 729, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSelecionarDiretorioDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jdData, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(67, 67, 67)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jsHora, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtNomeBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(rdbPC, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap(24, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtID, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtArquivoDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSelecionarArquivoDiretorio))
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtDiretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSelecionarDiretorioDestino))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jsHora, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNomeBackup, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(rdbPC))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jdData, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnSelecionarArquivoDiretorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarArquivoDiretorioActionPerformed
selecionarDiretorioOuArquivo();
}//GEN-LAST:event_btnSelecionarArquivoDiretorioActionPerformed
private void btnSelecionarDiretorioDestinoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelecionarDiretorioDestinoActionPerformed
selecionarDiretorio();
}//GEN-LAST:event_btnSelecionarDiretorioDestinoActionPerformed
private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
configurarBotoes(true, true, false, false, true, false, false, true);
habilitarCampos(true, true, true, true, true, true);
}//GEN-LAST:event_btnNovoActionPerformed
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
configurarBotoes(false, false, true, false, false, true, false, false);
habilitarCampos(false, false, false, false, false, false);
limparCampos();
}//GEN-LAST:event_btnCancelarActionPerformed
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
salvarAgendamentoBackup();
}//GEN-LAST:event_btnSalvarActionPerformed
private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
editarAgendamentoBackup();
}//GEN-LAST:event_btnEditarActionPerformed
private void btnAtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtualizarActionPerformed
atualizarAgendamentoBuckup();
}//GEN-LAST:event_btnAtualizarActionPerformed
private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
excluirAgendamentoBackup();
}//GEN-LAST:event_btnExcluirActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FerramentaDeBackupView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new FerramentaDeBackupView().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAtualizar;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnEditar;
private javax.swing.JButton btnExcluir;
private javax.swing.JButton btnNovo;
private javax.swing.JButton btnSalvar;
private javax.swing.JButton btnSelecionarArquivoDiretorio;
private javax.swing.JButton btnSelecionarDiretorioDestino;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private com.toedter.calendar.JDateChooser jdData;
private javax.swing.JSpinner jsHora;
private javax.swing.JTable jtTabela;
private javax.swing.JRadioButton rdbPC;
private javax.swing.JTextField txtArquivoDiretorio;
private javax.swing.JTextField txtDiretorio;
private javax.swing.JTextField txtID;
private javax.swing.JTextField txtNomeBackup;
// End of variables declaration//GEN-END:variables
/**
* Permite ao usuário escolher entre selecionar um diretório ou um arquivo.
* <p>
* Este método exibe uma caixa de diálogo com duas opções: "Diretório" e
* "Arquivo". A escolha do usuário determina se o {@link JFileChooser} será
* configurado para selecionar apenas diretórios ou apenas arquivos. Após a
* seleção, o caminho absoluto do diretório ou arquivo escolhido é retornado
* dentro de um {@link java.util.Optional}.
* </p>
*
* <p>
* Se o usuário selecionar um item, o caminho absoluto é retornado
* encapsulado em um {@code Optional<String>}. Se o usuário cancelar a
* operação ou se ocorrer um erro, um {@code Optional<String>} vazio é
* retornado.
* </p>
*
* <p>
* Exceções são tratadas internamente, e uma mensagem de erro é exibida em
* caso de falha.
* </p>
*
* @return Um {@link java.util.Optional<String>} contendo o caminho do
* arquivo ou diretório selecionado, ou um {@code Optional} vazio em caso de
* cancelamento ou erro.
*/
public Optional<String> selecionarDiretorioOuArquivo() {
Object[] options = {"Diretório", "Arquivo"};
int choice = JOptionPane.showOptionDialog(
null,
"Você deseja selecionar um diretório ou um arquivo?",
"Selecionar Diretório ou Arquivo",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(choice == JOptionPane.YES_OPTION
? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY);
try {
int option = fileChooser.showOpenDialog(null);
if (option == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null) {
String caminhoArquivoDiretorio = selectedFile.getAbsolutePath();
txtArquivoDiretorio.setText(caminhoArquivoDiretorio); // Ajuste conforme sua lógica de interface
return Optional.of(caminhoArquivoDiretorio);
}
}
} catch (HeadlessException error) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao selecionar o arquivo ou diretório " + error, "Erro", JOptionPane.ERROR_MESSAGE);
}
return Optional.empty();
}
/**
* Abre uma caixa de diálogo para o usuário selecionar um diretório.
* <p>
* Este método utiliza o {@link JFileChooser} configurado para permitir que
* o usuário selecione apenas diretórios. Após a seleção, o caminho absoluto
* do diretório escolhido é atribuído a uma variável de instância.
* </p>
*
* <p>
* Se o usuário selecionar um diretório, o caminho absoluto é armazenado na
* variável {@code txtDiretorio}. Em caso de cancelamento da operação,
* nenhuma ação é tomada.
* </p>
*
* <p>
* <b>Nota:</b> Este método não retorna nenhum valor, mas atualiza
* diretamente a interface do usuário com o caminho do diretório
* selecionado.
* </p>
*/
public void selecionarDiretorio() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Configura para selecionar apenas diretórios
int option = fileChooser.showOpenDialog(null); // Abre a caixa de diálogo centralizada
if (option == JFileChooser.APPROVE_OPTION) {
File selectedDirectory = fileChooser.getSelectedFile();
if (selectedDirectory != null) {
// Atribui o caminho à variável de instância
String caminhoDoDiretorio = selectedDirectory.getAbsolutePath();
txtDiretorio.setText(caminhoDoDiretorio);
}
}
}
/**
* Verifica a existência do banco de dados e o cria, se necessário.
* <p>
* Este método utiliza a classe {@link BancoDeDadosDAO} para verificar se o
* banco de dados já existe. Se o banco de dados não existir, ele é criado
* por meio do método {@link BancoDeDadosDAO#verificarECriarBancoDeDados()}.
* </p>
*
* <p>
* <b>Nota:</b> Este método não retorna nenhum valor, pois sua função é
* verificar e criar o banco de dados, se necessário, sem fornecer
* resultados diretos.
* </p>
*/
public final void verificarBancoDeDados() {
BancoDeDadosDAO objBancoDeDadosDAO = new BancoDeDadosDAO();
objBancoDeDadosDAO.verificarECriarBancoDeDados();
}
/**
* Define o ícone da janela com base em um arquivo de imagem.
* <p>
* Este método carrega uma imagem de ícone da classe {@link ImageIcon} com o
* caminho especificado. Em seguida, define essa imagem como o ícone da
* janela atual usando {@link #setIconImage(java.awt.Image)}.
* </p>
*
* <p>
* <b>Nota:</b> Este método é usado para configurar o ícone da janela e não
* retorna nenhum valor.
* </p>
*/
private void iconeJanela() {
ImageIcon icone = new ImageIcon(getClass().getClassLoader().getResource("images/iconeJanela.png"));
setIconImage(icone.getImage());
}
/**
* Configura o estado dos botões da interface com base em parâmetros
* booleanos.
* <p>
* Este método permite configurar o estado de vários botões da interface de
* acordo com os valores booleanos fornecidos como parâmetros. Cada
* parâmetro corresponde a um botão e define se ele deve estar habilitado
* (true) ou desabilitado (false).
* </p>
*
* @param diretorioOrigem Define se os botões de seleção de diretório de
* origem devem estar habilitados.
* @param diretorioDestino Define se os botões de seleção de diretório de
* destino devem estar habilitados.
* @param novo Define se o botão "Novo" deve estar habilitado.
* @param atualizar Define se o botão "Atualizar" deve estar habilitado.
* @param salvar Define se o botão "Salvar" deve estar habilitado.
* @param editar Define se o botão "Editar" deve estar habilitado.
* @param excluir Define se o botão "Excluir" deve estar habilitado.
* @param cancelar Define se o botão "Cancelar" deve estar habilitado.
*/
public void configurarBotoes(boolean diretorioOrigem, boolean diretorioDestino, boolean novo, boolean atualizar, boolean salvar, boolean editar, boolean excluir, boolean cancelar) {
btnSelecionarArquivoDiretorio.setEnabled(diretorioOrigem);
btnSelecionarDiretorioDestino.setEnabled(diretorioOrigem);
btnNovo.setEnabled(novo);
btnAtualizar.setEnabled(atualizar);
btnSalvar.setEnabled(salvar);
btnEditar.setEnabled(editar);
btnExcluir.setEnabled(excluir);
btnCancelar.setEnabled(cancelar);
}
/**
* Habilita ou desabilita campos da interface com base em parâmetros
* booleanos.
* <p>
* Este método permite habilitar ou desabilitar vários campos da interface
* com base nos valores booleanos fornecidos como parâmetros. Cada parâmetro
* corresponde a um campo e define se ele deve estar habilitado (true) ou
* desabilitado (false).
* </p>
*
* @param arquivoDiretorio Define se o campo de arquivo/diretório deve estar
* habilitado.
* @param diretorio Define se o campo de diretório deve estar habilitado.
* @param data Define se o campo de data deve estar habilitado.
* @param nomeBackup Define se o campo de nome de backup deve estar
* habilitado.
* @param desligarPC Define se a opção de desligar o PC deve estar
* habilitada.
* @param hora Define se o campo de hora deve estar habilitado.
*/
private void habilitarCampos(boolean arquivoDiretorio, boolean diretorio, boolean data, boolean nomeBackup, boolean desligarPC, boolean hora) {
txtArquivoDiretorio.setEnabled(arquivoDiretorio);
txtDiretorio.setEnabled(diretorio);
jdData.setEnabled(data);
txtNomeBackup.setEnabled(nomeBackup);
rdbPC.setEnabled(desligarPC);
jsHora.setEnabled(hora);
}
/**
* Salva um agendamento de backup com base nos campos preenchidos na interface.
* <p>
* Este método realiza as seguintes ações:
* 1. Verifica se os campos obrigatórios contendo endereços de diretórios estão preenchidos.
* 2. Coleta os valores dos campos da interface, como arquivo/diretório, diretório de destino, data, hora,
* opção de desligar o PC e nome do backup.
* 3. Configura um objeto de transferência de dados (DTO) com os valores coletados.
* 4. Chama o método para salvar os dados no banco de dados usando um objeto de acesso a dados (DAO).
* 5. Limpa os campos da interface.
* 6. Desabilita campos e configura os botões na interface de acordo com a lógica.
* 7. Atualiza a tabela de agendamento de backup na interface.
* </p>
*/
public void salvarAgendamentoBackup() {
//Método verifica se os campos tem os endereços dos diretórios
if (verificarCampos()) {
return;
}
String arquivoDiretorio = txtArquivoDiretorio.getText();
String diretorioDestino = txtDiretorio.getText();
Date dataSelecionada = jdData.getDate();
String dataFormatada = formatarData(dataSelecionada);
JSpinner.DateEditor editor = new JSpinner.DateEditor(jsHora, "HH:mm");
jsHora.setEditor(editor);
Date dataHora = (Date) jsHora.getValue();
String horaFormatada = formatarHora(dataHora);
String desligarPC = rdbPC.isSelected() ? "Sim" : "Não";
String nomeBackup = txtNomeBackup.getText();
// Criando e configurando o DTO
BancoDeDadosDTO objBancoDeDadosDTO = new BancoDeDadosDTO();
objBancoDeDadosDTO.setDiretorioOrigem(arquivoDiretorio);
objBancoDeDadosDTO.setDiretorioDestino(diretorioDestino);
objBancoDeDadosDTO.setData(dataFormatada);
objBancoDeDadosDTO.setDesligarPC(desligarPC);
objBancoDeDadosDTO.setNomeBackup(nomeBackup);
objBancoDeDadosDTO.setHora(horaFormatada);
// Salvando os dados no banco de dados
BancoDeDadosDAO objBancoDeDadosDAO = new BancoDeDadosDAO();
objBancoDeDadosDAO.cadastrar(objBancoDeDadosDTO);
limparCampos();
habilitarCampos(false, false, false, false, false, false);
configurarBotoes(false, false, true, false, false, true, false, false);
popularTabelaAgendamentoBackup();
}
/**
* Preenche a tabela de agendamento de backup na interface com os dados obtidos do banco de dados.
* <p>
* Este método realiza as seguintes ações:
* 1. Cria uma instância do DAO (objeto de acesso a dados) para interagir com o banco de dados.
* 2. Obtém o modelo da tabela existente na interface e limpa todas as suas linhas.
* 3. Chama o método `listar` do DAO para obter uma lista de agendamentos de backup armazenados no banco de dados.
* 4. Preenche a tabela na interface com os dados obtidos da lista, adicionando uma nova linha para cada agendamento.
* Os campos exibidos na tabela incluem: ID, Nome do Backup, Diretório de Origem, Diretório de Destino,
* Data, Hora e opção de Desligar o PC.
* 5. Trata exceções e exibe uma mensagem de erro em caso de falha no processo.
* </p>
*/
public final void popularTabelaAgendamentoBackup() {
try {
// Cria um objeto da classe CentroDeCustoDAO para realizar operações no banco de dados
BancoDeDadosDAO objBancoDeDadosDAO = new BancoDeDadosDAO();
// Pega o modelo da tabela jtTabela e limpa suas linhas
DefaultTableModel model = (DefaultTableModel) jtTabela.getModel();
model.setNumRows(0);
// Chama o método PesquisarCentroDeCusto para obter a lista de centros de custo
ArrayList<BancoDeDadosDTO> lista = objBancoDeDadosDAO.listar();
// Preenche a tabela com a lista de centros de custo
for (int num = 0; num < lista.size(); num++) {
// Adiciona uma nova linha na tabela para cada item da lista
model.addRow(new Object[]{
lista.get(num).getId(),
lista.get(num).getNomeBackup(),//Trabalhando
lista.get(num).getDiretorioOrigem(),
lista.get(num).getDiretorioDestino(),
lista.get(num).getData(),
lista.get(num).getHora(),
lista.get(num).getDesligarPC()
});
}
} catch (Exception error) {
// Exibe uma mensagem de erro caso algo dê errado durante o processo
JOptionPane.showMessageDialog(null, "Listar Valores View - " + error, "Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Formata uma data no formato "dd-MM-yyyy" e a retorna como uma string.
*
* @param data A data a ser formatada.
* @return A data formatada como uma string no formato "dd-MM-yyyy" ou uma string vazia se a data for nula.
*/
private String formatarData(Date data) {
if (data == null) {
return "";
}
SimpleDateFormat formatadorData = new SimpleDateFormat("dd-MM-yyyy");
return formatadorData.format(data);
}
/**
* Formata uma hora no formato "HH:mm" e a retorna como uma string.
*
* @param hora A hora a ser formatada.
* @return A hora formatada como uma string no formato "HH:mm" ou uma string vazia se a hora for nula.
*/
private String formatarHora(Date hora) {
if (hora == null) {
return "";
}
SimpleDateFormat formatadorHora = new SimpleDateFormat("HH:mm");
return formatadorHora.format(hora);
}
/**
* Limpa os campos de entrada de dados da interface, restaurando-os para seus valores padrão ou vazios.
*/
private void limparCampos() {
txtID.setText("");
txtArquivoDiretorio.setText("");
txtDiretorio.setText("");
jdData.setDate(null);
txtNomeBackup.setText("");
rdbPC.setSelected(false);
//jsHora.setValue(new Date());
}
/**
* Verifica se os campos de entrada de dados obrigatórios estão preenchidos.
*
* @return true se algum campo obrigatório estiver vazio, caso contrário, false.
*/
private boolean verificarCampos() {
if (txtArquivoDiretorio.getText().isEmpty() || txtDiretorio.getText().isEmpty()
|| jdData.getDate() == null || txtNomeBackup.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "Favor preencher todos os dados!",
"Informação", JOptionPane.INFORMATION_MESSAGE);
return true;
}
return false;
}
/**
* Permite editar um agendamento de backup selecionado na tabela.
*
* Se uma linha da tabela estiver selecionada, este método preenche os campos de edição
* com os valores do agendamento selecionado, permitindo a edição desses valores.
*
* @throws ParseException Se ocorrer um erro na conversão de datas/horas.
*/
private void editarAgendamentoBackup() {
try {
// Armazena o índice da linha que foi selecionada na tabela
int setar = jtTabela.getSelectedRow();
// Verifica se alguma linha foi selecionada (índice diferente de -1)
if (setar != -1) {
habilitarCampos(true, true, true, true, true, true);
configurarBotoes(true, true, false, true, false, false, true, true);
// Pega os valores da linha selecionada e preenche os campos de texto correspondentes
txtID.setText(jtTabela.getModel().getValueAt(setar, 0).toString());
txtNomeBackup.setText(jtTabela.getModel().getValueAt(setar, 1).toString());
txtArquivoDiretorio.setText(jtTabela.getModel().getValueAt(setar, 2).toString());
txtDiretorio.setText(jtTabela.getModel().getValueAt(setar, 3).toString());
SimpleDateFormat formatador = new SimpleDateFormat("dd-MM-yyyy");
Date data = formatador.parse(jtTabela.getModel().getValueAt(setar, 4).toString());
jdData.setDate(data);
//Obtem a string da tabela
String valorHoraTabela = jtTabela.getModel().getValueAt(setar, 5).toString();
//Cria um formatador com o mesmo formato usado no JSpinner
SimpleDateFormat formatadorHora = new SimpleDateFormat("HH:mm");
//Converte a string para um objeto Date
Date dataHora = formatadorHora.parse(valorHoraTabela);
//Configura o valor do JSpinner
jsHora.setValue(dataHora);
String valorRadioButton = jtTabela.getModel().getValueAt(setar, 6).toString();
rdbPC.setSelected(valorRadioButton.equals("Sim"));
} else {
// Caso nenhuma linha tenha sido selecionada, exibe uma mensagem de informação
JOptionPane.showMessageDialog(null, "Favor Selecionar um agendamento de backup!", "Informação", JOptionPane.INFORMATION_MESSAGE);
}
} catch (Exception e) {
// Caso ocorra algum erro durante o processo, captura a exceção e exibe uma mensagem de erro
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao editar os dados do usuário: " + e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Atualiza um agendamento de backup com os valores dos campos de edição.
*
* Este método realiza a atualização de um agendamento de backup com base nos valores
* preenchidos nos campos de edição. Ele verifica se os campos estão preenchidos corretamente
* e, se estiverem, atualiza o agendamento no banco de dados.
*
* @throws NumberFormatException Se ocorrer um erro na conversão de texto para número.
* @throws ParseException Se ocorrer um erro na conversão de datas/horas.
*/
private void atualizarAgendamentoBuckup() {
try {
if (verificarCampos()) {
return;
}
//Atribuição dos valores as váriaveis
int ID = Integer.parseInt(txtID.getText());
String arquivoDiretorio = txtArquivoDiretorio.getText();
String diretorioDestino = txtDiretorio.getText();
Date dataSelecionada = jdData.getDate();
String dataFormatada = formatarData(dataSelecionada);
JSpinner.DateEditor editor = new JSpinner.DateEditor(jsHora, "HH:mm");
jsHora.setEditor(editor);
Date dataHora = (Date) jsHora.getValue();
String horaFormatada = formatarHora(dataHora);
String desligarPC = rdbPC.isSelected() ? "Sim" : "Não";
String nomeBackup = txtNomeBackup.getText();
//DTO
BancoDeDadosDTO objBancoDeDadosDTO = new BancoDeDadosDTO();
objBancoDeDadosDTO.setId(ID);
objBancoDeDadosDTO.setDiretorioOrigem(arquivoDiretorio);
objBancoDeDadosDTO.setDiretorioDestino(diretorioDestino);
objBancoDeDadosDTO.setData(dataFormatada);
objBancoDeDadosDTO.setNomeBackup(nomeBackup);
objBancoDeDadosDTO.setDesligarPC(desligarPC);
objBancoDeDadosDTO.setHora(horaFormatada);
//DAO
BancoDeDadosDAO objBancoDeDadosDAO = new BancoDeDadosDAO();
objBancoDeDadosDAO.editar(objBancoDeDadosDTO);
configurarBotoes(false, false, true, false, false, true, false, false);
limparCampos();
habilitarCampos(false, false, false, false, false, false);
popularTabelaAgendamentoBackup();
} catch (Exception e) {
// Captura e exibe qualquer exceção que possa ocorrer
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao atualizar o agendamento d buckup: "
+ e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Exclui um agendamento de backup com base no ID fornecido.
*
* Este método exclui um agendamento de backup com base no ID obtido a partir do campo de texto `txtID`.
* Após a exclusão, os campos são limpos e a tabela de agendamentos é atualizada.
*
* @throws NumberFormatException Se ocorrer um erro na conversão de texto para número.
*/
private void excluirAgendamentoBackup() {
try {
int ID = Integer.parseInt(txtID.getText());
BancoDeDadosDTO objBancoDeDadosDTO = new BancoDeDadosDTO();
objBancoDeDadosDTO.setId(ID);
BancoDeDadosDAO objBancoDeDadosDao = new BancoDeDadosDAO();
objBancoDeDadosDao.excluir(objBancoDeDadosDTO);
configurarBotoes(false, false, true, false, false, true, false, false);
habilitarCampos(false, false, false, false, false, false);
popularTabelaAgendamentoBackup();
limparCampos();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Erro - " + e, "Informação", JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Formata a exibição do componente JSpinner para exibir horas no formato "HH:mm".
*
* Este método configura o formato de exibição do componente JSpinner `jsHora` para exibir horas no formato "HH:mm".
* Isso torna a entrada e exibição de horas mais amigável para o usuário.
*/
private void formatarJSpinner() {
JSpinner.DateEditor editor = new JSpinner.DateEditor(jsHora, "HH:mm");
jsHora.setEditor(editor);
}
// Criar uma instância da classe BancoDeDadosDAO
BancoDeDadosDAO bancoDeDadosDAO = new BancoDeDadosDAO();
// Tempo em milissegundos (45 segundos)
int delay = 50000;
/**
* Um ActionListener que executa ações em resposta a eventos ActionEvent.
*
* Este ActionListener, chamado de `taskPerformer`, é configurado para ser executado em resposta a eventos ActionEvent.
* Quando acionado, ele verifica se a data e hora atual atendem a determinados critérios com base no objeto `bancoDeDadosDAO`.
* Se os critérios forem atendidos, ele inicia uma nova Thread para realizar as seguintes ações:
* 1. Chama o método `backup()` para realizar uma operação de backup.
* 2. Verifica se o `bancoDeDadosDAO` indica que o PC deve ser desligado e, se sim, chama o método `desligarPC()`.
*
* Esse ActionListener é usado para agendar a execução das ações com base em eventos e condições específicas.
*/
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (bancoDeDadosDAO.verificarDataHoraAtual()) {
new Thread(() -> {
backup();
if (bancoDeDadosDAO.verificarDesligarPC()) {
desligarPC();
}
}).start();
}
}
};
/**
* Realiza o backup dos arquivos ou diretórios especificados.
* <p>
* Este método obtém os caminhos de origem e destino do banco de dados e, em
* seguida, chama o método {@code compactarParaZip} para compactar o arquivo
* ou diretório de origem no arquivo ZIP de destino. O nome do arquivo ZIP é
* formado a partir do nome do backup e do destino.
* </p>
*
* <p>
* <b>Nota:</b> Este método assume que os caminhos de origem e destino, bem
* como o nome do backup, estão corretamente definidos no banco de dados e
* são acessíveis.</p>
*
* <p>
* Em caso de falha na compactação, as exceções são capturadas e registradas
* no console.</p>
*
*/
public void backup() {
BancoDeDadosDAO dao = new BancoDeDadosDAO();
BancoDeDadosDTO dto = dao.verificarDataHoraAtualArquivos();
SimpleDateFormat sdf = new SimpleDateFormat("-dd-MM-yyyy-HH_mm_ss");
try {
String destinoZip = dto.getDiretorioDestino() + File.separator + dto.getNomeBackup() + sdf.format(new Date()) + ".zip";
System.out.println("Origem: " + dto.getDiretorioOrigem());
System.out.println("Destino ZIP: " + destinoZip);
| CompactadorZip.compactarParaZip(dto.getDiretorioOrigem(), destinoZip, null); | 2 | 2023-12-02 02:23:51+00:00 | 12k |
tuxiaobei-scu/SCU-CCSOJ-Backend | DataBackup/src/main/java/top/hcode/hoj/manager/admin/training/AdminTrainingProblemManager.java | [
{
"identifier": "StatusFailException",
"path": "DataBackup/src/main/java/top/hcode/hoj/common/exception/StatusFailException.java",
"snippet": "public class StatusFailException extends Exception{\n public StatusFailException() {\n }\n\n public StatusFailException(String message) {\n super... | import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.hcode.hoj.common.exception.StatusFailException;
import top.hcode.hoj.crawler.problem.ProblemStrategy;
import top.hcode.hoj.manager.admin.problem.RemoteProblemManager;
import top.hcode.hoj.pojo.dto.TrainingProblemDto;
import top.hcode.hoj.pojo.entity.problem.Problem;
import top.hcode.hoj.pojo.entity.training.Training;
import top.hcode.hoj.pojo.entity.training.TrainingProblem;
import top.hcode.hoj.pojo.vo.UserRolesVo;
import top.hcode.hoj.dao.problem.ProblemEntityService;
import top.hcode.hoj.dao.training.TrainingProblemEntityService;
import top.hcode.hoj.dao.training.TrainingEntityService;
import top.hcode.hoj.utils.Constants;
import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors; | 8,209 | package top.hcode.hoj.manager.admin.training;
/**
* @Author: Himit_ZH
* @Date: 2022/3/9 20:20
* @Description:
*/
@Component
public class AdminTrainingProblemManager {
@Resource
private TrainingProblemEntityService trainingProblemEntityService;
@Resource
private TrainingEntityService trainingEntityService;
@Resource
private ProblemEntityService problemEntityService;
@Resource
private AdminTrainingRecordManager adminTrainingRecordManager;
@Resource
private RemoteProblemManager remoteProblemManager;
public HashMap<String, Object> getProblemList(Integer limit, Integer currentPage, String keyword, Boolean queryExisted, Long tid) {
if (currentPage == null || currentPage < 1) currentPage = 1;
if (limit == null || limit < 1) limit = 10;
IPage<Problem> iPage = new Page<>(currentPage, limit);
// 根据tid在TrainingProblem表中查询到对应pid集合
QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
trainingProblemQueryWrapper.eq("tid", tid).orderByAsc("display_id");
List<Long> pidList = new LinkedList<>();
List<TrainingProblem> trainingProblemList = trainingProblemEntityService.list(trainingProblemQueryWrapper);
HashMap<Long, TrainingProblem> trainingProblemMap = new HashMap<>();
trainingProblemList.forEach(trainingProblem -> {
if (!trainingProblemMap.containsKey(trainingProblem.getPid())) {
trainingProblemMap.put(trainingProblem.getPid(), trainingProblem);
}
pidList.add(trainingProblem.getPid());
});
HashMap<String, Object> trainingProblem = new HashMap<>();
QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>();
// 逻辑判断,如果是查询已有的就应该是in,如果是查询不要重复的,使用not in
if (queryExisted) {
problemQueryWrapper.in(pidList.size() > 0, "id", pidList);
} else {
// 权限需要是公开的(隐藏的,比赛中不可加入!)
problemQueryWrapper.eq("auth", 1).eq("is_group", false);
problemQueryWrapper.notIn(pidList.size() > 0, "id", pidList);
}
if (!StringUtils.isEmpty(keyword)) {
problemQueryWrapper.and(wrapper -> wrapper.like("title", keyword).or()
.like("problem_id", keyword).or()
.like("author", keyword));
}
if (pidList.size() == 0 && queryExisted) {
problemQueryWrapper = new QueryWrapper<>();
problemQueryWrapper.eq("id", null);
}
IPage<Problem> problemListPage = problemEntityService.page(iPage, problemQueryWrapper);
if (queryExisted && pidList.size() > 0) {
List<Problem> problemListPageRecords = problemListPage.getRecords();
List<Problem> sortProblemList = problemListPageRecords
.stream()
.sorted(Comparator.comparingInt(problem -> trainingProblemMap.get(problem.getId()).getRank()))
.collect(Collectors.toList());
problemListPage.setRecords(sortProblemList);
}
trainingProblem.put("problemList", problemListPage);
trainingProblem.put("trainingProblemMap", trainingProblemMap);
return trainingProblem;
}
public void updateProblem(TrainingProblem trainingProblem) throws StatusFailException {
boolean isOk = trainingProblemEntityService.saveOrUpdate(trainingProblem);
if (!isOk) {
throw new StatusFailException("修改失败!");
}
}
public void deleteProblem(Long pid,Long tid) throws StatusFailException {
boolean isOk = false;
// 训练id不为null,表示就是从比赛列表移除而已
if (tid != null) {
QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
trainingProblemQueryWrapper.eq("tid", tid).eq("pid", pid);
isOk = trainingProblemEntityService.remove(trainingProblemQueryWrapper);
} else {
/*
problem的id为其他表的外键的表中的对应数据都会被一起删除!
*/
isOk = problemEntityService.removeById(pid);
}
if (isOk) { // 删除成功
if (tid == null) {
FileUtil.del(Constants.File.TESTCASE_BASE_FOLDER.getPath() + File.separator + "problem_" + pid);
}
// 更新训练最近更新时间
UpdateWrapper<Training> trainingUpdateWrapper = new UpdateWrapper<>();
trainingUpdateWrapper.set("gmt_modified", new Date())
.eq("id", tid);
trainingEntityService.update(trainingUpdateWrapper);
} else {
throw new StatusFailException("删除失败!");
}
}
public void addProblemFromPublic(TrainingProblemDto trainingProblemDto) throws StatusFailException {
Long pid = trainingProblemDto.getPid();
Long tid = trainingProblemDto.getTid();
String displayId = trainingProblemDto.getDisplayId();
QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
trainingProblemQueryWrapper.eq("tid", tid)
.and(wrapper -> wrapper.eq("pid", pid)
.or()
.eq("display_id", displayId));
TrainingProblem trainingProblem = trainingProblemEntityService.getOne(trainingProblemQueryWrapper, false);
if (trainingProblem != null) {
throw new StatusFailException("添加失败,该题目已添加或者题目的训练展示ID已存在!");
}
TrainingProblem newTProblem = new TrainingProblem();
boolean isOk = trainingProblemEntityService.saveOrUpdate(newTProblem
.setTid(tid).setPid(pid).setDisplayId(displayId));
if (isOk) { // 添加成功
// 更新训练最近更新时间
UpdateWrapper<Training> trainingUpdateWrapper = new UpdateWrapper<>();
trainingUpdateWrapper.set("gmt_modified", new Date())
.eq("id", tid);
trainingEntityService.update(trainingUpdateWrapper);
// 异步地同步用户对该题目的提交数据
adminTrainingRecordManager.syncAlreadyRegisterUserRecord(tid, pid, newTProblem.getId());
} else {
throw new StatusFailException("添加失败!");
}
}
public void importTrainingRemoteOJProblem(String name, String problemId, Long tid) throws StatusFailException {
QueryWrapper<Problem> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("problem_id", name.toUpperCase() + "-" + problemId);
Problem problem = problemEntityService.getOne(queryWrapper, false);
// 如果该题目不存在,需要先导入
if (problem == null) {
Session session = SecurityUtils.getSubject().getSession(); | package top.hcode.hoj.manager.admin.training;
/**
* @Author: Himit_ZH
* @Date: 2022/3/9 20:20
* @Description:
*/
@Component
public class AdminTrainingProblemManager {
@Resource
private TrainingProblemEntityService trainingProblemEntityService;
@Resource
private TrainingEntityService trainingEntityService;
@Resource
private ProblemEntityService problemEntityService;
@Resource
private AdminTrainingRecordManager adminTrainingRecordManager;
@Resource
private RemoteProblemManager remoteProblemManager;
public HashMap<String, Object> getProblemList(Integer limit, Integer currentPage, String keyword, Boolean queryExisted, Long tid) {
if (currentPage == null || currentPage < 1) currentPage = 1;
if (limit == null || limit < 1) limit = 10;
IPage<Problem> iPage = new Page<>(currentPage, limit);
// 根据tid在TrainingProblem表中查询到对应pid集合
QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
trainingProblemQueryWrapper.eq("tid", tid).orderByAsc("display_id");
List<Long> pidList = new LinkedList<>();
List<TrainingProblem> trainingProblemList = trainingProblemEntityService.list(trainingProblemQueryWrapper);
HashMap<Long, TrainingProblem> trainingProblemMap = new HashMap<>();
trainingProblemList.forEach(trainingProblem -> {
if (!trainingProblemMap.containsKey(trainingProblem.getPid())) {
trainingProblemMap.put(trainingProblem.getPid(), trainingProblem);
}
pidList.add(trainingProblem.getPid());
});
HashMap<String, Object> trainingProblem = new HashMap<>();
QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>();
// 逻辑判断,如果是查询已有的就应该是in,如果是查询不要重复的,使用not in
if (queryExisted) {
problemQueryWrapper.in(pidList.size() > 0, "id", pidList);
} else {
// 权限需要是公开的(隐藏的,比赛中不可加入!)
problemQueryWrapper.eq("auth", 1).eq("is_group", false);
problemQueryWrapper.notIn(pidList.size() > 0, "id", pidList);
}
if (!StringUtils.isEmpty(keyword)) {
problemQueryWrapper.and(wrapper -> wrapper.like("title", keyword).or()
.like("problem_id", keyword).or()
.like("author", keyword));
}
if (pidList.size() == 0 && queryExisted) {
problemQueryWrapper = new QueryWrapper<>();
problemQueryWrapper.eq("id", null);
}
IPage<Problem> problemListPage = problemEntityService.page(iPage, problemQueryWrapper);
if (queryExisted && pidList.size() > 0) {
List<Problem> problemListPageRecords = problemListPage.getRecords();
List<Problem> sortProblemList = problemListPageRecords
.stream()
.sorted(Comparator.comparingInt(problem -> trainingProblemMap.get(problem.getId()).getRank()))
.collect(Collectors.toList());
problemListPage.setRecords(sortProblemList);
}
trainingProblem.put("problemList", problemListPage);
trainingProblem.put("trainingProblemMap", trainingProblemMap);
return trainingProblem;
}
public void updateProblem(TrainingProblem trainingProblem) throws StatusFailException {
boolean isOk = trainingProblemEntityService.saveOrUpdate(trainingProblem);
if (!isOk) {
throw new StatusFailException("修改失败!");
}
}
public void deleteProblem(Long pid,Long tid) throws StatusFailException {
boolean isOk = false;
// 训练id不为null,表示就是从比赛列表移除而已
if (tid != null) {
QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
trainingProblemQueryWrapper.eq("tid", tid).eq("pid", pid);
isOk = trainingProblemEntityService.remove(trainingProblemQueryWrapper);
} else {
/*
problem的id为其他表的外键的表中的对应数据都会被一起删除!
*/
isOk = problemEntityService.removeById(pid);
}
if (isOk) { // 删除成功
if (tid == null) {
FileUtil.del(Constants.File.TESTCASE_BASE_FOLDER.getPath() + File.separator + "problem_" + pid);
}
// 更新训练最近更新时间
UpdateWrapper<Training> trainingUpdateWrapper = new UpdateWrapper<>();
trainingUpdateWrapper.set("gmt_modified", new Date())
.eq("id", tid);
trainingEntityService.update(trainingUpdateWrapper);
} else {
throw new StatusFailException("删除失败!");
}
}
public void addProblemFromPublic(TrainingProblemDto trainingProblemDto) throws StatusFailException {
Long pid = trainingProblemDto.getPid();
Long tid = trainingProblemDto.getTid();
String displayId = trainingProblemDto.getDisplayId();
QueryWrapper<TrainingProblem> trainingProblemQueryWrapper = new QueryWrapper<>();
trainingProblemQueryWrapper.eq("tid", tid)
.and(wrapper -> wrapper.eq("pid", pid)
.or()
.eq("display_id", displayId));
TrainingProblem trainingProblem = trainingProblemEntityService.getOne(trainingProblemQueryWrapper, false);
if (trainingProblem != null) {
throw new StatusFailException("添加失败,该题目已添加或者题目的训练展示ID已存在!");
}
TrainingProblem newTProblem = new TrainingProblem();
boolean isOk = trainingProblemEntityService.saveOrUpdate(newTProblem
.setTid(tid).setPid(pid).setDisplayId(displayId));
if (isOk) { // 添加成功
// 更新训练最近更新时间
UpdateWrapper<Training> trainingUpdateWrapper = new UpdateWrapper<>();
trainingUpdateWrapper.set("gmt_modified", new Date())
.eq("id", tid);
trainingEntityService.update(trainingUpdateWrapper);
// 异步地同步用户对该题目的提交数据
adminTrainingRecordManager.syncAlreadyRegisterUserRecord(tid, pid, newTProblem.getId());
} else {
throw new StatusFailException("添加失败!");
}
}
public void importTrainingRemoteOJProblem(String name, String problemId, Long tid) throws StatusFailException {
QueryWrapper<Problem> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("problem_id", name.toUpperCase() + "-" + problemId);
Problem problem = problemEntityService.getOne(queryWrapper, false);
// 如果该题目不存在,需要先导入
if (problem == null) {
Session session = SecurityUtils.getSubject().getSession(); | UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); | 7 | 2023-12-03 14:15:51+00:00 | 12k |
yichenhsiaonz/EscAIpe-room-final | src/main/java/nz/ac/auckland/se206/controllers/LabController.java | [
{
"identifier": "App",
"path": "src/main/java/nz/ac/auckland/se206/App.java",
"snippet": "public class App extends Application {\n\n private static Scene scene;\n public static ControlRoomController controlRoomController;\n public static LabController labController;\n public static KitchenController... | import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import nz.ac.auckland.se206.App;
import nz.ac.auckland.se206.GameState;
import nz.ac.auckland.se206.SceneManager.AppUi;
import nz.ac.auckland.se206.TextToSpeechManager; | 10,577 | package nz.ac.auckland.se206.controllers;
/**
* Controller for the lab scene. This class controls the items in the lab and the functionality of
* them.
*/
public class LabController {
public static LabController instance;
@FXML private AnchorPane contentPane;
@FXML private Rectangle printer;
@FXML private ImageView rightArrow;
@FXML private ImageView rightGlowArrow;
@FXML private ImageView printerGlow;
@FXML private ImageView character;
@FXML private ImageView running;
@FXML private AnchorPane room;
@FXML private HBox dialogueHorizontalBox;
@FXML private VBox bottomVerticalBox;
@FXML private Pane inventoryPane;
@FXML private VBox hintVerticalBox;
@FXML private ImageView neutralAi;
@FXML private ImageView loadingAi;
@FXML private ImageView talkingAi;
@FXML private ImageView doorGlow;
@FXML private ImageView usbGlow;
@FXML private ImageView usb;
@FXML private Button muteButton;
private double startX = 1512;
private double startY = 814;
/** Initalizes the lab scene. This method is called when the game starts. */
public void initialize() {
SharedElements.initialize(
room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane);
| package nz.ac.auckland.se206.controllers;
/**
* Controller for the lab scene. This class controls the items in the lab and the functionality of
* them.
*/
public class LabController {
public static LabController instance;
@FXML private AnchorPane contentPane;
@FXML private Rectangle printer;
@FXML private ImageView rightArrow;
@FXML private ImageView rightGlowArrow;
@FXML private ImageView printerGlow;
@FXML private ImageView character;
@FXML private ImageView running;
@FXML private AnchorPane room;
@FXML private HBox dialogueHorizontalBox;
@FXML private VBox bottomVerticalBox;
@FXML private Pane inventoryPane;
@FXML private VBox hintVerticalBox;
@FXML private ImageView neutralAi;
@FXML private ImageView loadingAi;
@FXML private ImageView talkingAi;
@FXML private ImageView doorGlow;
@FXML private ImageView usbGlow;
@FXML private ImageView usb;
@FXML private Button muteButton;
private double startX = 1512;
private double startY = 814;
/** Initalizes the lab scene. This method is called when the game starts. */
public void initialize() {
SharedElements.initialize(
room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane);
| GameState.goToInstant(startX, startY, character, running); | 1 | 2023-12-02 04:57:43+00:00 | 12k |
nageoffer/shortlink | project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java | [
{
"identifier": "LinkAccessLogsDO",
"path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java",
"snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ... | import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO;
import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO;
import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO;
import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO;
import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO;
import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper;
import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper;
import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper;
import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper;
import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper;
import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper;
import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper;
import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsAccessRecordReqDTO;
import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO;
import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO;
import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO;
import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO;
import com.nageoffer.shortlink.project.service.ShortLinkStatsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger; | 10,281 | /*
* 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 com.nageoffer.shortlink.project.service.impl;
/**
* 短链接监控接口实现层
* 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料
*/
@Service
@RequiredArgsConstructor
public class ShortLinkStatsServiceImpl implements ShortLinkStatsService {
private final LinkAccessStatsMapper linkAccessStatsMapper;
private final LinkLocaleStatsMapper linkLocaleStatsMapper; | /*
* 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 com.nageoffer.shortlink.project.service.impl;
/**
* 短链接监控接口实现层
* 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料
*/
@Service
@RequiredArgsConstructor
public class ShortLinkStatsServiceImpl implements ShortLinkStatsService {
private final LinkAccessStatsMapper linkAccessStatsMapper;
private final LinkLocaleStatsMapper linkLocaleStatsMapper; | private final LinkAccessLogsMapper linkAccessLogsMapper; | 5 | 2023-11-19 16:04:32+00:00 | 12k |
NEWCIH2023/galois | src/main/java/io/liuguangsheng/galois/service/spring/runners/AgentInitializeRunner.java | [
{
"identifier": "AgentService",
"path": "src/main/java/io/liuguangsheng/galois/service/AgentService.java",
"snippet": "public abstract class AgentService {\n\n /**\n * 文件变更监听器列表\n */\n protected List<FileChangedListener> listeners = new ArrayList<>(4);\n /**\n * 对应的Bean重载的service\n ... | import io.liuguangsheng.galois.utils.ClassUtil;
import io.liuguangsheng.galois.utils.GaloisLog;
import org.slf4j.Logger;
import org.springframework.context.ConfigurableApplicationContext;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.stream.Collectors;
import static io.liuguangsheng.galois.constants.ClassNameConstant.PACKAGE_SERVICE;
import io.liuguangsheng.galois.service.AgentService;
import io.liuguangsheng.galois.service.BeanReloader;
import io.liuguangsheng.galois.service.annotation.LazyBean;
import io.liuguangsheng.galois.service.monitor.ApacheFileWatchService;
import io.liuguangsheng.galois.service.monitor.FileChangedListener;
import io.liuguangsheng.galois.service.monitor.FileWatchService; | 7,250 | /*
* MIT License
*
* Copyright (c) [2023] [liuguangsheng]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.liuguangsheng.galois.service.spring.runners;
/**
* agent service init runner
*
* @author liuguangsheng
*/
public class AgentInitializeRunner extends AbstractRunner {
private static final Logger logger = new GaloisLog(AgentInitializeRunner.class);
private static final FileWatchService watchService = ApacheFileWatchService.getInstance();
@Override
public void started(ConfigurableApplicationContext context) {
if (!canInvoke()) {
return;
}
logger.info("{} Started with context {}.", getClass().getSimpleName(), context.getId());
try {
Set<Class<?>> lazyBeanFactorys = ClassUtil.scanAnnotationClass(PACKAGE_SERVICE, LazyBean.class); | /*
* MIT License
*
* Copyright (c) [2023] [liuguangsheng]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.liuguangsheng.galois.service.spring.runners;
/**
* agent service init runner
*
* @author liuguangsheng
*/
public class AgentInitializeRunner extends AbstractRunner {
private static final Logger logger = new GaloisLog(AgentInitializeRunner.class);
private static final FileWatchService watchService = ApacheFileWatchService.getInstance();
@Override
public void started(ConfigurableApplicationContext context) {
if (!canInvoke()) {
return;
}
logger.info("{} Started with context {}.", getClass().getSimpleName(), context.getId());
try {
Set<Class<?>> lazyBeanFactorys = ClassUtil.scanAnnotationClass(PACKAGE_SERVICE, LazyBean.class); | Set<AgentService> agentServices = ClassUtil.scanBaseClass(PACKAGE_SERVICE, AgentService.class) | 0 | 2023-11-22 04:51:35+00:00 | 12k |
TongchengOpenSource/ckibana | src/main/java/com/ly/ckibana/parser/AggResultParser.java | [
{
"identifier": "AggBucketsName",
"path": "src/main/java/com/ly/ckibana/model/enums/AggBucketsName.java",
"snippet": "public enum AggBucketsName {\n BUCKETS,\n VALUES\n}"
},
{
"identifier": "AggType",
"path": "src/main/java/com/ly/ckibana/model/enums/AggType.java",
"snippet": "publ... | import com.alibaba.fastjson2.JSONObject;
import com.ly.ckibana.model.enums.AggBucketsName;
import com.ly.ckibana.model.enums.AggType;
import com.ly.ckibana.model.request.CkRequest;
import com.ly.ckibana.model.request.CkRequestContext;
import com.ly.ckibana.model.response.Response;
import com.ly.ckibana.service.CkService;
import com.ly.ckibana.strategy.aggs.Aggregation;
import com.ly.ckibana.strategy.aggs.FiltersAggregation;
import com.ly.ckibana.util.JSONUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 8,198 | /*
* Copyright (c) 2023 LY.com 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.ly.ckibana.parser;
/**
* 封装结果类.
*
* @author caojiaqiang
*/
@Service
public class AggResultParser extends HitsResultParser {
@Resource
private CkService ckService;
@Resource
private ResultParser resultParseService;
@Resource
private AggResultParserHelper aggResultParserHelper;
/**
* todo range子agg 请求1->n+1,filters 1->n待优化
* 基于查询参数解析获取聚合结果.
* filters是和其他agg组合使用。支持n个filter,每种filter有自己的query条件。filters会返回n组数据返回。
* 其他聚合进返回1组数据
*
* @param ckRequestContext ckRequestContext
* @return Response
* @throws Exception 异常
*/
public Response executeByAgg(CkRequestContext ckRequestContext) throws Exception {
List<Aggregation> filtersAggList = ckRequestContext.getAggs().stream().filter(each -> AggType.FILTERS.equals(each.getAggType())).toList();
if (!filtersAggList.isEmpty()) { | /*
* Copyright (c) 2023 LY.com 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.ly.ckibana.parser;
/**
* 封装结果类.
*
* @author caojiaqiang
*/
@Service
public class AggResultParser extends HitsResultParser {
@Resource
private CkService ckService;
@Resource
private ResultParser resultParseService;
@Resource
private AggResultParserHelper aggResultParserHelper;
/**
* todo range子agg 请求1->n+1,filters 1->n待优化
* 基于查询参数解析获取聚合结果.
* filters是和其他agg组合使用。支持n个filter,每种filter有自己的query条件。filters会返回n组数据返回。
* 其他聚合进返回1组数据
*
* @param ckRequestContext ckRequestContext
* @return Response
* @throws Exception 异常
*/
public Response executeByAgg(CkRequestContext ckRequestContext) throws Exception {
List<Aggregation> filtersAggList = ckRequestContext.getAggs().stream().filter(each -> AggType.FILTERS.equals(each.getAggType())).toList();
if (!filtersAggList.isEmpty()) { | return executeFiltersAggs(ckRequestContext, (FiltersAggregation) filtersAggList.get(0)); | 7 | 2023-11-21 09:12:07+00:00 | 12k |
libgdx/gdx-particle-editor | core/src/main/java/com/ray3k/gdxparticleeditor/widgets/subpanels/CountSubPanel.java | [
{
"identifier": "UndoManager",
"path": "core/src/main/java/com/ray3k/gdxparticleeditor/undo/UndoManager.java",
"snippet": "public class UndoManager {\n public final static Array<Undoable> undoables = new Array<>();\n public static int undoIndex = -1;\n\n public static void add(Undoable undoable... | import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Align;
import com.ray3k.gdxparticleeditor.undo.UndoManager;
import com.ray3k.gdxparticleeditor.undo.undoables.CountMaxUndoable;
import com.ray3k.gdxparticleeditor.undo.undoables.CountMinUndoable;
import com.ray3k.gdxparticleeditor.widgets.Panel;
import com.ray3k.stripe.Spinner;
import com.ray3k.stripe.Spinner.Orientation;
import static com.ray3k.gdxparticleeditor.Core.selectedEmitter;
import static com.ray3k.gdxparticleeditor.Core.skin;
import static com.ray3k.gdxparticleeditor.Listeners.*;
import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.spinnerStyle;
import static com.ray3k.gdxparticleeditor.widgets.styles.Styles.tooltipBottomArrowStyle; | 7,878 | package com.ray3k.gdxparticleeditor.widgets.subpanels;
/**
* A widget that allows the user to modify the Count value of the particle effect specifically. Numeric spinners for min
* and max.
*/
public class CountSubPanel extends Panel {
public CountSubPanel() {
setTouchable(Touchable.enabled);
final var itemSpacing = 5;
final var gap = 15;
final var spinnerWidth = 50;
tabTable.left();
var label = new Label("Count", skin, "header");
tabTable.add(label);
bodyTable.defaults().space(itemSpacing);
bodyTable.left();
label = new Label("Min:", skin);
bodyTable.add(label);
| package com.ray3k.gdxparticleeditor.widgets.subpanels;
/**
* A widget that allows the user to modify the Count value of the particle effect specifically. Numeric spinners for min
* and max.
*/
public class CountSubPanel extends Panel {
public CountSubPanel() {
setTouchable(Touchable.enabled);
final var itemSpacing = 5;
final var gap = 15;
final var spinnerWidth = 50;
tabTable.left();
var label = new Label("Count", skin, "header");
tabTable.add(label);
bodyTable.defaults().space(itemSpacing);
bodyTable.left();
label = new Label("Min:", skin);
bodyTable.add(label);
| var minSpinner = new Spinner(selectedEmitter.getMinParticleCount(), 1, 0, Orientation.RIGHT_STACK, spinnerStyle); | 6 | 2023-11-24 15:58:20+00:00 | 12k |
siam1026/siam-server | siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/controller/member/MemberAdvertisementController.java | [
{
"identifier": "BusinessType",
"path": "siam-common/src/main/java/com/siam/package_common/constant/BusinessType.java",
"snippet": "public class BusinessType {\n\n //超级管理员的主键id\n public static final int ADMIN_ID = 1;\n\n //TODO-验证码需要对小程序端、商家端、调度后台进行区分\n //1、验证码发送记录表\n // 注册\n public st... | import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siam.package_common.constant.BusinessType;
import com.siam.package_common.constant.Quantity;
import com.siam.package_common.entity.BasicData;
import com.siam.package_common.entity.BasicResult;
import com.siam.package_common.util.ImageComposeUtils;
import com.siam.package_common.util.OSSUtils;
import com.siam.package_weixin_basic.util.WxQrCodeUtils;
import com.siam.system.modular.package_goods.entity.Advertisement;
import com.siam.system.modular.package_goods.model.param.AdvertisementParam;
import com.siam.system.modular.package_goods.service.AdvertisementService;
import com.siam.system.modular.package_user.auth.cache.MemberSessionManager;
import com.siam.system.modular.package_user.entity.Member;
import com.siam.system.util.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
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.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException; | 7,888 | package com.siam.system.modular.package_goods.controller.member;
@Slf4j
@RestController
@RequestMapping(value = "/rest/member/advertisement")
@Transactional(rollbackFor = Exception.class)
@Api(tags = "用户广告轮播图模块相关接口", description = "MemberAdvertisementController")
public class MemberAdvertisementController {
@Autowired
private AdvertisementService advertisementService;
@Autowired | package com.siam.system.modular.package_goods.controller.member;
@Slf4j
@RestController
@RequestMapping(value = "/rest/member/advertisement")
@Transactional(rollbackFor = Exception.class)
@Api(tags = "用户广告轮播图模块相关接口", description = "MemberAdvertisementController")
public class MemberAdvertisementController {
@Autowired
private AdvertisementService advertisementService;
@Autowired | private OSSUtils ossUtils; | 5 | 2023-11-26 12:41:06+00:00 | 12k |
windsbell/shardingkey-autofill | src/main/java/com/windsbell/shardingkey/autofill/handler/BusinessKeyStrategyHelper.java | [
{
"identifier": "StatementParser",
"path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/StatementParser.java",
"snippet": "public abstract class StatementParser implements SelectVisitor, FromItemVisitor, ExpressionVisitor, ItemsListVisitor, SelectItemVisitor, StatementVisitor {\n\n pr... | import com.windsbell.shardingkey.autofill.jsqlparser.StatementParser;
import com.windsbell.shardingkey.autofill.strategy.BusinessKeyStrategy;
import com.windsbell.shardingkey.autofill.strategy.BusinessStrategy;
import com.windsbell.shardingkey.autofill.strategy.TableShardingKeyStrategy;
import lombok.Getter;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.JdbcParameter;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.Join;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; | 7,362 | package com.windsbell.shardingkey.autofill.handler;
/**
* 业务字段策略执行器:
* 匹配SQL中,找到必填业务字段和值,找到任意业务字段和值
*/
public class BusinessKeyStrategyHelper extends StatementParser {
private final Map<String, Map<String, BusinessStrategy<Object>>> matchNecessaryColumnMap = new LinkedHashMap<>(); // 匹配必填业务字段map
private final Map<String, Map<String, BusinessStrategy<Object>>> matchAnyOneColumnMap = new LinkedHashMap<>(); // 匹配任意业务字段map
private final List<?> parameterList; // 占位符内容值列表
@Getter | package com.windsbell.shardingkey.autofill.handler;
/**
* 业务字段策略执行器:
* 匹配SQL中,找到必填业务字段和值,找到任意业务字段和值
*/
public class BusinessKeyStrategyHelper extends StatementParser {
private final Map<String, Map<String, BusinessStrategy<Object>>> matchNecessaryColumnMap = new LinkedHashMap<>(); // 匹配必填业务字段map
private final Map<String, Map<String, BusinessStrategy<Object>>> matchAnyOneColumnMap = new LinkedHashMap<>(); // 匹配任意业务字段map
private final List<?> parameterList; // 占位符内容值列表
@Getter | private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 表分片键映射策略map | 3 | 2023-11-23 09:05:56+00:00 | 12k |
3dcitydb/citydb-tool | citydb-operation/src/main/java/org/citydb/operation/importer/ImportHelper.java | [
{
"identifier": "FileLocator",
"path": "citydb-core/src/main/java/org/citydb/core/file/FileLocator.java",
"snippet": "public class FileLocator {\n private final URL url;\n private final Path path;\n\n private FileLocator(URL url) {\n this.url = Objects.requireNonNull(url, \"The URL must ... | import org.citydb.core.file.FileLocator;
import org.citydb.database.adapter.DatabaseAdapter;
import org.citydb.database.schema.SchemaMapping;
import org.citydb.database.schema.Table;
import org.citydb.model.common.ExternalFile;
import org.citydb.model.common.Visitable;
import org.citydb.model.feature.Feature;
import org.citydb.model.feature.FeatureDescriptor;
import org.citydb.operation.importer.common.DatabaseImporter;
import org.citydb.operation.importer.feature.FeatureImporter;
import org.citydb.operation.importer.reference.CacheType;
import org.citydb.operation.importer.reference.ReferenceCache;
import org.citydb.operation.importer.reference.ReferenceManager;
import org.citydb.operation.importer.util.*;
import org.citydb.operation.util.FeatureStatistics;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map; | 10,209 | /*
* citydb-tool - Command-line tool for the 3D City Database
* https://www.3dcitydb.org/
*
* Copyright 2022-2023
* virtualcitysystems GmbH, Germany
* https://vc.systems/
*
* 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.citydb.operation.importer;
public class ImportHelper {
private final DatabaseAdapter adapter;
private final ReferenceManager referenceManager;
private final ImportLogger logger;
private final StatisticsConsumer statisticsConsumer;
private final Connection connection;
private final SchemaMapping schemaMapping;
private final TableHelper tableHelper;
private final SequenceHelper sequenceHelper;
private final FeatureStatistics statistics;
private final Map<CacheType, ReferenceCache> caches = new EnumMap<>(CacheType.class);
private final List<ImportLogEntry> logEntries = new ArrayList<>();
private final int batchSize;
private final boolean autoCommit;
private SequenceValues sequenceValues;
private int batchCounter;
ImportHelper(DatabaseAdapter adapter, ImportOptions options, ReferenceManager referenceManager,
ImportLogger logger, StatisticsConsumer statisticsConsumer, boolean autoCommit) throws SQLException {
this.adapter = adapter;
this.referenceManager = referenceManager;
this.logger = logger;
this.statisticsConsumer = statisticsConsumer;
this.autoCommit = autoCommit;
connection = adapter.getPool().getConnection(false);
schemaMapping = adapter.getSchemaAdapter().getSchemaMapping();
tableHelper = new TableHelper(this);
sequenceHelper = new SequenceHelper(this);
statistics = new FeatureStatistics(schemaMapping);
batchSize = options.getBatchSize() > 0 ?
Math.min(options.getBatchSize(), adapter.getSchemaAdapter().getMaximumBatchSize()) :
ImportOptions.DEFAULT_BATCH_SIZE;
}
public DatabaseAdapter getAdapter() {
return adapter;
}
public SchemaMapping getSchemaMapping() {
return schemaMapping;
}
public Connection getConnection() {
return connection;
}
public TableHelper getTableHelper() {
return tableHelper;
}
public SequenceValues getSequenceValues() {
return sequenceValues;
}
public ReferenceCache getOrCreateReferenceCache(CacheType type) {
return caches.computeIfAbsent(type, v -> new ReferenceCache(type));
}
public FileLocator getFileLocator(ExternalFile file) {
if (file != null) {
return file.getPath().map(FileLocator::of)
.orElseGet(() -> FileLocator.of(file.getFileLocation()));
}
return null;
}
FeatureDescriptor importFeature(Feature feature) throws ImportException {
try {
generateSequenceValues(feature);
FeatureDescriptor descriptor = tableHelper.getOrCreateImporter(FeatureImporter.class).doImport(feature);
if (statisticsConsumer != null) {
statistics.add(feature);
}
if (logger != null) {
logEntries.add(ImportLogEntry.of(feature, descriptor));
}
executeBatch(false, autoCommit);
return descriptor;
} catch (Exception e) {
throw new ImportException("Failed to import feature.", e);
}
}
private void generateSequenceValues(Visitable visitable) throws SQLException {
sequenceValues = sequenceHelper.nextSequenceValues(visitable);
}
void executeBatch(boolean force, boolean commit) throws ImportException, SQLException {
if (force || ++batchCounter == batchSize) {
try {
if (batchCounter > 0) { | /*
* citydb-tool - Command-line tool for the 3D City Database
* https://www.3dcitydb.org/
*
* Copyright 2022-2023
* virtualcitysystems GmbH, Germany
* https://vc.systems/
*
* 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.citydb.operation.importer;
public class ImportHelper {
private final DatabaseAdapter adapter;
private final ReferenceManager referenceManager;
private final ImportLogger logger;
private final StatisticsConsumer statisticsConsumer;
private final Connection connection;
private final SchemaMapping schemaMapping;
private final TableHelper tableHelper;
private final SequenceHelper sequenceHelper;
private final FeatureStatistics statistics;
private final Map<CacheType, ReferenceCache> caches = new EnumMap<>(CacheType.class);
private final List<ImportLogEntry> logEntries = new ArrayList<>();
private final int batchSize;
private final boolean autoCommit;
private SequenceValues sequenceValues;
private int batchCounter;
ImportHelper(DatabaseAdapter adapter, ImportOptions options, ReferenceManager referenceManager,
ImportLogger logger, StatisticsConsumer statisticsConsumer, boolean autoCommit) throws SQLException {
this.adapter = adapter;
this.referenceManager = referenceManager;
this.logger = logger;
this.statisticsConsumer = statisticsConsumer;
this.autoCommit = autoCommit;
connection = adapter.getPool().getConnection(false);
schemaMapping = adapter.getSchemaAdapter().getSchemaMapping();
tableHelper = new TableHelper(this);
sequenceHelper = new SequenceHelper(this);
statistics = new FeatureStatistics(schemaMapping);
batchSize = options.getBatchSize() > 0 ?
Math.min(options.getBatchSize(), adapter.getSchemaAdapter().getMaximumBatchSize()) :
ImportOptions.DEFAULT_BATCH_SIZE;
}
public DatabaseAdapter getAdapter() {
return adapter;
}
public SchemaMapping getSchemaMapping() {
return schemaMapping;
}
public Connection getConnection() {
return connection;
}
public TableHelper getTableHelper() {
return tableHelper;
}
public SequenceValues getSequenceValues() {
return sequenceValues;
}
public ReferenceCache getOrCreateReferenceCache(CacheType type) {
return caches.computeIfAbsent(type, v -> new ReferenceCache(type));
}
public FileLocator getFileLocator(ExternalFile file) {
if (file != null) {
return file.getPath().map(FileLocator::of)
.orElseGet(() -> FileLocator.of(file.getFileLocation()));
}
return null;
}
FeatureDescriptor importFeature(Feature feature) throws ImportException {
try {
generateSequenceValues(feature);
FeatureDescriptor descriptor = tableHelper.getOrCreateImporter(FeatureImporter.class).doImport(feature);
if (statisticsConsumer != null) {
statistics.add(feature);
}
if (logger != null) {
logEntries.add(ImportLogEntry.of(feature, descriptor));
}
executeBatch(false, autoCommit);
return descriptor;
} catch (Exception e) {
throw new ImportException("Failed to import feature.", e);
}
}
private void generateSequenceValues(Visitable visitable) throws SQLException {
sequenceValues = sequenceHelper.nextSequenceValues(visitable);
}
void executeBatch(boolean force, boolean commit) throws ImportException, SQLException {
if (force || ++batchCounter == batchSize) {
try {
if (batchCounter > 0) { | for (Table table : tableHelper.getCommitOrder()) { | 3 | 2023-11-19 12:29:54+00:00 | 12k |
magmamaintained/Magma-1.12.2 | src/main/java/co/aikar/timings/TimingsReportListener.java | [
{
"identifier": "Bukkit",
"path": "src/main/java/org/bukkit/Bukkit.java",
"snippet": "public final class Bukkit {\n private static Server server;\n\n /**\n * Static class cannot be initialized.\n */\n private Bukkit() {}\n\n /**\n * Gets the current {@link Server} singleton\n ... | import java.util.List;
import com.google.common.collect.Lists;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.MessageCommandSender;
import org.bukkit.command.RemoteConsoleCommandSender; | 10,479 | package co.aikar.timings;
@SuppressWarnings("WeakerAccess")
public class TimingsReportListener implements MessageCommandSender {
private final List<CommandSender> senders;
private final Runnable onDone;
private String timingsURL;
public TimingsReportListener(CommandSender senders) {
this(senders, null);
}
public TimingsReportListener(CommandSender sender, Runnable onDone) {
this(Lists.newArrayList(sender), onDone);
}
public TimingsReportListener(List<CommandSender> senders) {
this(senders, null);
}
public TimingsReportListener(List<CommandSender> senders, Runnable onDone) {
Validate.notNull(senders);
Validate.notEmpty(senders);
this.senders = Lists.newArrayList(senders);
this.onDone = onDone;
}
public String getTimingsURL() {
return timingsURL;
}
public void done() {
done(null);
}
public void done(String url) {
this.timingsURL = url;
if (onDone != null) {
onDone.run();
}
for (CommandSender sender : senders) {
if (sender instanceof TimingsReportListener) {
((TimingsReportListener) sender).done();
}
}
}
@Override
public void sendMessage(String message) {
senders.forEach((sender) -> sender.sendMessage(message));
}
public void addConsoleIfNeeded() {
boolean hasConsole = false;
for (CommandSender sender : this.senders) { | package co.aikar.timings;
@SuppressWarnings("WeakerAccess")
public class TimingsReportListener implements MessageCommandSender {
private final List<CommandSender> senders;
private final Runnable onDone;
private String timingsURL;
public TimingsReportListener(CommandSender senders) {
this(senders, null);
}
public TimingsReportListener(CommandSender sender, Runnable onDone) {
this(Lists.newArrayList(sender), onDone);
}
public TimingsReportListener(List<CommandSender> senders) {
this(senders, null);
}
public TimingsReportListener(List<CommandSender> senders, Runnable onDone) {
Validate.notNull(senders);
Validate.notEmpty(senders);
this.senders = Lists.newArrayList(senders);
this.onDone = onDone;
}
public String getTimingsURL() {
return timingsURL;
}
public void done() {
done(null);
}
public void done(String url) {
this.timingsURL = url;
if (onDone != null) {
onDone.run();
}
for (CommandSender sender : senders) {
if (sender instanceof TimingsReportListener) {
((TimingsReportListener) sender).done();
}
}
}
@Override
public void sendMessage(String message) {
senders.forEach((sender) -> sender.sendMessage(message));
}
public void addConsoleIfNeeded() {
boolean hasConsole = false;
for (CommandSender sender : this.senders) { | if (sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) { | 4 | 2023-11-22 11:25:51+00:00 | 12k |
logaritex/assistant-api | src/test/java/com/logaritex/ai/api/samples/chat/ChatCompletionFunctionToolDemo.java | [
{
"identifier": "ChatCompletionApi",
"path": "src/main/java/com/logaritex/ai/api/ChatCompletionApi.java",
"snippet": "public class ChatCompletionApi {\n\n\tprivate static final String DEFAULT_BASE_URL = \"https://api.openai.com\";\n\tprivate static final String DEFAULT_EMBEDDING_MODEL = \"text-embedding... | import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.logaritex.ai.api.ChatCompletionApi;
import com.logaritex.ai.api.ChatCompletionApi.ChatCompletion;
import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionMessage;
import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionMessage.Role;
import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionMessage.ToolCall;
import com.logaritex.ai.api.ChatCompletionApi.ChatCompletionRequest;
import com.logaritex.ai.api.samples.function.WeatherFunction;
import com.logaritex.ai.api.samples.function.WeatherFunction.Response; | 7,836 | /*
* Copyright 2023-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.logaritex.ai.api.samples.chat;
/**
* Based on the OpenAI Function Calling tutorial:
* https://platform.openai.com/docs/guides/function-calling/parallel-function-calling
*
* @author Christian Tzolov
*/
public class ChatCompletionFunctionToolDemo {
public static void main(String[] args) {
var weatherService = new WeatherFunction(System.getenv("OPEN_WEATHER_MAP_API_KEY"));
| /*
* Copyright 2023-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.logaritex.ai.api.samples.chat;
/**
* Based on the OpenAI Function Calling tutorial:
* https://platform.openai.com/docs/guides/function-calling/parallel-function-calling
*
* @author Christian Tzolov
*/
public class ChatCompletionFunctionToolDemo {
public static void main(String[] args) {
var weatherService = new WeatherFunction(System.getenv("OPEN_WEATHER_MAP_API_KEY"));
| ChatCompletionApi completionApi = new ChatCompletionApi(System.getenv("OPENAI_API_KEY")); | 0 | 2023-11-25 18:52:37+00:00 | 12k |
Barsanti5BI/flight-simulator | src/Aereoporto/Aereoporto.java | [
{
"identifier": "Aereo",
"path": "src/Aereo/Aereo.java",
"snippet": "public abstract class Aereo extends Thread{\n public int id;\n public String destinazione;\n public int posizione;\n public Gate gate;\n private ArrayList<Bagno> bagni;\n private ScatolaNera scatolaNera;\n private... | import Aereo.Aereo;
import Aereoporto.Common.ListaOggetti;
import Aereoporto.ZonaArrivi.ZonaArrivi;
import Aereoporto.ZonaCheckIn.NastroTrasportatore;
import Aereoporto.ZonaCheckIn.ZonaCheckIn;
import Aereoporto.ZonaControlli.ZonaControlli;
import Aereoporto.ZonaControlli.ZonaControlliBagagliStiva;
import Aereoporto.ZonaEntrata.ZonaEntrata;
import Aereoporto.ZonaNegozi.ZonaNegozi;
import Aereoporto.ZonaPartenze.ZonaPartenze;
import Persona.ImpiegatoControlliStiva;
import Persona.Turista;
import TorreDiControllo.Viaggio;
import java.util.ArrayList;
import java.util.LinkedList; | 9,646 | package Aereoporto;
public class Aereoporto {
ZonaEntrata zonaEntrata;
ZonaCheckIn zonaCheckIn;
ZonaControlli zonaControlli; | package Aereoporto;
public class Aereoporto {
ZonaEntrata zonaEntrata;
ZonaCheckIn zonaCheckIn;
ZonaControlli zonaControlli; | ZonaControlliBagagliStiva zonaControlliBagagliStiva; | 6 | 2023-11-18 07:13:43+00:00 | 12k |
Youkehai/openai_assistants_java | assistants-front/src/main/java/com/kh/assistants/front/controller/AssistantsApiController.java | [
{
"identifier": "CommonPathReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/CommonPathReq.java",
"snippet": "@Data\n@Accessors(chain = true)\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommonPathReq {\n private fin... | import io.github.youkehai.assistant.core.req.CommonPathReq;
import io.github.youkehai.assistant.core.req.PageReq;
import io.github.youkehai.assistant.core.req.assistants.CreateAssistantFileReq;
import io.github.youkehai.assistant.core.req.message.CreateAndRunReq;
import io.github.youkehai.assistant.core.req.message.CreateMessageReq;
import io.github.youkehai.assistant.core.req.run.CreateRunReq;
import io.github.youkehai.assistant.core.resp.BasePageResp;
import io.github.youkehai.assistant.core.resp.assistants.AssistantFile;
import io.github.youkehai.assistant.core.resp.assistants.Assistants;
import io.github.youkehai.assistant.core.resp.file.File;
import io.github.youkehai.assistant.core.resp.message.Message;
import io.github.youkehai.assistant.core.resp.run.Run;
import io.github.youkehai.assistant.core.resp.run.RunStep;
import io.github.youkehai.assistant.core.resp.thread.Thread;
import io.github.youkehai.assistant.core.service.AssistantsMessageApiService;
import io.github.youkehai.assistant.core.service.AssistantsRunApiService;
import io.github.youkehai.assistant.core.service.AssistantsService;
import io.github.youkehai.assistant.core.service.AssistantsThreadApiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; | 7,311 | package com.kh.assistants.front.controller;
/**
* assistants api
*/
@AllArgsConstructor
@Tag(name = "assistantsAPI")
@RestController
@RequestMapping("/assistant")
@Slf4j
public class AssistantsApiController {
private final AssistantsMessageApiService assistantsMessageApiService;
private final AssistantsRunApiService assistantsRunApiService;
private final AssistantsService assistantsService;
private final AssistantsThreadApiService assistantsThreadApiService;
@Operation(summary = "获取消息列表")
@GetMapping("/message/{threadId}")
public BasePageResp<Message> messageList(@PathVariable("threadId") String threadId, PageReq pageReqVO) {
BasePageResp<Message> messageList = assistantsMessageApiService.getMessageList(threadId, pageReqVO);
for (Message datum : messageList.getData()) {
log.info("测试:{}", datum);
}
return messageList;
}
@Operation(summary = "发送并运行消息")
@PostMapping("/message/{threadId}")
public Run messageList(@PathVariable("threadId") String threadId, CreateAndRunReq req) {
assistantsMessageApiService.createMessage(threadId, new CreateMessageReq().setContent(req.getContent()));
return assistantsRunApiService.createRun(threadId, new CreateRunReq().setAssistant_id(req.getAssistant_id()));
}
@Operation(summary = "获取线程信息")
@GetMapping("/thread/{threadId}")
public Thread messageList(@PathVariable("threadId") String threadId) {
return assistantsThreadApiService.retrieveThread(threadId);
}
@Operation(summary = "获取线程信息")
@GetMapping("/assistants/{assistantsId}")
public Assistants retrieveAssistants(@PathVariable("assistantsId") String assistantsId) {
return assistantsService.retrieveAssistants(assistantsId);
}
@Operation(summary = "单纯的只上传文件,给某次问答使用")
@GetMapping("/upload")
public File retrieveAssistants(MultipartFile file) {
return assistantsService.upload(file);
}
@Operation(summary = "上传文件并绑定具体的 assistant")
@PostMapping("/createAssistantFile/{assistantsId}") | package com.kh.assistants.front.controller;
/**
* assistants api
*/
@AllArgsConstructor
@Tag(name = "assistantsAPI")
@RestController
@RequestMapping("/assistant")
@Slf4j
public class AssistantsApiController {
private final AssistantsMessageApiService assistantsMessageApiService;
private final AssistantsRunApiService assistantsRunApiService;
private final AssistantsService assistantsService;
private final AssistantsThreadApiService assistantsThreadApiService;
@Operation(summary = "获取消息列表")
@GetMapping("/message/{threadId}")
public BasePageResp<Message> messageList(@PathVariable("threadId") String threadId, PageReq pageReqVO) {
BasePageResp<Message> messageList = assistantsMessageApiService.getMessageList(threadId, pageReqVO);
for (Message datum : messageList.getData()) {
log.info("测试:{}", datum);
}
return messageList;
}
@Operation(summary = "发送并运行消息")
@PostMapping("/message/{threadId}")
public Run messageList(@PathVariable("threadId") String threadId, CreateAndRunReq req) {
assistantsMessageApiService.createMessage(threadId, new CreateMessageReq().setContent(req.getContent()));
return assistantsRunApiService.createRun(threadId, new CreateRunReq().setAssistant_id(req.getAssistant_id()));
}
@Operation(summary = "获取线程信息")
@GetMapping("/thread/{threadId}")
public Thread messageList(@PathVariable("threadId") String threadId) {
return assistantsThreadApiService.retrieveThread(threadId);
}
@Operation(summary = "获取线程信息")
@GetMapping("/assistants/{assistantsId}")
public Assistants retrieveAssistants(@PathVariable("assistantsId") String assistantsId) {
return assistantsService.retrieveAssistants(assistantsId);
}
@Operation(summary = "单纯的只上传文件,给某次问答使用")
@GetMapping("/upload")
public File retrieveAssistants(MultipartFile file) {
return assistantsService.upload(file);
}
@Operation(summary = "上传文件并绑定具体的 assistant")
@PostMapping("/createAssistantFile/{assistantsId}") | public AssistantFile CreateAssistantFileReq(@PathVariable("assistantsId") String assistantsId, MultipartFile file, String fileId) { | 7 | 2023-11-25 13:19:47+00:00 | 12k |
objectionary/opeo-maven-plugin | src/main/java/org/eolang/opeo/decompilation/DecompilerMachine.java | [
{
"identifier": "Instruction",
"path": "src/main/java/org/eolang/opeo/Instruction.java",
"snippet": "public interface Instruction {\n\n /**\n * Opcode number.\n * @return Opcode number.\n */\n int opcode();\n\n /**\n * Retrieve operand by position index.\n * @param index Ope... | import java.util.Arrays;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.cactoos.list.ListOf;
import org.cactoos.map.MapEntry;
import org.cactoos.map.MapOf;
import org.eolang.opeo.Instruction;
import org.eolang.opeo.ast.Add;
import org.eolang.opeo.ast.AstNode;
import org.eolang.opeo.ast.Attributes;
import org.eolang.opeo.ast.Constructor;
import org.eolang.opeo.ast.InstanceField;
import org.eolang.opeo.ast.Invocation;
import org.eolang.opeo.ast.Label;
import org.eolang.opeo.ast.Literal;
import org.eolang.opeo.ast.Mul;
import org.eolang.opeo.ast.Opcode;
import org.eolang.opeo.ast.Reference;
import org.eolang.opeo.ast.Root;
import org.eolang.opeo.ast.StoreLocal;
import org.eolang.opeo.ast.Super;
import org.eolang.opeo.ast.WriteField;
import org.eolang.opeo.jeo.JeoLabel;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.xembly.Directive; | 9,379 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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 org.eolang.opeo.decompilation;
/**
* Decompiler machine.
* @since 0.1
*/
public final class DecompilerMachine {
/**
* Output Stack.
*/
private final Deque<AstNode> stack;
/**
* Local variables.
*/
private final LocalVariables locals;
/**
* Instruction handlers.
*/
private final Map<Integer, InstructionHandler> handlers;
/**
* Arguments provided to decompiler.
*/
private final Map<String, String> arguments;
/**
* Constructor.
*/
public DecompilerMachine() {
this(new HashMap<>());
}
/**
* Constructor.
* @param args Arguments provided to decompiler.
*/
public DecompilerMachine(final Map<String, String> args) {
this(new LocalVariables(), args);
}
/**
* Constructor.
* @param locals Local variables.
* @param arguments Arguments provided to decompiler.
*/
public DecompilerMachine(final LocalVariables locals, final Map<String, String> arguments) {
this.stack = new LinkedList<>();
this.locals = locals;
this.arguments = arguments;
this.handlers = new MapOf<>(
new MapEntry<>(Opcodes.ICONST_1, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_2, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_3, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_4, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_5, new IconstHandler()),
new MapEntry<>(Opcodes.IADD, new AddHandler()),
new MapEntry<>(Opcodes.IMUL, new MulHandler()),
new MapEntry<>(Opcodes.ILOAD, new LoadHandler(Type.INT_TYPE)),
new MapEntry<>(Opcodes.LLOAD, new LoadHandler(Type.LONG_TYPE)),
new MapEntry<>(Opcodes.FLOAD, new LoadHandler(Type.FLOAT_TYPE)),
new MapEntry<>(Opcodes.DLOAD, new LoadHandler(Type.DOUBLE_TYPE)),
new MapEntry<>(Opcodes.ALOAD, new LoadHandler(Type.getType(Object.class))),
new MapEntry<>(Opcodes.ISTORE, new StoreHandler(Type.INT_TYPE)),
new MapEntry<>(Opcodes.LSTORE, new StoreHandler(Type.LONG_TYPE)),
new MapEntry<>(Opcodes.FSTORE, new StoreHandler(Type.FLOAT_TYPE)),
new MapEntry<>(Opcodes.DSTORE, new StoreHandler(Type.DOUBLE_TYPE)),
new MapEntry<>(Opcodes.ASTORE, new StoreHandler(Type.getType(Object.class))),
new MapEntry<>(Opcodes.NEW, new NewHandler()),
new MapEntry<>(Opcodes.DUP, new DupHandler()),
new MapEntry<>(Opcodes.BIPUSH, new BipushHandler()),
new MapEntry<>(Opcodes.INVOKESPECIAL, new InvokespecialHandler()),
new MapEntry<>(Opcodes.INVOKEVIRTUAL, new InvokevirtualHandler()),
new MapEntry<>(Opcodes.GETFIELD, new GetFieldHandler()),
new MapEntry<>(Opcodes.PUTFIELD, new PutFieldHnadler()),
new MapEntry<>(Opcodes.LDC, new LdcHandler()),
new MapEntry<>(Opcodes.POP, new PopHandler()),
new MapEntry<>(Opcodes.RETURN, new ReturnHandler()), | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND 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 org.eolang.opeo.decompilation;
/**
* Decompiler machine.
* @since 0.1
*/
public final class DecompilerMachine {
/**
* Output Stack.
*/
private final Deque<AstNode> stack;
/**
* Local variables.
*/
private final LocalVariables locals;
/**
* Instruction handlers.
*/
private final Map<Integer, InstructionHandler> handlers;
/**
* Arguments provided to decompiler.
*/
private final Map<String, String> arguments;
/**
* Constructor.
*/
public DecompilerMachine() {
this(new HashMap<>());
}
/**
* Constructor.
* @param args Arguments provided to decompiler.
*/
public DecompilerMachine(final Map<String, String> args) {
this(new LocalVariables(), args);
}
/**
* Constructor.
* @param locals Local variables.
* @param arguments Arguments provided to decompiler.
*/
public DecompilerMachine(final LocalVariables locals, final Map<String, String> arguments) {
this.stack = new LinkedList<>();
this.locals = locals;
this.arguments = arguments;
this.handlers = new MapOf<>(
new MapEntry<>(Opcodes.ICONST_1, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_2, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_3, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_4, new IconstHandler()),
new MapEntry<>(Opcodes.ICONST_5, new IconstHandler()),
new MapEntry<>(Opcodes.IADD, new AddHandler()),
new MapEntry<>(Opcodes.IMUL, new MulHandler()),
new MapEntry<>(Opcodes.ILOAD, new LoadHandler(Type.INT_TYPE)),
new MapEntry<>(Opcodes.LLOAD, new LoadHandler(Type.LONG_TYPE)),
new MapEntry<>(Opcodes.FLOAD, new LoadHandler(Type.FLOAT_TYPE)),
new MapEntry<>(Opcodes.DLOAD, new LoadHandler(Type.DOUBLE_TYPE)),
new MapEntry<>(Opcodes.ALOAD, new LoadHandler(Type.getType(Object.class))),
new MapEntry<>(Opcodes.ISTORE, new StoreHandler(Type.INT_TYPE)),
new MapEntry<>(Opcodes.LSTORE, new StoreHandler(Type.LONG_TYPE)),
new MapEntry<>(Opcodes.FSTORE, new StoreHandler(Type.FLOAT_TYPE)),
new MapEntry<>(Opcodes.DSTORE, new StoreHandler(Type.DOUBLE_TYPE)),
new MapEntry<>(Opcodes.ASTORE, new StoreHandler(Type.getType(Object.class))),
new MapEntry<>(Opcodes.NEW, new NewHandler()),
new MapEntry<>(Opcodes.DUP, new DupHandler()),
new MapEntry<>(Opcodes.BIPUSH, new BipushHandler()),
new MapEntry<>(Opcodes.INVOKESPECIAL, new InvokespecialHandler()),
new MapEntry<>(Opcodes.INVOKEVIRTUAL, new InvokevirtualHandler()),
new MapEntry<>(Opcodes.GETFIELD, new GetFieldHandler()),
new MapEntry<>(Opcodes.PUTFIELD, new PutFieldHnadler()),
new MapEntry<>(Opcodes.LDC, new LdcHandler()),
new MapEntry<>(Opcodes.POP, new PopHandler()),
new MapEntry<>(Opcodes.RETURN, new ReturnHandler()), | new MapEntry<>(JeoLabel.LABEL_OPCODE, new LabelHandler()) | 16 | 2023-11-20 13:01:13+00:00 | 12k |
GregTech-Chinese-Community/EPCore | src/main/java/cn/gtcommunity/epimorphism/common/CommonProxy.java | [
{
"identifier": "CACasingTierProperty",
"path": "src/main/java/cn/gtcommunity/epimorphism/api/recipe/properties/CACasingTierProperty.java",
"snippet": "public class CACasingTierProperty extends RecipeProperty<Integer> {\n\n public static final String KEY = \"machineLevel\";\n private static final ... | import cn.gtcommunity.epimorphism.api.recipe.properties.CACasingTierProperty;
import cn.gtcommunity.epimorphism.api.recipe.properties.PACasingTierProperty;
import cn.gtcommunity.epimorphism.api.recipe.properties.QFTCasingTierProperty;
import cn.gtcommunity.epimorphism.common.blocks.EPBlockWireCoil;
import cn.gtcommunity.epimorphism.common.covers.EPCoverBehavior;
import cn.gtcommunity.epimorphism.api.recipe.properties.CasingTierProperty;
import cn.gtcommunity.epimorphism.api.utils.EPLog;
import cn.gtcommunity.epimorphism.common.blocks.EPMetablocks;
import cn.gtcommunity.epimorphism.common.items.BehaviorAddition;
import cn.gtcommunity.epimorphism.loaders.formula.FormulaManager;
import cn.gtcommunity.epimorphism.loaders.recipe.EPRecipeManager;
import cn.gtcommunity.epimorphism.loaders.recipe.components.MaterialComponents;
import cn.gtcommunity.epimorphism.loaders.recipe.handlers.EPRecipeHandlerList;
import gregtech.api.GregTechAPI;
import gregtech.api.block.VariantItemBlock;
import gregtech.api.cover.CoverDefinition;
import gregtech.api.recipes.recipeproperties.FusionEUToStartProperty;
import gregtech.loaders.recipe.CraftingComponent;
import net.minecraft.block.Block;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.registries.IForgeRegistry;
import java.util.Objects;
import java.util.function.Function;
import static gregtech.api.GregTechAPI.HEATING_COILS; | 10,725 | package cn.gtcommunity.epimorphism.common;
@EventBusSubscriber(
modid = "epimorphism"
)
public class CommonProxy {
public CommonProxy() {}
public void preLoad() {}
@SubscribeEvent
public static void syncConfigValues(ConfigChangedEvent.OnConfigChangedEvent event) {}
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event) { | package cn.gtcommunity.epimorphism.common;
@EventBusSubscriber(
modid = "epimorphism"
)
public class CommonProxy {
public CommonProxy() {}
public void preLoad() {}
@SubscribeEvent
public static void syncConfigValues(ConfigChangedEvent.OnConfigChangedEvent event) {}
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event) { | EPLog.logger.info("Registering blocks..."); | 6 | 2023-11-26 01:56:35+00:00 | 12k |
LaughingMuffin/laughing-logger | app/src/main/java/org/laughing/logger/ui/SettingsActivity.java | [
{
"identifier": "LogLine",
"path": "app/src/main/java/org/laughing/logger/data/LogLine.java",
"snippet": "public class LogLine {\n\n private static final int TIMESTAMP_LENGTH = 19;\n\n private static Pattern logPattern = Pattern.compile(\n // log level\n \"(\\\\w)\" +\n ... | import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.preference.SwitchPreference;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.Toolbar;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import org.laughing.logger.R;
import org.laughing.logger.data.LogLine;
import org.laughing.logger.helper.PackageHelper;
import org.laughing.logger.helper.PreferenceHelper;
import org.laughing.logger.util.ArrayUtil;
import org.laughing.logger.util.StringUtil;
import org.laughing.logger.widget.MultipleChoicePreference;
import java.util.ArrayList;
import java.util.List; | 7,334 | package org.laughing.logger.ui;
public class SettingsActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar_actionbar);
toolbar.setOverflowIcon(AppCompatResources.getDrawable(this, R.drawable.ic_more_vert));
setSupportActionBar(toolbar);
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentById(R.id.content);
if (f == null) {
fm.beginTransaction()
.replace(R.id.content,
new SettingsFragment())
.commit();
}
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.settings);
}
private void setResultAndFinish() {
Intent data = new Intent();
FragmentManager fm = getFragmentManager();
SettingsFragment f = (SettingsFragment) fm.findFragmentById(R.id.content);
data.putExtra("bufferChanged", f.getBufferChanged());
setResult(RESULT_OK, data);
finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// set result and finish
setResultAndFinish();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
setResultAndFinish();
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment implements OnPreferenceChangeListener {
private static final int MAX_LOG_LINE_PERIOD = 1000;
private static final int MIN_LOG_LINE_PERIOD = 1;
private static final int MAX_DISPLAY_LIMIT = 100000;
private static final int MIN_DISPLAY_LIMIT = 1000;
private EditTextPreference logLinePeriodPreference, displayLimitPreference, filterPatternPreference;
private ListPreference textSizePreference, defaultLevelPreference;
private MultipleChoicePreference bufferPreference;
private Preference mThemePreference;
private Preference mAboutPreference;
private SwitchPreference scrubberPreference;
private boolean bufferChanged = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
setUpPreferences();
}
public boolean getBufferChanged() {
return bufferChanged;
}
private void setUpPreferences() {
setCurrentValue("ui.accent");
setCurrentValue("ui.theme");
setCurrentValue("theme");
displayLimitPreference = (EditTextPreference) findPreference(getString(R.string.pref_display_limit));
| package org.laughing.logger.ui;
public class SettingsActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar_actionbar);
toolbar.setOverflowIcon(AppCompatResources.getDrawable(this, R.drawable.ic_more_vert));
setSupportActionBar(toolbar);
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentById(R.id.content);
if (f == null) {
fm.beginTransaction()
.replace(R.id.content,
new SettingsFragment())
.commit();
}
//noinspection ConstantConditions
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.settings);
}
private void setResultAndFinish() {
Intent data = new Intent();
FragmentManager fm = getFragmentManager();
SettingsFragment f = (SettingsFragment) fm.findFragmentById(R.id.content);
data.putExtra("bufferChanged", f.getBufferChanged());
setResult(RESULT_OK, data);
finish();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// set result and finish
setResultAndFinish();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
setResultAndFinish();
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SettingsFragment extends PreferenceFragment implements OnPreferenceChangeListener {
private static final int MAX_LOG_LINE_PERIOD = 1000;
private static final int MIN_LOG_LINE_PERIOD = 1;
private static final int MAX_DISPLAY_LIMIT = 100000;
private static final int MIN_DISPLAY_LIMIT = 1000;
private EditTextPreference logLinePeriodPreference, displayLimitPreference, filterPatternPreference;
private ListPreference textSizePreference, defaultLevelPreference;
private MultipleChoicePreference bufferPreference;
private Preference mThemePreference;
private Preference mAboutPreference;
private SwitchPreference scrubberPreference;
private boolean bufferChanged = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
setUpPreferences();
}
public boolean getBufferChanged() {
return bufferChanged;
}
private void setUpPreferences() {
setCurrentValue("ui.accent");
setCurrentValue("ui.theme");
setCurrentValue("theme");
displayLimitPreference = (EditTextPreference) findPreference(getString(R.string.pref_display_limit));
| int displayLimitValue = PreferenceHelper.getDisplayLimitPreference(getActivity()); | 2 | 2023-11-19 15:31:51+00:00 | 12k |
GT-ARC/opaca-core | opaca-platform/src/main/java/de/gtarc/opaca/platform/session/Session.java | [
{
"identifier": "AgentContainer",
"path": "opaca-model/src/main/java/de/gtarc/opaca/model/AgentContainer.java",
"snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class AgentContainer {\n\n /** ID of the container; does not necessarily have to be the Docker Container ID */\n @NonNull... | import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import com.google.common.base.Strings;
import de.gtarc.opaca.model.AgentContainer;
import de.gtarc.opaca.model.PostAgentContainer;
import de.gtarc.opaca.platform.PlatformImpl;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import de.gtarc.opaca.util.RestHelper;
import de.gtarc.opaca.platform.PlatformConfig;
import de.gtarc.opaca.platform.PlatformConfig.SessionPolicy; | 7,508 | package de.gtarc.opaca.platform.session;
/**
* Class responsible for Session handling. Load SessionData from JSON file when platform is
* started, and save it to that file when it is stopped (depending on policy).
*/
@Component
@Log
public class Session {
@Autowired
private PlatformConfig config;
@Autowired
private SessionData data;
@Autowired | package de.gtarc.opaca.platform.session;
/**
* Class responsible for Session handling. Load SessionData from JSON file when platform is
* started, and save it to that file when it is stopped (depending on policy).
*/
@Component
@Log
public class Session {
@Autowired
private PlatformConfig config;
@Autowired
private SessionData data;
@Autowired | private PlatformImpl implementation; | 2 | 2023-11-23 11:06:10+00:00 | 12k |
ZayrexDev/ZPixiv | src/main/java/xyz/zcraft/zpixiv/ui/controller/MainController.java | [
{
"identifier": "PixivClient",
"path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ... | import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import javafx.util.Pair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.controlsfx.control.PopOver;
import org.jetbrains.annotations.NotNull;
import xyz.zcraft.zpixiv.api.PixivClient;
import xyz.zcraft.zpixiv.api.artwork.Identifier;
import xyz.zcraft.zpixiv.api.artwork.Quality;
import xyz.zcraft.zpixiv.api.user.PixivUser;
import xyz.zcraft.zpixiv.ui.Main;
import xyz.zcraft.zpixiv.util.*;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.Stack;
import static xyz.zcraft.zpixiv.util.LayoutUtil.fillAnchor; | 9,159 | package xyz.zcraft.zpixiv.ui.controller;
public class MainController implements Initializable {
private static final Logger LOG = LogManager.getLogger(MainController.class);
private final Stack<Pair<Object, Parent>> contents = new Stack<>();
public TextField topSearchBar;
public AnchorPane contentPane;
public AnchorPane main;
public VBox closePageBtn;
public VBox refreshBtn;
public VBox msgPane;
public ImageView profileImg;
public Label userNameLbl;
public AnchorPane topBar;
public VBox sideBar;
private double offsetX = 0;
private double offsetY = 0;
private double offsetE = -1;
private double offsetS = -1;
private PopOver pop;
public void profileBtnOnAction() {
if (Main.getClient() != null) {
pop.show(profileImg);
} else {
try {
FXMLLoader loader = new FXMLLoader(ResourceLoader.load("fxml/Login.fxml"));
closeAll();
addContent(loader.getController(), loader.load(), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public void exitBtnOnAction() {
Platform.exit();
Main.getTpe().shutdownNow();
Main.getTimer().cancel();
}
@Override
public void initialize(URL urlIgnored, ResourceBundle resourceBundle) {
LOG.info("Initializing main layout...");
Rectangle r = new Rectangle(profileImg.getFitWidth(), profileImg.getFitHeight());
r.setArcWidth(profileImg.getFitWidth());
r.setArcHeight(profileImg.getFitHeight());
profileImg.setClip(r);
try {
FXMLLoader loader = new FXMLLoader(ResourceLoader.load("fxml/Demo.fxml"));
addContent(loader.getController(), loader.load(), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
contentPane.maxWidthProperty().bind(main.maxWidthProperty().subtract(sideBar.widthProperty()));
contentPane.maxHeightProperty().bind(main.maxHeightProperty().subtract(topBar.heightProperty()));
final Button exitLoginBtn = getExitLoginBtn();
pop = new PopOver(profileImg);
pop.setAnimated(true);
pop.setCornerRadius(2);
pop.setArrowIndent(0);
pop.setContentNode(exitLoginBtn);
pop.hide();
try {
final String s = Main.loadCookie();
if (s != null) {
profileImg.setDisable(true);
userNameLbl.setText("登录中...");
Main.getTpe().submit(() -> {
try {
SSLUtil.ignoreSsl(); | package xyz.zcraft.zpixiv.ui.controller;
public class MainController implements Initializable {
private static final Logger LOG = LogManager.getLogger(MainController.class);
private final Stack<Pair<Object, Parent>> contents = new Stack<>();
public TextField topSearchBar;
public AnchorPane contentPane;
public AnchorPane main;
public VBox closePageBtn;
public VBox refreshBtn;
public VBox msgPane;
public ImageView profileImg;
public Label userNameLbl;
public AnchorPane topBar;
public VBox sideBar;
private double offsetX = 0;
private double offsetY = 0;
private double offsetE = -1;
private double offsetS = -1;
private PopOver pop;
public void profileBtnOnAction() {
if (Main.getClient() != null) {
pop.show(profileImg);
} else {
try {
FXMLLoader loader = new FXMLLoader(ResourceLoader.load("fxml/Login.fxml"));
closeAll();
addContent(loader.getController(), loader.load(), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public void exitBtnOnAction() {
Platform.exit();
Main.getTpe().shutdownNow();
Main.getTimer().cancel();
}
@Override
public void initialize(URL urlIgnored, ResourceBundle resourceBundle) {
LOG.info("Initializing main layout...");
Rectangle r = new Rectangle(profileImg.getFitWidth(), profileImg.getFitHeight());
r.setArcWidth(profileImg.getFitWidth());
r.setArcHeight(profileImg.getFitHeight());
profileImg.setClip(r);
try {
FXMLLoader loader = new FXMLLoader(ResourceLoader.load("fxml/Demo.fxml"));
addContent(loader.getController(), loader.load(), true);
} catch (IOException e) {
throw new RuntimeException(e);
}
contentPane.maxWidthProperty().bind(main.maxWidthProperty().subtract(sideBar.widthProperty()));
contentPane.maxHeightProperty().bind(main.maxHeightProperty().subtract(topBar.heightProperty()));
final Button exitLoginBtn = getExitLoginBtn();
pop = new PopOver(profileImg);
pop.setAnimated(true);
pop.setCornerRadius(2);
pop.setArrowIndent(0);
pop.setContentNode(exitLoginBtn);
pop.hide();
try {
final String s = Main.loadCookie();
if (s != null) {
profileImg.setDisable(true);
userNameLbl.setText("登录中...");
Main.getTpe().submit(() -> {
try {
SSLUtil.ignoreSsl(); | final PixivClient client = new PixivClient(s, Main.getConfig().parseProxy(), true); | 0 | 2023-11-23 15:08:16+00:00 | 12k |
myzticbean/QSFindItemAddOn | src/main/java/io/myzticbean/finditemaddon/QuickShopHandler/QSReremakeAPIHandler.java | [
{
"identifier": "FindItemCmdReremakeImpl",
"path": "src/main/java/io/myzticbean/finditemaddon/Commands/QSSubCommands/FindItemCmdReremakeImpl.java",
"snippet": "public class FindItemCmdReremakeImpl implements CommandHandler<Player> {\n\n private final String hideSubCommand;\n private final String r... | import io.myzticbean.finditemaddon.Commands.QSSubCommands.FindItemCmdReremakeImpl;
import io.myzticbean.finditemaddon.FindItemAddOn;
import io.myzticbean.finditemaddon.Models.FoundShopItemModel;
import io.myzticbean.finditemaddon.Models.ShopSearchActivityModel;
import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms;
import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil;
import io.myzticbean.finditemaddon.Utils.LoggerUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.maxgamer.quickshop.QuickShop;
import org.maxgamer.quickshop.api.QuickShopAPI;
import org.maxgamer.quickshop.api.command.CommandContainer;
import org.maxgamer.quickshop.api.shop.Shop;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; | 7,382 | package io.myzticbean.finditemaddon.QuickShopHandler;
/**
* Implementation of QSApi for Reremake
* @author ronsane
*/
public class QSReremakeAPIHandler implements QSApi<QuickShop, Shop> {
private final QuickShopAPI api;
private final String QS_REREMAKE_PLUGIN_NAME = "QuickShop";
public QSReremakeAPIHandler() {
api = (QuickShopAPI) Bukkit.getPluginManager().getPlugin(QS_REREMAKE_PLUGIN_NAME);
}
@Override | package io.myzticbean.finditemaddon.QuickShopHandler;
/**
* Implementation of QSApi for Reremake
* @author ronsane
*/
public class QSReremakeAPIHandler implements QSApi<QuickShop, Shop> {
private final QuickShopAPI api;
private final String QS_REREMAKE_PLUGIN_NAME = "QuickShop";
public QSReremakeAPIHandler() {
api = (QuickShopAPI) Bukkit.getPluginManager().getPlugin(QS_REREMAKE_PLUGIN_NAME);
}
@Override | public List<FoundShopItemModel> findItemBasedOnTypeFromAllShops(ItemStack item, boolean toBuy, Player searchingPlayer) { | 2 | 2023-11-22 11:36:01+00:00 | 12k |
DIDA-lJ/qiyao-12306 | services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/TrainBusinessClassPurchaseTicketHandler.java | [
{
"identifier": "VehicleSeatTypeEnum",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/common/enums/VehicleSeatTypeEnum.java",
"snippet": "@RequiredArgsConstructor\npublic enum VehicleSeatTypeEnum {\n\n /**\n * 商务座\n */\n BUSINESS_CLASS(0, \"BUSINE... | import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Pair;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleSeatTypeEnum;
import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleTypeEnum;
import org.opengoofy.index12306.biz.ticketservice.dto.domain.PurchaseTicketPassengerDetailDTO;
import org.opengoofy.index12306.biz.ticketservice.dto.domain.TrainSeatBaseDTO;
import org.opengoofy.index12306.biz.ticketservice.service.SeatService;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.base.AbstractTrainPurchaseTicketTemplate;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.base.BitMapCheckSeat;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.base.BitMapCheckSeatStatusFactory;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.SelectSeatDTO;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.TrainPurchaseTicketRespDTO;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.select.SeatSelection;
import org.opengoofy.index12306.biz.ticketservice.toolkit.CarriageVacantSeatCalculateUtil;
import org.opengoofy.index12306.biz.ticketservice.toolkit.SeatNumberUtil;
import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import static org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.base.BitMapCheckSeatStatusFactory.TRAIN_BUSINESS; | 7,810 | /*
* 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.opengoofy.index12306.biz.ticketservice.service.handler.ticket;
/**
* 高铁商务座购票组件
*
* @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料
*/
@Component
@RequiredArgsConstructor
public class TrainBusinessClassPurchaseTicketHandler extends AbstractTrainPurchaseTicketTemplate {
private final SeatService seatService;
private static final Map<Character, Integer> SEAT_Y_INT = Map.of('A', 0, 'C', 1, 'F', 2);
@Override
public String mark() {
return VehicleTypeEnum.HIGH_SPEED_RAIN.getName() + VehicleSeatTypeEnum.BUSINESS_CLASS.getName();
}
@Override
protected List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam) {
String trainId = requestParam.getRequestParam().getTrainId();
String departure = requestParam.getRequestParam().getDeparture();
String arrival = requestParam.getRequestParam().getArrival();
List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails = requestParam.getPassengerSeatDetails();
List<String> trainCarriageList = seatService.listUsableCarriageNumber(trainId, requestParam.getSeatType(), departure, arrival);
List<Integer> trainStationCarriageRemainingTicket = seatService.listSeatRemainingTicket(trainId, departure, arrival, trainCarriageList);
int remainingTicketSum = trainStationCarriageRemainingTicket.stream().mapToInt(Integer::intValue).sum();
if (remainingTicketSum < passengerSeatDetails.size()) {
throw new ServiceException("站点余票不足,请尝试更换座位类型或选择其它站点");
}
if (passengerSeatDetails.size() < 3) {
if (CollUtil.isNotEmpty(requestParam.getRequestParam().getChooseSeats())) {
Pair<List<TrainPurchaseTicketRespDTO>, Boolean> actualSeatPair = findMatchSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
return actualSeatPair.getKey();
}
return selectSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
} else {
if (CollUtil.isNotEmpty(requestParam.getRequestParam().getChooseSeats())) {
Pair<List<TrainPurchaseTicketRespDTO>, Boolean> actualSeatPair = findMatchSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
return actualSeatPair.getKey();
}
return selectComplexSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
}
}
private Pair<List<TrainPurchaseTicketRespDTO>, Boolean> findMatchSeats(SelectSeatDTO requestParam, List<String> trainCarriageList, List<Integer> trainStationCarriageRemainingTicket) {
TrainSeatBaseDTO trainSeatBaseDTO = buildTrainSeatBaseDTO(requestParam);
int chooseSeatSize = trainSeatBaseDTO.getChooseSeatList().size();
List<TrainPurchaseTicketRespDTO> actualResult = Lists.newArrayListWithCapacity(trainSeatBaseDTO.getPassengerSeatDetails().size());
BitMapCheckSeat instance = BitMapCheckSeatStatusFactory.getInstance(TRAIN_BUSINESS);
HashMap<String, List<Pair<Integer, Integer>>> carriagesSeatMap = new HashMap<>(4);
int passengersNumber = trainSeatBaseDTO.getPassengerSeatDetails().size();
for (int i = 0; i < trainStationCarriageRemainingTicket.size(); i++) {
String carriagesNumber = trainCarriageList.get(i);
List<String> listAvailableSeat = seatService.listAvailableSeat(trainSeatBaseDTO.getTrainId(), carriagesNumber, requestParam.getSeatType(), trainSeatBaseDTO.getDeparture(), trainSeatBaseDTO.getArrival());
int[][] actualSeats = new int[2][3];
for (int j = 1; j < 3; j++) {
for (int k = 1; k < 4; k++) { | /*
* 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.opengoofy.index12306.biz.ticketservice.service.handler.ticket;
/**
* 高铁商务座购票组件
*
* @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料
*/
@Component
@RequiredArgsConstructor
public class TrainBusinessClassPurchaseTicketHandler extends AbstractTrainPurchaseTicketTemplate {
private final SeatService seatService;
private static final Map<Character, Integer> SEAT_Y_INT = Map.of('A', 0, 'C', 1, 'F', 2);
@Override
public String mark() {
return VehicleTypeEnum.HIGH_SPEED_RAIN.getName() + VehicleSeatTypeEnum.BUSINESS_CLASS.getName();
}
@Override
protected List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam) {
String trainId = requestParam.getRequestParam().getTrainId();
String departure = requestParam.getRequestParam().getDeparture();
String arrival = requestParam.getRequestParam().getArrival();
List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails = requestParam.getPassengerSeatDetails();
List<String> trainCarriageList = seatService.listUsableCarriageNumber(trainId, requestParam.getSeatType(), departure, arrival);
List<Integer> trainStationCarriageRemainingTicket = seatService.listSeatRemainingTicket(trainId, departure, arrival, trainCarriageList);
int remainingTicketSum = trainStationCarriageRemainingTicket.stream().mapToInt(Integer::intValue).sum();
if (remainingTicketSum < passengerSeatDetails.size()) {
throw new ServiceException("站点余票不足,请尝试更换座位类型或选择其它站点");
}
if (passengerSeatDetails.size() < 3) {
if (CollUtil.isNotEmpty(requestParam.getRequestParam().getChooseSeats())) {
Pair<List<TrainPurchaseTicketRespDTO>, Boolean> actualSeatPair = findMatchSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
return actualSeatPair.getKey();
}
return selectSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
} else {
if (CollUtil.isNotEmpty(requestParam.getRequestParam().getChooseSeats())) {
Pair<List<TrainPurchaseTicketRespDTO>, Boolean> actualSeatPair = findMatchSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
return actualSeatPair.getKey();
}
return selectComplexSeats(requestParam, trainCarriageList, trainStationCarriageRemainingTicket);
}
}
private Pair<List<TrainPurchaseTicketRespDTO>, Boolean> findMatchSeats(SelectSeatDTO requestParam, List<String> trainCarriageList, List<Integer> trainStationCarriageRemainingTicket) {
TrainSeatBaseDTO trainSeatBaseDTO = buildTrainSeatBaseDTO(requestParam);
int chooseSeatSize = trainSeatBaseDTO.getChooseSeatList().size();
List<TrainPurchaseTicketRespDTO> actualResult = Lists.newArrayListWithCapacity(trainSeatBaseDTO.getPassengerSeatDetails().size());
BitMapCheckSeat instance = BitMapCheckSeatStatusFactory.getInstance(TRAIN_BUSINESS);
HashMap<String, List<Pair<Integer, Integer>>> carriagesSeatMap = new HashMap<>(4);
int passengersNumber = trainSeatBaseDTO.getPassengerSeatDetails().size();
for (int i = 0; i < trainStationCarriageRemainingTicket.size(); i++) {
String carriagesNumber = trainCarriageList.get(i);
List<String> listAvailableSeat = seatService.listAvailableSeat(trainSeatBaseDTO.getTrainId(), carriagesNumber, requestParam.getSeatType(), trainSeatBaseDTO.getDeparture(), trainSeatBaseDTO.getArrival());
int[][] actualSeats = new int[2][3];
for (int j = 1; j < 3; j++) {
for (int k = 1; k < 4; k++) { | actualSeats[j - 1][k - 1] = listAvailableSeat.contains("0" + j + SeatNumberUtil.convert(0, k)) ? 0 : 1; | 12 | 2023-11-23 07:59:11+00:00 | 12k |
estkme-group/infineon-lpa-mirror | core/src/main/java/com/infineon/esim/lpa/core/es9plus/messages/request/CancelSessionReq.java | [
{
"identifier": "CancelSessionRequestEs9",
"path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/CancelSessionRequestEs9.java",
"snippet": "public class CancelSessionRequestEs9 implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static fina... | import com.infineon.esim.util.Bytes;
import androidx.annotation.NonNull;
import com.gsma.sgp.messages.rspdefinitions.CancelSessionRequestEs9;
import com.gsma.sgp.messages.rspdefinitions.CancelSessionResponse;
import com.gsma.sgp.messages.rspdefinitions.TransactionId;
import com.infineon.esim.lpa.core.es9plus.messages.request.base.RequestMsgBody;
import com.infineon.esim.messages.Ber; | 10,176 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.core.es9plus.messages.request;
public class CancelSessionReq extends RequestMsgBody {
private String transactionId;
private String cancelSessionResponse;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getCancelSessionResponse() {
return cancelSessionResponse;
}
public void setCancelSessionResponse(String cancelSessionResponse) {
this.cancelSessionResponse = cancelSessionResponse;
}
public CancelSessionRequestEs9 getRequest() {
CancelSessionRequestEs9 cancelSessionRequestEs9 = new CancelSessionRequestEs9();
cancelSessionRequestEs9.setTransactionId(this.getTransactionIdParsed());
cancelSessionRequestEs9.setCancelSessionResponse(this.getCancelSessionResponseParsed());
return cancelSessionRequestEs9;
}
public void setRequest(CancelSessionRequestEs9 cancelSessionRequestEs9) {
setTransactionIdParsed(cancelSessionRequestEs9.getTransactionId());
setCancelSessionResponseParsed(cancelSessionRequestEs9.getCancelSessionResponse());
}
private TransactionId getTransactionIdParsed() {
return new TransactionId(Bytes.decodeHexString(this.transactionId));
}
private void setTransactionIdParsed(TransactionId transactionIdParsed) {
transactionId = Ber.getEncodedValueAsHexString(transactionIdParsed);
}
| /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.core.es9plus.messages.request;
public class CancelSessionReq extends RequestMsgBody {
private String transactionId;
private String cancelSessionResponse;
public String getTransactionId() {
return transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
public String getCancelSessionResponse() {
return cancelSessionResponse;
}
public void setCancelSessionResponse(String cancelSessionResponse) {
this.cancelSessionResponse = cancelSessionResponse;
}
public CancelSessionRequestEs9 getRequest() {
CancelSessionRequestEs9 cancelSessionRequestEs9 = new CancelSessionRequestEs9();
cancelSessionRequestEs9.setTransactionId(this.getTransactionIdParsed());
cancelSessionRequestEs9.setCancelSessionResponse(this.getCancelSessionResponseParsed());
return cancelSessionRequestEs9;
}
public void setRequest(CancelSessionRequestEs9 cancelSessionRequestEs9) {
setTransactionIdParsed(cancelSessionRequestEs9.getTransactionId());
setCancelSessionResponseParsed(cancelSessionRequestEs9.getCancelSessionResponse());
}
private TransactionId getTransactionIdParsed() {
return new TransactionId(Bytes.decodeHexString(this.transactionId));
}
private void setTransactionIdParsed(TransactionId transactionIdParsed) {
transactionId = Ber.getEncodedValueAsHexString(transactionIdParsed);
}
| private CancelSessionResponse getCancelSessionResponseParsed() { | 1 | 2023-11-22 07:46:30+00:00 | 12k |
MattiDragon/JsonPatcherLang | src/main/java/io/github/mattidragon/jsonpatcher/lang/parse/Parser.java | [
{
"identifier": "PositionedException",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/PositionedException.java",
"snippet": "public abstract class PositionedException extends RuntimeException {\n protected PositionedException(String message) {\n super(message);\n }\n\n pro... | import io.github.mattidragon.jsonpatcher.lang.PositionedException;
import io.github.mattidragon.jsonpatcher.lang.parse.parselet.PostfixParser;
import io.github.mattidragon.jsonpatcher.lang.parse.parselet.Precedence;
import io.github.mattidragon.jsonpatcher.lang.parse.parselet.PrefixParser;
import io.github.mattidragon.jsonpatcher.lang.parse.parselet.StatementParser;
import io.github.mattidragon.jsonpatcher.lang.runtime.Program;
import io.github.mattidragon.jsonpatcher.lang.runtime.expression.ErrorExpression;
import io.github.mattidragon.jsonpatcher.lang.runtime.expression.Expression;
import io.github.mattidragon.jsonpatcher.lang.runtime.statement.Statement;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.VisibleForTesting;
import java.util.ArrayList;
import java.util.List; | 8,026 | package io.github.mattidragon.jsonpatcher.lang.parse;
public class Parser {
private final List<PositionedToken<?>> tokens;
private List<ParseException> errors = new ArrayList<>();
private final PatchMetadata metadata;
private int current = 0;
private Parser(List<PositionedToken<?>> tokens) {
this.tokens = tokens;
this.metadata = new PatchMetadata();
}
public static Result parse(List<PositionedToken<?>> tokens) {
return new Parser(tokens).program();
}
@VisibleForTesting
public static Expression parseExpression(List<PositionedToken<?>> tokens) throws ParseException {
var parser = new Parser(tokens);
var errors = parser.errors;
Expression expression = null;
try {
expression = parser.expression();
} catch (EndParsingException ignored) {
} catch (ParseException e) {
errors.add(e);
}
if (!errors.isEmpty()) {
var error = new RuntimeException("Expected successful parse");
errors.forEach(error::addSuppressed);
throw error;
}
return expression;
}
public Result program() {
while (hasNext(Token.SimpleToken.AT_SIGN)) {
next();
var id = expectWord().value();
metadata.add(id, this);
expect(Token.SimpleToken.SEMICOLON);
}
| package io.github.mattidragon.jsonpatcher.lang.parse;
public class Parser {
private final List<PositionedToken<?>> tokens;
private List<ParseException> errors = new ArrayList<>();
private final PatchMetadata metadata;
private int current = 0;
private Parser(List<PositionedToken<?>> tokens) {
this.tokens = tokens;
this.metadata = new PatchMetadata();
}
public static Result parse(List<PositionedToken<?>> tokens) {
return new Parser(tokens).program();
}
@VisibleForTesting
public static Expression parseExpression(List<PositionedToken<?>> tokens) throws ParseException {
var parser = new Parser(tokens);
var errors = parser.errors;
Expression expression = null;
try {
expression = parser.expression();
} catch (EndParsingException ignored) {
} catch (ParseException e) {
errors.add(e);
}
if (!errors.isEmpty()) {
var error = new RuntimeException("Expected successful parse");
errors.forEach(error::addSuppressed);
throw error;
}
return expression;
}
public Result program() {
while (hasNext(Token.SimpleToken.AT_SIGN)) {
next();
var id = expectWord().value();
metadata.add(id, this);
expect(Token.SimpleToken.SEMICOLON);
}
| var statements = new ArrayList<Statement>(); | 6 | 2023-11-23 14:17:00+00:00 | 12k |
wssun/AST4PLU | data-process/process/src/main/java/process/SplitAST_for_bcb.java | [
{
"identifier": "GenerateAST",
"path": "data-process/process/src/main/java/JDT/GenerateAST.java",
"snippet": "public class GenerateAST {\n\tprivate static String ast;\n\tprivate static String masked_ast;\n\t\n\tpublic static class astVisitor extends ASTVisitor{\n\t\tpublic void preVisit(ASTNode node) {\... | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import JDT.GenerateAST;
import tree.Tree;
import utils.TreeToJSON;
import utils.TreeTools;
import tree.Test; | 9,418 | package process;
public class SplitAST_for_bcb {
private static String AST_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data_ast.jsonl";
private static String JSON_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data.jsonl";
// use Tree-sitter
public static void main(String[] args) throws IOException {
FileReader fr = null;
BufferedReader br = null;
File jsonFile = null;
FileWriter fileWriter = null;
BufferedWriter bw = null;
try {
fr = new FileReader(AST_FILE_PATH);
br = new BufferedReader(fr);
jsonFile = new File(JSON_FILE_PATH);
if (!jsonFile.exists()) {
jsonFile.createNewFile();
}
fileWriter = new FileWriter(jsonFile.getAbsoluteFile());
bw = new BufferedWriter(fileWriter);
String line = "";
//读取每一行的数据
int cnt=1;
while ( (line = br.readLine()) != null) {
JSONObject lineJson = JSONObject.parseObject(line);
String idx=lineJson.getString("idx");
JSONArray asts=lineJson.getJSONArray("asts");
List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class);
int sz=ast_seqs.size();
JSONArray new_asts=new JSONArray();
for(int i=0;i<sz;++i)
{
Tree ast=TreeTools.stringToTree(ast_seqs.get(i));
Test.printTree(ast, 0); | package process;
public class SplitAST_for_bcb {
private static String AST_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data_ast.jsonl";
private static String JSON_FILE_PATH="D:\\ast_dataset\\bcb\\split_ast\\data.jsonl";
// use Tree-sitter
public static void main(String[] args) throws IOException {
FileReader fr = null;
BufferedReader br = null;
File jsonFile = null;
FileWriter fileWriter = null;
BufferedWriter bw = null;
try {
fr = new FileReader(AST_FILE_PATH);
br = new BufferedReader(fr);
jsonFile = new File(JSON_FILE_PATH);
if (!jsonFile.exists()) {
jsonFile.createNewFile();
}
fileWriter = new FileWriter(jsonFile.getAbsoluteFile());
bw = new BufferedWriter(fileWriter);
String line = "";
//读取每一行的数据
int cnt=1;
while ( (line = br.readLine()) != null) {
JSONObject lineJson = JSONObject.parseObject(line);
String idx=lineJson.getString("idx");
JSONArray asts=lineJson.getJSONArray("asts");
List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class);
int sz=ast_seqs.size();
JSONArray new_asts=new JSONArray();
for(int i=0;i<sz;++i)
{
Tree ast=TreeTools.stringToTree(ast_seqs.get(i));
Test.printTree(ast, 0); | TreeToJSON.toJSON(ast,0); | 2 | 2023-11-23 06:08:43+00:00 | 12k |
phamdung2209/FAP | src/main/java/com/func/ClassroomHandler/HandleClassroom.java | [
{
"identifier": "BackToMain",
"path": "src/main/java/com/func/BackToMain.java",
"snippet": "public class BackToMain {\n public void backToMain() {\n System.out.println(\"Returning to main menu...\");\n System.out.println(\"--------MANAGE FAP SYSTEM--------\");\n System.out.printl... | import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import com.func.BackToMain;
import com.persons.Administrator; | 10,637 | package com.func.ClassroomHandler;
public class HandleClassroom {
public Scanner scanner = new Scanner(System.in);
| package com.func.ClassroomHandler;
public class HandleClassroom {
public Scanner scanner = new Scanner(System.in);
| public void processClassroom(int option, Administrator admin) { | 1 | 2023-11-23 18:42:19+00:00 | 12k |
morihofi/acmeserver | src/main/java/de/morihofi/acmeserver/certificate/acme/api/endpoints/account/AccountEndpoint.java | [
{
"identifier": "Provisioner",
"path": "src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java",
"snippet": "public class Provisioner {\n\n\n /**\n * Get the ACME Server URL, reachable from other Hosts\n *\n * @return Full url (including HTTPS prefix) and port to this ... | import com.google.gson.Gson;
import de.morihofi.acmeserver.certificate.acme.api.Provisioner;
import de.morihofi.acmeserver.certificate.acme.api.abstractclass.AbstractAcmeEndpoint;
import de.morihofi.acmeserver.certificate.acme.api.endpoints.account.objects.ACMEAccountRequestPayload;
import de.morihofi.acmeserver.certificate.objects.ACMERequestBody;
import de.morihofi.acmeserver.database.Database;
import de.morihofi.acmeserver.database.objects.ACMEAccount;
import de.morihofi.acmeserver.exception.exceptions.ACMEAccountNotFoundException;
import de.morihofi.acmeserver.exception.exceptions.ACMEInvalidContactException;
import de.morihofi.acmeserver.tools.regex.EmailValidation;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.javalin.http.Context;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List; | 10,454 | package de.morihofi.acmeserver.certificate.acme.api.endpoints.account;
/**
* New Order Endpoint
* <p>
* URL: /acme/new-order
*/
public class AccountEndpoint extends AbstractAcmeEndpoint {
/**
* Logger
*/
public final Logger log = LogManager.getLogger(getClass());
/**
* Endpoint for managing ACME Account settings. Change E-Mail etc.
* @param provisioner Provisioner instance
*/
@SuppressFBWarnings("EI_EXPOSE_REP2")
public AccountEndpoint(Provisioner provisioner) {
super(provisioner);
}
@Override
public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception {
String accountId = ctx.pathParam("id");
ACMEAccountRequestPayload acmeAccountRequestPayload = gson.fromJson(acmeRequestBody.getDecodedPayload(), ACMEAccountRequestPayload.class);
performSignatureAndNonceCheck(ctx, accountId, acmeRequestBody);
// Check if account exists
ACMEAccount account = Database.getAccount(accountId);
if (account == null) { | package de.morihofi.acmeserver.certificate.acme.api.endpoints.account;
/**
* New Order Endpoint
* <p>
* URL: /acme/new-order
*/
public class AccountEndpoint extends AbstractAcmeEndpoint {
/**
* Logger
*/
public final Logger log = LogManager.getLogger(getClass());
/**
* Endpoint for managing ACME Account settings. Change E-Mail etc.
* @param provisioner Provisioner instance
*/
@SuppressFBWarnings("EI_EXPOSE_REP2")
public AccountEndpoint(Provisioner provisioner) {
super(provisioner);
}
@Override
public void handleRequest(Context ctx, Provisioner provisioner, Gson gson, ACMERequestBody acmeRequestBody) throws Exception {
String accountId = ctx.pathParam("id");
ACMEAccountRequestPayload acmeAccountRequestPayload = gson.fromJson(acmeRequestBody.getDecodedPayload(), ACMEAccountRequestPayload.class);
performSignatureAndNonceCheck(ctx, accountId, acmeRequestBody);
// Check if account exists
ACMEAccount account = Database.getAccount(accountId);
if (account == null) { | throw new ACMEAccountNotFoundException("Account with ID " + accountId + " not found!"); | 6 | 2023-11-22 15:54:36+00:00 | 12k |
sakura-ryoko/afkplus | src/main/java/io/github/sakuraryoko/afkplus/commands/AfkPlusCommand.java | [
{
"identifier": "ConfigManager",
"path": "src/main/java/io/github/sakuraryoko/afkplus/config/ConfigManager.java",
"snippet": "public class ConfigManager {\n public static ConfigData CONFIG = new ConfigData();\n\n public static void initConfig() {\n CONFIG.afkPlusOptions.afkPlusCommandPermis... | import static io.github.sakuraryoko.afkplus.config.ConfigManager.*;
import static net.minecraft.server.command.CommandManager.*;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import eu.pb4.placeholders.api.TextParserUtils;
import io.github.sakuraryoko.afkplus.config.ConfigManager;
import io.github.sakuraryoko.afkplus.data.IAfkPlayer;
import io.github.sakuraryoko.afkplus.util.AfkPlayerInfo;
import io.github.sakuraryoko.afkplus.util.AfkPlusInfo;
import io.github.sakuraryoko.afkplus.util.AfkPlusLogger;
import io.github.sakuraryoko.afkplus.util.FormattingExample;
import me.lucko.fabric.api.permissions.v0.Permissions;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.minecraft.command.argument.EntityArgumentType;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text; | 8,888 | package io.github.sakuraryoko.afkplus.commands;
public class AfkPlusCommand {
public static void register() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(
literal("afkplus")
.executes(ctx -> afkAbout(ctx.getSource(), ctx))
.then(literal("ex")
.requires(Permissions.require("afkplus.afkplus.ex", 4))
.executes(ctx -> afkExample(ctx.getSource(), ctx))
)
.then(literal("reload")
.requires(Permissions.require("afkplus.afkplus.reload", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.executes(ctx -> afkReload(ctx.getSource(), ctx))
)
.then(literal("set")
.requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player",
EntityArgumentType.player())
.executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"),"", ctx))
.then(argument("reason", StringArgumentType.greedyString())
.requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"), StringArgumentType.getString(ctx, "reason"), ctx))
)
)
)
.then(literal("clear")
.requires(Permissions.require("afkplus.afkplus.clear", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> clearAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
.then(literal("info")
.requires(Permissions.require("afkplus.afkplus.info", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> infoAfkPlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
.then(literal("damage")
.then(literal("disable")
.requires(Permissions.require("afkplus.afkplus.damage.disable", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> disableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
.then(literal("enable")
.requires(Permissions.require("afkplus.afkplus.damage.enable", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> enableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
)
.then(literal("update")
.requires(Permissions.require("afkplus.afkplus.update", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> updatePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)
)
)
)
));
}
private static int afkAbout(ServerCommandSource src, CommandContext<ServerCommandSource> context) { | package io.github.sakuraryoko.afkplus.commands;
public class AfkPlusCommand {
public static void register() {
CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> dispatcher.register(
literal("afkplus")
.executes(ctx -> afkAbout(ctx.getSource(), ctx))
.then(literal("ex")
.requires(Permissions.require("afkplus.afkplus.ex", 4))
.executes(ctx -> afkExample(ctx.getSource(), ctx))
)
.then(literal("reload")
.requires(Permissions.require("afkplus.afkplus.reload", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.executes(ctx -> afkReload(ctx.getSource(), ctx))
)
.then(literal("set")
.requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player",
EntityArgumentType.player())
.executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"),"", ctx))
.then(argument("reason", StringArgumentType.greedyString())
.requires(Permissions.require("afkplus.afkplus.set", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.executes((ctx) -> setAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx, "player"), StringArgumentType.getString(ctx, "reason"), ctx))
)
)
)
.then(literal("clear")
.requires(Permissions.require("afkplus.afkplus.clear", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> clearAfk(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
.then(literal("info")
.requires(Permissions.require("afkplus.afkplus.info", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> infoAfkPlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
.then(literal("damage")
.then(literal("disable")
.requires(Permissions.require("afkplus.afkplus.damage.disable", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> disableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
.then(literal("enable")
.requires(Permissions.require("afkplus.afkplus.damage.enable", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> enableDamagePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx))
)
)
)
.then(literal("update")
.requires(Permissions.require("afkplus.afkplus.update", CONFIG.afkPlusOptions.afkPlusCommandPermissions))
.then(argument("player", EntityArgumentType.player())
.executes(ctx -> updatePlayer(ctx.getSource(), EntityArgumentType.getPlayer(ctx,"player"), ctx)
)
)
)
));
}
private static int afkAbout(ServerCommandSource src, CommandContext<ServerCommandSource> context) { | Text ModInfo = AfkPlusInfo.getModInfoText(); | 4 | 2023-11-22 00:21:36+00:00 | 12k |
clover/clover-tr34-host | src/test/java/com/clover/tr34/samples/AscSampleTr34KeyStoreData.java | [
{
"identifier": "Tr34CryptoUtils",
"path": "src/main/java/com/clover/tr34/Tr34CryptoUtils.java",
"snippet": "public final class Tr34CryptoUtils {\n\n private Tr34CryptoUtils() { }\n\n public static PrivateKey parsePrivateKey(String pem) {\n if (pem.contains(\"BEGIN RSA PRIVATE KEY\")) {\n ... | import com.clover.tr34.Tr34CryptoUtils;
import com.clover.tr34.Tr34KdhRevocation;
import com.clover.tr34.Tr34KeyStoreData;
import com.clover.tr34.Tr34ScdKeyStoreData;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.cert.CRLReason;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List; | 7,714 | "gGRs4LrDf7/BXemZIiLXlFMKWzw3WLR8Q/kpbs4DPms4DzSdpTXkwzmkddTyopm7\n" +
"dtwuoAJxs+086OMBWqXLALmacibX2EtM3sNAMezY/QKBgQCjMcS9aViitfs68dA8\n" +
"mazoZvUP4JjBguspTnpz31lMQiDn7HnK+vwWsmzgEhF4suuVf6+4f4mjr4AVg7E4\n" +
"L1IdBgvzFM2hXXmgsTlazousJ/uE+513nwrNMqm2/O/iZe1yvCjMevBSVo+4CDa0\n" +
"WETw0cEkmteh/Z9Z2IOVOoj82Q==\n" +
"-----END PRIVATE KEY-----";
public static final String SAMPLE_KRD_1_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDOTCCAiGgAwIBAgIFNAAAAAcwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEbMBkGA1UEAxMSVFIzNCBTYW1wbGUg\n" +
"Q0EgS1JEMB4XDTEwMTEwMjAwMDAwMFoXDTIwMTAyOTIzNTk1OVowQDELMAkGA1UE\n" +
"BhMCVVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEaMBgGA1UEAxMRVFIzNCBTYW1w\n" +
"bGUgS1JEIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDUXDDLb7sd\n" +
"OUzlqHtJ223PFDSw+k4Ko3H4UO6Lrn8tw8VI1Ry9o90B8NZVO/t5hR5zFUOYSyLj\n" +
"YrT8HdPW3oI3fSATLMY5Zd0K0t1onphSkWE1QPMOdaVY+RWy6eQN1CHKxr23RZD0\n" +
"Qoq0aE7LQpTTutIS9mYiAO733cMBMW+6Z2txIPuRiTwroxGoT3OvIWO1YEQF/XYL\n" +
"sVJonPUgTyDLvZdiO125bM9ro4Jqw4eQ08LGbNfr/VyfHnDLx39Vj5VQGpqctKs9\n" +
"/aJl0BCkmrcCoAFd8PbgjQzjYzBkHE3HXqj+fdXqaze9ZDKFd/hVDT8BWqVvGrXy\n" +
"XlX1k0CvU/lVAgMBAAGjOTA3MAkGA1UdEwQCMAAwHQYDVR0OBBYEFA1yBTypguLB\n" +
"ic5HIFDTTQRamlnTMAsGA1UdDwQEAwIEMDANBgkqhkiG9w0BAQsFAAOCAQEADZ7T\n" +
"nJfS4XvwcTTbQLoaSs7XKtaP1RnePiL5uMtqUYBbX81DjxxzCX5pmfBcwG+8e/I/\n" +
"yxJBEo4KedeTUWAGhRjRimUw+0hjN8l/DK1xjKHcJIHyHB994D7FaxLOqCvIHr30\n" +
"lEJ1b/PamS0owURXR6sQIfHBT/5D0IUo5mjgQG3/UA1VXYI7nwtRxLvbR8bxezAn\n" +
"R5tci+RIQnbtC3HNrcHCSUa20YZGjIV047jR6hUf2JQiG9v0wuc8lAXXlee3/eIZ\n" +
"muMxdtOucq2oDZUQIE8MhwV3t/dS3EebKdUBITkcz8qBeMhrGq12m1hOaBfhYrBa\n" +
"MRkw+KTx3ddSdCDXsQ==\n" +
"-----END CERTIFICATE-----";
public static final String SAMPLE_KDH_1_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDUTCCAjmgAwIBAgIFNAAAAAYwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEbMBkGA1UEAxMSVFIzNCBTYW1wbGUg\n" +
"Q0EgS0RIMB4XDTEwMTEwMjAwMDAwMFoXDTIwMTAyOTIzNTk1OVowQDELMAkGA1UE\n" +
"BhMCVVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEaMBgGA1UEAxMRVFIzNCBTYW1w\n" +
"bGUgS0RIIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDD648pBL7L\n" +
"b5Hvyjjbt13ZGTHKj+IRZj9Ib8q6B6DC7YfLUobFCNotHw7e3cCn21xgXby5q3PR\n" +
"YbsaDxsO5VV4D697yrpeBt/viJ5R9o/mXcIa8AA6hvFwbkYeFQK+pFh3uuICZY+8\n" +
"ouvtVpIBhjV/cU5b7slwoeqICKn0Ji8vZEOCedh8ZMF+ObpxMPR7SqRBNkP4aphi\n" +
"o1rZNz2OLSjFksilIXMbqVyORDJ6uw7OUL+ubOjq9JNOlIxqO4vr4mimknvIfhrn\n" +
"ktUxUzmbS4KILJp55DHRDc5YQHBTuSv21tZyKbtyquAQgn5xJtdXBAbKqp9NtPKM\n" +
"S9ZKnvyYoOrNAgMBAAGjUTBPMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgbAMAkGA1Ud\n" +
"EwQCMAAwHQYDVR0OBBYEFA8RoQrHXhlpbL0WonoyGxhajYcHMAsGA1UdDwQEAwIG\n" +
"wDANBgkqhkiG9w0BAQsFAAOCAQEAjadCTzoj3bOETDwaxSm3rRO/pbKj86kUVQL7\n" +
"rFQIgqZTkIGY/ljVwlJpNReYCVeJKAnpNEDw1+IWO/QoLDLy1XyZhGj4luLGqO4v\n" +
"HrdsA8g9j4Wj60+G7I+P/RJuP2orslSLV7JTiKwvrMI8jPUv0I3Q7ADbDH7MCCHG\n" +
"gd+ubgVCWWt0vYXIbzfXpB6Q0bMjjHlQAklqq4oAGrvEr/mcVNbNAXR2Ind+IPQB\n" +
"SBAjlWsUN87K5SkeSTO+EU/OG4I+TFFVy7gxQr0VQ4KbCK4fTIcYcZgtiorW6If0\n" +
"C1gvjNMu6DCl1aTjAzp6QV/rkYG+1Lk91eN8BF5jKBPOQMScrA==\n" +
"-----END CERTIFICATE-----";
// B.4 CAKDH – Certificate Authority – KDH Certificate
public static final String SAMPLE_CA_KDH_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDPjCCAiagAwIBAgIFNAAAAAUwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEZMBcGA1UEAxMQVFIzNCBTYW1wbGUg\n" +
"Um9vdDAeFw0xMDExMDIwMDAwMDBaFw0yNTEwMjgyMzU5NTlaMEExCzAJBgNVBAYT\n" +
"AlVTMRUwEwYDVQQKEwxUUjM0IFNhbXBsZXMxGzAZBgNVBAMTElRSMzQgU2FtcGxl\n" +
"IENBIEtESDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK76HXOWw9uk\n" +
"meVdeqUHFKxedcEnHZAA6u7SoAerZGZwUV9DISyKILwyy2exzV1xL2Z3b3dtWLxf\n" +
"gXMMU5Y2IitEKMiq/PzQDLzoSXBwZsGUbQ6vsjMTtqatvyPpIvWV0e5XpsS+AU1q\n" +
"ZOXZxFQpySBBDh8Swl5VAAZdSXpHeM8DVg3oEYbO1+W3R0odRwPqr5RAajxzFE34\n" +
"yXH4ec8zro6YSN5QUbRgKaYslJe86GrxUkYLOUOuJM/5zoj1pQSF2hSz0x3Txp3y\n" +
"QQXSUmJT6jiJ/hxv2DOoE69D/sQMQPiC2t5O6/5YAUSN3L2d5Pu2nVaggQ4IK3Mq\n" +
"NeoqFnByhv8CAwEAAaM/MD0wDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUuCpY\n" +
"Cg159koHx1irw5NlY183yhgwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IB\n" +
"AQCb+yPhlvcoHPANAfIV6DVxd7CoPzLihuz4VjE24OQZ8LvIa5l++fmeD3mwonKO\n" +
"CVAu1zBO1qzguAP1nybImPeoFPpMGUq0A+HpmY0cFhUW5HcYrFp4UnUyPqOtmKVA\n" +
"7kr2W5qMPoMcuDO778vNQXNDyeskBOi+LMfdVy1OFIW7OS+L9xp5L2k4koMCyjse\n" +
"65sUl87YMe+EOqVYWCImFmgjilnAn2uF3cn9BheEXstxyPJ7RNxLFPNqv7lFQkgm\n" +
"SfKTqvfEYirqrAinZBVp9uU6ZOEE+C84pKCXZDrcuQf8EVJK9HLX0NCQcxfD32OU\n" +
"7N32YnGn+yrjDPjVgXyDVt+D\n" +
"-----END CERTIFICATE-----";
private final X509Certificate rootCert;
private final X509Certificate krdCaCert;
private final X509Certificate kdhCaCert;
private final X509Certificate kdhCert;
private final PrivateKey krdCaPrivateKey;
private final PrivateKey kdhCaPrivateKey;
private final PrivateKey kdhPrivateKey;
private AscSampleTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) {
kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem);
if (kdhPrivateKeyPem != null) {
kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem);
} else {
kdhPrivateKey = null;
}
rootCert = Tr34CryptoUtils.parseCert(SAMPLE_ROOT_CERT_PEM);
kdhCaCert = Tr34CryptoUtils.parseCert(SAMPLE_CA_KDH_CERT_PEM);
krdCaCert = null;
kdhCaPrivateKey = null;
krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(SAMPLE_KRD_1_PRIVATE_KEY_PEM);
}
public static final Tr34KeyStoreData KDH_1 =
new AscSampleTr34KeyStoreData(SAMPLE_KDH_1_CERT_PEM, null);
@Override
public X509Certificate getRootCert() {
return rootCert;
}
@Override
public X509Certificate getKdhCaCert() {
return kdhCaCert;
}
@Override
public X509Certificate getKdhCert() {
return kdhCert;
}
@Override
public X509Certificate getKrdCaCert() {
return krdCaCert;
}
@Override | package com.clover.tr34.samples;
/**
* Some of the samples appear to be non-conforming to standards such as DER and X.509.
* Instances of this class are currently populated just enough to run some basic tests.
*/
public class AscSampleTr34KeyStoreData extends Tr34KeyStoreData {
public static final String SAMPLE_ROOT_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDPDCCAiSgAwIBAgIFNAAAAAEwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEZMBcGA1UEAxMQVFIzNCBTYW1wbGUg\n" +
"Um9vdDAeFw0xMDExMDIwMDAwMDBaFw0zMDEwMjcyMzU5NTlaMD8xCzAJBgNVBAYT\n" +
"AlVTMRUwEwYDVQQKEwxUUjM0IFNhbXBsZXMxGTAXBgNVBAMTEFRSMzQgU2FtcGxl\n" +
"IFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDeZ10uwGLGQWI4\n" +
"AG+CbKUnGCWD8q3S/owdgeatXsHoWzm+r5cIlNsrTyJ3OXlUHBIj1RqCth/1QYwe\n" +
"XzZ5J8m6qsMvPhYgVdB3bsOSQiXD30LCI4/5qqo+ikcocVKs48ypFH1fgiC+c0hL\n" +
"CN7XQ/ekPubrmGGZ0RFFC2oV8FB6tOBy3bjbFpbIAB/XmWd+g185anJp6twtesIK\n" +
"vaod2I3UhW/xGhdqfDlAvH1gmszJ88Ud0AF8P+3Zx70L/er6CwkWH5xx6SrnOvF1\n" +
"rbFTy+/OLDoPzeo5TEQjCjf4LtxEjrmwZp/ILpQ15pmprjGRrU7qXc0dLNw75sdR\n" +
"B45sE4afAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIKDHIan\n" +
"OuC29C5MzvfJw6JPSsnsMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEA\n" +
"zP2PtLg0ePSOxWB47oKHmrHUaBAaaC1RKYzcEyyTXwOdR1NuH0sB7Z5Si2nFJgsv\n" +
"eFu2hixQLnhuXGP4gTOP/Mu5Kf5O4wi1D2xzGt6JVQIKW//eBgjeUd+GzRiHMPvM\n" +
"TAb1DVf1DQRQ37kiJY6FlpxBBolmFzwmZkPp50vu3bgjSs1nAnG//PUXq03wqojh\n" +
"Rqp1Q9MtGGpOnCv/mFyw3hR16Eqg9YVgTWg3wq+H74JZiWrTBq33kT9NMYf1jIMo\n" +
"A1exxP5BvJaTBE2wcEPVAAdzjmeoFqUjWZGoBff8hT2KqDo01SC46Aa6z1bQZWhO\n" +
"kCETYhPBMp8I9cRBZQS2/g==\n" +
"-----END CERTIFICATE-----";
// B.2.1.7 TR34 Sample KRD 1 Key
public static final String SAMPLE_KRD_1_PRIVATE_KEY_PEM = "-----BEGIN PRIVATE KEY-----\n" +
"MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDUXDDLb7sdOUzl\n" +
"qHtJ223PFDSw+k4Ko3H4UO6Lrn8tw8VI1Ry9o90B8NZVO/t5hR5zFUOYSyLjYrT8\n" +
"HdPW3oI3fSATLMY5Zd0K0t1onphSkWE1QPMOdaVY+RWy6eQN1CHKxr23RZD0Qoq0\n" +
"aE7LQpTTutIS9mYiAO733cMBMW+6Z2txIPuRiTwroxGoT3OvIWO1YEQF/XYLsVJo\n" +
"nPUgTyDLvZdiO125bM9ro4Jqw4eQ08LGbNfr/VyfHnDLx39Vj5VQGpqctKs9/aJl\n" +
"0BCkmrcCoAFd8PbgjQzjYzBkHE3HXqj+fdXqaze9ZDKFd/hVDT8BWqVvGrXyXlX1\n" +
"k0CvU/lVAgMBAAECggEBAIRrIDoa59CnRF4ImyhI3cY80UZyLmvP02eF/9m167P7\n" +
"2W87BHr0TQHCzcPEbWEvMveMEORMJesoR7bWWpwnj4dOTMvoJYrxC86OAmYUTuNd\n" +
"qAHvCCDCF2LNn0w7MGu3FYM+Plqj1GmbfKZWTJvOXsNQQWJ1puYZMun4rHp3+zV9\n" +
"2JxeSS/jeY+gZCtNEtFTB59e/XePM0GyCgogLi+Zswd7WdBdLBVJviP5uvZZSfLG\n" +
"zZsw0GABv4/mzce+64XtD7cTe7GFJ+JSB3nDWpqHZ7t6cM9OwSuuZSUrB02rIiby\n" +
"6PoO0dweO3fpG0TIFV8/eJQCVb2qDWszt5R35Ze7tNkCgYEA89cBvXQP+sHjbvqf\n" +
"euBcQaOYke2oUeAecBVp1tTfLP8qZK4juNjq11x0GDS1oVoYzP2Nwkks2LZDZDMe\n" +
"WYKtXkXImkmOZaGBNI0/5/F3C/tFPt3W7/QT249sWayMJkkuDKl6kmSDX/Bg7/sr\n" +
"MaJDxgSTyOjvjNieSy6GBvLBwf8CgYEA3vNLzDPe9HEqeCubKTD1doxevLDg5Pg1\n" +
"1a61U+Tgrp7XuONh2VtnP6zpFcq7Psd1L2EeQdhGIBhf+zP2d55ib76dNOBrG85d\n" +
"EiY5Qdu1FnHZDDvSnDN6AHsqZD//nHX6FgSN64PmhHvV2SyTjNUPdZU1WqN2TRzm\n" +
"ebS5sipQnKsCgYEAkWgQkJJqiQUgA+kOOy8ZtMbCz5qiOhjk7b/HOqX8ZA/RjvJN\n" +
"OQiZmk12qYydFxfsHCnDZC1QwfaGX3UgTw5fJg2FH4RnlvFlZBorFrxmWk2/sEqH\n" +
"xtWNFewEF8GOXbJb9I8IGc44jXiBxfnIezOhKK9IFZHab+opEvouUGxo4K8CgYA0\n" +
"tYRoBKNjWxXVT0nhlSeTHWCQb6jbuSrRF/ramLPd1MPffDJ39roUPcblVgaqsvEr\n" +
"gGRs4LrDf7/BXemZIiLXlFMKWzw3WLR8Q/kpbs4DPms4DzSdpTXkwzmkddTyopm7\n" +
"dtwuoAJxs+086OMBWqXLALmacibX2EtM3sNAMezY/QKBgQCjMcS9aViitfs68dA8\n" +
"mazoZvUP4JjBguspTnpz31lMQiDn7HnK+vwWsmzgEhF4suuVf6+4f4mjr4AVg7E4\n" +
"L1IdBgvzFM2hXXmgsTlazousJ/uE+513nwrNMqm2/O/iZe1yvCjMevBSVo+4CDa0\n" +
"WETw0cEkmteh/Z9Z2IOVOoj82Q==\n" +
"-----END PRIVATE KEY-----";
public static final String SAMPLE_KRD_1_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDOTCCAiGgAwIBAgIFNAAAAAcwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEbMBkGA1UEAxMSVFIzNCBTYW1wbGUg\n" +
"Q0EgS1JEMB4XDTEwMTEwMjAwMDAwMFoXDTIwMTAyOTIzNTk1OVowQDELMAkGA1UE\n" +
"BhMCVVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEaMBgGA1UEAxMRVFIzNCBTYW1w\n" +
"bGUgS1JEIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDUXDDLb7sd\n" +
"OUzlqHtJ223PFDSw+k4Ko3H4UO6Lrn8tw8VI1Ry9o90B8NZVO/t5hR5zFUOYSyLj\n" +
"YrT8HdPW3oI3fSATLMY5Zd0K0t1onphSkWE1QPMOdaVY+RWy6eQN1CHKxr23RZD0\n" +
"Qoq0aE7LQpTTutIS9mYiAO733cMBMW+6Z2txIPuRiTwroxGoT3OvIWO1YEQF/XYL\n" +
"sVJonPUgTyDLvZdiO125bM9ro4Jqw4eQ08LGbNfr/VyfHnDLx39Vj5VQGpqctKs9\n" +
"/aJl0BCkmrcCoAFd8PbgjQzjYzBkHE3HXqj+fdXqaze9ZDKFd/hVDT8BWqVvGrXy\n" +
"XlX1k0CvU/lVAgMBAAGjOTA3MAkGA1UdEwQCMAAwHQYDVR0OBBYEFA1yBTypguLB\n" +
"ic5HIFDTTQRamlnTMAsGA1UdDwQEAwIEMDANBgkqhkiG9w0BAQsFAAOCAQEADZ7T\n" +
"nJfS4XvwcTTbQLoaSs7XKtaP1RnePiL5uMtqUYBbX81DjxxzCX5pmfBcwG+8e/I/\n" +
"yxJBEo4KedeTUWAGhRjRimUw+0hjN8l/DK1xjKHcJIHyHB994D7FaxLOqCvIHr30\n" +
"lEJ1b/PamS0owURXR6sQIfHBT/5D0IUo5mjgQG3/UA1VXYI7nwtRxLvbR8bxezAn\n" +
"R5tci+RIQnbtC3HNrcHCSUa20YZGjIV047jR6hUf2JQiG9v0wuc8lAXXlee3/eIZ\n" +
"muMxdtOucq2oDZUQIE8MhwV3t/dS3EebKdUBITkcz8qBeMhrGq12m1hOaBfhYrBa\n" +
"MRkw+KTx3ddSdCDXsQ==\n" +
"-----END CERTIFICATE-----";
public static final String SAMPLE_KDH_1_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDUTCCAjmgAwIBAgIFNAAAAAYwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEbMBkGA1UEAxMSVFIzNCBTYW1wbGUg\n" +
"Q0EgS0RIMB4XDTEwMTEwMjAwMDAwMFoXDTIwMTAyOTIzNTk1OVowQDELMAkGA1UE\n" +
"BhMCVVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEaMBgGA1UEAxMRVFIzNCBTYW1w\n" +
"bGUgS0RIIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDD648pBL7L\n" +
"b5Hvyjjbt13ZGTHKj+IRZj9Ib8q6B6DC7YfLUobFCNotHw7e3cCn21xgXby5q3PR\n" +
"YbsaDxsO5VV4D697yrpeBt/viJ5R9o/mXcIa8AA6hvFwbkYeFQK+pFh3uuICZY+8\n" +
"ouvtVpIBhjV/cU5b7slwoeqICKn0Ji8vZEOCedh8ZMF+ObpxMPR7SqRBNkP4aphi\n" +
"o1rZNz2OLSjFksilIXMbqVyORDJ6uw7OUL+ubOjq9JNOlIxqO4vr4mimknvIfhrn\n" +
"ktUxUzmbS4KILJp55DHRDc5YQHBTuSv21tZyKbtyquAQgn5xJtdXBAbKqp9NtPKM\n" +
"S9ZKnvyYoOrNAgMBAAGjUTBPMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgbAMAkGA1Ud\n" +
"EwQCMAAwHQYDVR0OBBYEFA8RoQrHXhlpbL0WonoyGxhajYcHMAsGA1UdDwQEAwIG\n" +
"wDANBgkqhkiG9w0BAQsFAAOCAQEAjadCTzoj3bOETDwaxSm3rRO/pbKj86kUVQL7\n" +
"rFQIgqZTkIGY/ljVwlJpNReYCVeJKAnpNEDw1+IWO/QoLDLy1XyZhGj4luLGqO4v\n" +
"HrdsA8g9j4Wj60+G7I+P/RJuP2orslSLV7JTiKwvrMI8jPUv0I3Q7ADbDH7MCCHG\n" +
"gd+ubgVCWWt0vYXIbzfXpB6Q0bMjjHlQAklqq4oAGrvEr/mcVNbNAXR2Ind+IPQB\n" +
"SBAjlWsUN87K5SkeSTO+EU/OG4I+TFFVy7gxQr0VQ4KbCK4fTIcYcZgtiorW6If0\n" +
"C1gvjNMu6DCl1aTjAzp6QV/rkYG+1Lk91eN8BF5jKBPOQMScrA==\n" +
"-----END CERTIFICATE-----";
// B.4 CAKDH – Certificate Authority – KDH Certificate
public static final String SAMPLE_CA_KDH_CERT_PEM = "-----BEGIN CERTIFICATE-----\n" +
"MIIDPjCCAiagAwIBAgIFNAAAAAUwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMC\n" +
"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEZMBcGA1UEAxMQVFIzNCBTYW1wbGUg\n" +
"Um9vdDAeFw0xMDExMDIwMDAwMDBaFw0yNTEwMjgyMzU5NTlaMEExCzAJBgNVBAYT\n" +
"AlVTMRUwEwYDVQQKEwxUUjM0IFNhbXBsZXMxGzAZBgNVBAMTElRSMzQgU2FtcGxl\n" +
"IENBIEtESDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK76HXOWw9uk\n" +
"meVdeqUHFKxedcEnHZAA6u7SoAerZGZwUV9DISyKILwyy2exzV1xL2Z3b3dtWLxf\n" +
"gXMMU5Y2IitEKMiq/PzQDLzoSXBwZsGUbQ6vsjMTtqatvyPpIvWV0e5XpsS+AU1q\n" +
"ZOXZxFQpySBBDh8Swl5VAAZdSXpHeM8DVg3oEYbO1+W3R0odRwPqr5RAajxzFE34\n" +
"yXH4ec8zro6YSN5QUbRgKaYslJe86GrxUkYLOUOuJM/5zoj1pQSF2hSz0x3Txp3y\n" +
"QQXSUmJT6jiJ/hxv2DOoE69D/sQMQPiC2t5O6/5YAUSN3L2d5Pu2nVaggQ4IK3Mq\n" +
"NeoqFnByhv8CAwEAAaM/MD0wDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUuCpY\n" +
"Cg159koHx1irw5NlY183yhgwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IB\n" +
"AQCb+yPhlvcoHPANAfIV6DVxd7CoPzLihuz4VjE24OQZ8LvIa5l++fmeD3mwonKO\n" +
"CVAu1zBO1qzguAP1nybImPeoFPpMGUq0A+HpmY0cFhUW5HcYrFp4UnUyPqOtmKVA\n" +
"7kr2W5qMPoMcuDO778vNQXNDyeskBOi+LMfdVy1OFIW7OS+L9xp5L2k4koMCyjse\n" +
"65sUl87YMe+EOqVYWCImFmgjilnAn2uF3cn9BheEXstxyPJ7RNxLFPNqv7lFQkgm\n" +
"SfKTqvfEYirqrAinZBVp9uU6ZOEE+C84pKCXZDrcuQf8EVJK9HLX0NCQcxfD32OU\n" +
"7N32YnGn+yrjDPjVgXyDVt+D\n" +
"-----END CERTIFICATE-----";
private final X509Certificate rootCert;
private final X509Certificate krdCaCert;
private final X509Certificate kdhCaCert;
private final X509Certificate kdhCert;
private final PrivateKey krdCaPrivateKey;
private final PrivateKey kdhCaPrivateKey;
private final PrivateKey kdhPrivateKey;
private AscSampleTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) {
kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem);
if (kdhPrivateKeyPem != null) {
kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem);
} else {
kdhPrivateKey = null;
}
rootCert = Tr34CryptoUtils.parseCert(SAMPLE_ROOT_CERT_PEM);
kdhCaCert = Tr34CryptoUtils.parseCert(SAMPLE_CA_KDH_CERT_PEM);
krdCaCert = null;
kdhCaPrivateKey = null;
krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(SAMPLE_KRD_1_PRIVATE_KEY_PEM);
}
public static final Tr34KeyStoreData KDH_1 =
new AscSampleTr34KeyStoreData(SAMPLE_KDH_1_CERT_PEM, null);
@Override
public X509Certificate getRootCert() {
return rootCert;
}
@Override
public X509Certificate getKdhCaCert() {
return kdhCaCert;
}
@Override
public X509Certificate getKdhCert() {
return kdhCert;
}
@Override
public X509Certificate getKrdCaCert() {
return krdCaCert;
}
@Override | public Tr34ScdKeyStoreData getKdhKeyStoreData() { | 3 | 2023-11-22 06:30:40+00:00 | 12k |
trgpnt/java-class-jacksonizer | src/main/java/com/aggregated/entry_point/InputEntry.java | [
{
"identifier": "Driver",
"path": "src/main/java/com/aggregated/Driver.java",
"snippet": "public class Driver {\n private static final ClassDecorator decorator = ClassDecorator.emptyInstance();\n\n public static void JacksonModePackageExecution(String packageName) {\n\n decorator.reset();\n... | import com.aggregated.Driver;
import com.aggregated.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Objects; | 7,679 | package com.aggregated.entry_point;
public class InputEntry {
private static final Logger LOG = LoggerFactory.getLogger(InputEntry.class);
private final static String INPUT_FILE_NAME = "input.txt";
private final static String SKIP_INDICATOR = "#";
private static final String BASE_PATH = "src//main//java//";
private static boolean isSinglePackage = false;
public static void main(String[] args) {
scanPackageOrSingleJava();
}
public static String resolveJavaFile(String inp) {
int firstUpperCaseIdx = isPackage(inp);
if (firstUpperCaseIdx == -1) {
return inp;
}
String fullJavaName = inp.substring(0, firstUpperCaseIdx) + inp.substring(firstUpperCaseIdx) + ".java";
return fullJavaName;
}
private static int isPackage(String inp) {
for (int i = 0, n = inp.length(); i < n; i++) {
if (Character.isUpperCase(inp.charAt(i))) {
return i;
}
}
return -1;
}
private static void scanPackageOrSingleJava() {
/**
* Build defined values
*/
isSinglePackage = false;
ClassLoader classLoader = InputEntry.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(INPUT_FILE_NAME);
if (Objects.isNull(inputStream)) {
return;
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isEmpty() || line.contains(SKIP_INDICATOR)) {
continue;
}
if (evalSinglePackage(line)) {
isSinglePackage = true;
line = resolveReplaces(line, ".*", "", "**", "", "*", "", " ", "");
scanClassesInPackage(line);
} else {
line = resolveJavaFile(StringUtils.stripDoubleEndedNonAlphaNumeric(line)); | package com.aggregated.entry_point;
public class InputEntry {
private static final Logger LOG = LoggerFactory.getLogger(InputEntry.class);
private final static String INPUT_FILE_NAME = "input.txt";
private final static String SKIP_INDICATOR = "#";
private static final String BASE_PATH = "src//main//java//";
private static boolean isSinglePackage = false;
public static void main(String[] args) {
scanPackageOrSingleJava();
}
public static String resolveJavaFile(String inp) {
int firstUpperCaseIdx = isPackage(inp);
if (firstUpperCaseIdx == -1) {
return inp;
}
String fullJavaName = inp.substring(0, firstUpperCaseIdx) + inp.substring(firstUpperCaseIdx) + ".java";
return fullJavaName;
}
private static int isPackage(String inp) {
for (int i = 0, n = inp.length(); i < n; i++) {
if (Character.isUpperCase(inp.charAt(i))) {
return i;
}
}
return -1;
}
private static void scanPackageOrSingleJava() {
/**
* Build defined values
*/
isSinglePackage = false;
ClassLoader classLoader = InputEntry.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(INPUT_FILE_NAME);
if (Objects.isNull(inputStream)) {
return;
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.isEmpty() || line.contains(SKIP_INDICATOR)) {
continue;
}
if (evalSinglePackage(line)) {
isSinglePackage = true;
line = resolveReplaces(line, ".*", "", "**", "", "*", "", " ", "");
scanClassesInPackage(line);
} else {
line = resolveJavaFile(StringUtils.stripDoubleEndedNonAlphaNumeric(line)); | Driver.JacksonModeSingleJavaExecution(line); | 0 | 2023-11-23 10:59:01+00:00 | 12k |
clasSeven7/sebo-cultural | src/Main.java | [
{
"identifier": "IClienteRepository",
"path": "src/Domain/Repositories/IClienteRepository.java",
"snippet": "public interface IClienteRepository {\n ArrayList<Cliente> buscar();\n void criar(Cliente cliente);\n void atualizar(String clienteId, Cliente cliente);\n void deletar(String clienteI... | import Domain.Repositories.IClienteRepository;
import Domain.Repositories.IEstoqueRepository;
import Domain.Repositories.ILivroRepository;
import Domain.Repositories.IRevistaRepository;
import Domain.Services.ClienteService;
import Domain.Services.Contracts.IClienteService;
import Domain.Services.Contracts.IEstoqueService;
import Domain.Services.Contracts.ILivroService;
import Domain.Services.Contracts.IRevistaService;
import Domain.Services.EstoqueService;
import Domain.Services.LivroService;
import Domain.Services.RevistaService;
import Infrastructure.ClienteRepository;
import Infrastructure.EstoqueRepository;
import Infrastructure.LivroRepository;
import Infrastructure.RevistaRepository;
import Presentation.Cli.CliFacade; | 7,587 |
public class Main {
public static void main(String[] args) {
ILivroRepository livroRepository = new LivroRepository();
ILivroService livroService = new LivroService(livroRepository);
IRevistaRepository revistaRepository = new RevistaRepository();
IRevistaService revistaService = new RevistaService(revistaRepository);
IEstoqueRepository estoqueRepository = new EstoqueRepository();
IEstoqueService estoqueService = new EstoqueService(estoqueRepository);
IClienteRepository clienteRepository = new ClienteRepository();
IClienteService clienteService = new ClienteService(clienteRepository);
|
public class Main {
public static void main(String[] args) {
ILivroRepository livroRepository = new LivroRepository();
ILivroService livroService = new LivroService(livroRepository);
IRevistaRepository revistaRepository = new RevistaRepository();
IRevistaService revistaService = new RevistaService(revistaRepository);
IEstoqueRepository estoqueRepository = new EstoqueRepository();
IEstoqueService estoqueService = new EstoqueService(estoqueRepository);
IClienteRepository clienteRepository = new ClienteRepository();
IClienteService clienteService = new ClienteService(clienteRepository);
| var cli = new CliFacade(livroService, revistaService, estoqueService, clienteService); | 16 | 2023-11-19 02:11:46+00:00 | 12k |
FalkorDB/JFalkorDB | src/main/java/com/falkordb/impl/api/GraphContextImpl.java | [
{
"identifier": "GraphContext",
"path": "src/main/java/com/falkordb/GraphContext.java",
"snippet": "public interface GraphContext extends Graph {\n\n /**\n * Returns a Redis transactional object, over the connection context, with graph API capabilities\n * @return Redis transactional object, ... | import java.util.List;
import com.falkordb.GraphContext;
import com.falkordb.GraphPipeline;
import com.falkordb.GraphTransaction;
import com.falkordb.ResultSet;
import com.falkordb.exceptions.GraphException;
import com.falkordb.impl.Utils;
import com.falkordb.impl.graph_cache.GraphCache;
import com.falkordb.impl.resultset.ResultSetImpl;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.util.SafeEncoder; | 7,607 | package com.falkordb.impl.api;
/**
* An implementation of GraphContext. Allows sending Graph and some Redis commands,
* within a specific connection context
*/
public class GraphContextImpl extends AbstractGraph implements GraphContext {
private final Jedis connection;
private final String graphId;
private GraphCache cache;
/**
* Generates a new instance with a specific Jedis connection
* @param connection Jedis connection
* @param cache GraphCache
* @param graphId graph id
*/
public GraphContextImpl(Jedis connection, GraphCache cache, String graphId) {
this.connection = connection;
this.graphId = graphId;
this.cache = cache;
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.RO_QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.RO_QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Creates a new GraphTransaction transactional object
* @return new GraphTransaction
*/
@Override | package com.falkordb.impl.api;
/**
* An implementation of GraphContext. Allows sending Graph and some Redis commands,
* within a specific connection context
*/
public class GraphContextImpl extends AbstractGraph implements GraphContext {
private final Jedis connection;
private final String graphId;
private GraphCache cache;
/**
* Generates a new instance with a specific Jedis connection
* @param connection Jedis connection
* @param cache GraphCache
* @param graphId graph id
*/
public GraphContextImpl(Jedis connection, GraphCache cache, String graphId) {
this.connection = connection;
this.graphId = graphId;
this.cache = cache;
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendCommand(GraphCommand.RO_QUERY, graphId, preparedQuery, Utils.COMPACT_STRING);
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Sends the query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException rt) {
throw rt;
} catch (JedisDataException j) {
throw new GraphException(j);
}
}
/**
* Sends the read-only query over the instance only connection
* @param preparedQuery prepared query
* @param timeout timeout in milliseconds
* @return Result set with the query answer
*/
@Override
protected ResultSet sendReadOnlyQuery(String preparedQuery, long timeout) {
try {
@SuppressWarnings("unchecked")
List<Object> rawResponse = (List<Object>) connection.sendBlockingCommand(GraphCommand.RO_QUERY,
graphId, preparedQuery, Utils.COMPACT_STRING, Utils.TIMEOUT_STRING, Long.toString(timeout));
return new ResultSetImpl(rawResponse, this, this.cache);
} catch (GraphException ge) {
throw ge;
} catch (JedisDataException de) {
throw new GraphException(de);
}
}
/**
* Creates a new GraphTransaction transactional object
* @return new GraphTransaction
*/
@Override | public GraphTransaction multi() { | 2 | 2023-11-26 13:38:14+00:00 | 12k |
DueWesternersProgramming/FRC-2023-Swerve-Offseason | src/main/java/frc/robot/subsystems/DriveSubsystem.java | [
{
"identifier": "EntechSubsystem",
"path": "src/main/java/entech/subsystems/EntechSubsystem.java",
"snippet": "public abstract class EntechSubsystem extends SubsystemBase {\n\n public EntechSubsystem() { \n }\n\tpublic abstract void initialize();\n\tpublic abstract boolean isEnabled();\n}"
... | import java.util.Optional;
import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.math.filter.SlewRateLimiter;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.geometry.Rotation2d;
import edu.wpi.first.math.geometry.Translation2d;
import edu.wpi.first.math.kinematics.ChassisSpeeds;
import edu.wpi.first.math.kinematics.SwerveDriveKinematics;
import edu.wpi.first.math.kinematics.SwerveDriveOdometry;
import edu.wpi.first.math.kinematics.SwerveModulePosition;
import edu.wpi.first.math.kinematics.SwerveModuleState;
import edu.wpi.first.math.util.Units;
import edu.wpi.first.util.WPIUtilJNI;
import edu.wpi.first.wpilibj.I2C.Port;
import edu.wpi.first.wpilibj.smartdashboard.Field2d;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import entech.subsystems.EntechSubsystem;
import frc.robot.RobotConstants;
import frc.robot.RobotConstants.DrivetrainConstants;
import frc.robot.swerve.SwerveModule;
import frc.robot.swerve.SwerveUtils; | 7,575 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
/**
* The {@code Drivetrain} class contains fields and methods pertaining to the
* function of the drivetrain.
*/
public class DriveSubsystem extends EntechSubsystem {
private static final boolean ENABLED = true;
public static final double FRONT_LEFT_VIRTUAL_OFFSET_RADIANS = 5.30603;
public static final double FRONT_RIGHT_VIRTUAL_OFFSET_RADIANS = 3.31033;
public static final double REAR_LEFT_VIRTUAL_OFFSET_RADIANS = 0.59211;
public static final double REAR_RIGHT_VIRTUAL_OFFSET_RADIANS = 5.67266;
public static final int GYRO_ORIENTATION = 1; // might be able to merge with kGyroReversed
public static final double FIELD_LENGTH_INCHES = 54 * 12 + 1; // 54ft 1in
public static final double FIELD_WIDTH_INCHES = 26 * 12 + 7; // 26ft 7in
private SwerveModule m_frontLeft;
private SwerveModule m_frontRight;
private SwerveModule m_rearLeft;
private SwerveModule m_rearRight;
private AHRS m_gyro;
private double m_currentRotation = 0.0;
private double m_currentTranslationDir = 0.0;
private double m_currentTranslationMag = 0.0;
private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DrivetrainConstants.MAGNITUDE_SLEW_RATE);
private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DrivetrainConstants.ROTATIONAL_SLEW_RATE);
private double m_prevTime = WPIUtilJNI.now() * 1e-6;
private SwerveDriveOdometry m_odometry;
Field2d field = new Field2d();
/** Creates a new Drivetrain. */
public DriveSubsystem() {
}
// Bad look on scope needs to be fixed
// public Pose3d createPose3d() {
// Pose2d initial = m_odometry.getPoseMeters();
// return new Pose3d(new Translation3d(initial.getX(), initial.getY(), 0.0),
// new Rotation3d(Units.degreesToRadians(m_gyro.getRoll()),
// Units.degreesToRadians(m_gyro.getPitch()),
// Units.degreesToRadians(m_gyro.getYaw() * -1)));
// }
private double getGyroAngle() {
return m_gyro.getAngle() + 0;
}
@Override
public void periodic() {
if (ENABLED) {
field.setRobotPose(m_odometry.getPoseMeters());
SmartDashboard.putData("Odometry Pose Field", field);
SmartDashboard.putNumberArray("modules pose angles", new double[] {
m_frontLeft.getPosition().angle.getDegrees(),
m_frontRight.getPosition().angle.getDegrees(),
m_rearLeft.getPosition().angle.getDegrees(),
m_rearRight.getPosition().angle.getDegrees()
});
SmartDashboard.putNumberArray("modules pose meters", new double[] {
m_frontLeft.getPosition().distanceMeters,
m_frontRight.getPosition().distanceMeters,
m_rearLeft.getPosition().distanceMeters,
m_rearRight.getPosition().distanceMeters
});
SmartDashboard.putNumberArray("Virtual abs encoders", new double[] {
m_frontLeft.getTurningAbsoluteEncoder().getVirtualPosition(),
m_frontRight.getTurningAbsoluteEncoder().getVirtualPosition(),
m_rearLeft.getTurningAbsoluteEncoder().getVirtualPosition(),
m_rearRight.getTurningAbsoluteEncoder().getVirtualPosition()
});
SmartDashboard.putNumberArray("Raw abs encoders", new double[] {
m_frontLeft.getTurningAbsoluteEncoder().getPosition(),
m_frontRight.getTurningAbsoluteEncoder().getPosition(),
m_rearLeft.getTurningAbsoluteEncoder().getPosition(),
m_rearRight.getTurningAbsoluteEncoder().getPosition()
});
SmartDashboard.putNumber("LEFT", m_rearRight.getTurningAbsoluteEncoder().getPosition());
SmartDashboard.putData("NAVX", m_gyro);
// Update the odometry in the periodic block
m_odometry.update(
Rotation2d.fromDegrees(GYRO_ORIENTATION * m_gyro.getAngle()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
});
}
}
/**
* Returns the currently-estimated pose of the robot.
*
* @return The pose.
*/
public Optional<Pose2d> getPose() {
return ENABLED ? Optional.of(m_odometry.getPoseMeters()) : Optional.empty();
}
/**
* Resets the odometry to the specified pose.
*
* @param pose The pose to which to set the odometry.
*/
public void resetOdometry(Pose2d pose) {
if (ENABLED) {
m_odometry.resetPosition(
Rotation2d.fromDegrees(GYRO_ORIENTATION * m_gyro.getAngle()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
},
pose);
}
}
/**
* Method to drive the robot using joystick info.
*
* @param xSpeed Speed of the robot in the x direction (forward).
* @param ySpeed Speed of the robot in the y direction (sideways).
* @param rot Angular rate of the robot.
* @param fieldRelative Whether the provided x and y speeds are relative to the
* field.
* @param rateLimit Whether to enable rate limiting for smoother control.
*/
public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) {
if (ENABLED) {
double xSpeedCommanded;
double ySpeedCommanded;
if (rateLimit) {
// Convert XY to polar for rate limiting
double inputTranslationDir = Math.atan2(ySpeed, xSpeed);
double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2));
// Calculate the direction slew rate based on an estimate of the lateral
// acceleration
double directionSlewRate;
if (m_currentTranslationMag != 0.0) {
directionSlewRate = Math.abs(DrivetrainConstants.DIRECTION_SLEW_RATE / m_currentTranslationMag);
} else {
directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous
}
double currentTime = WPIUtilJNI.now() * 1e-6;
double elapsedTime = currentTime - m_prevTime; | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.subsystems;
/**
* The {@code Drivetrain} class contains fields and methods pertaining to the
* function of the drivetrain.
*/
public class DriveSubsystem extends EntechSubsystem {
private static final boolean ENABLED = true;
public static final double FRONT_LEFT_VIRTUAL_OFFSET_RADIANS = 5.30603;
public static final double FRONT_RIGHT_VIRTUAL_OFFSET_RADIANS = 3.31033;
public static final double REAR_LEFT_VIRTUAL_OFFSET_RADIANS = 0.59211;
public static final double REAR_RIGHT_VIRTUAL_OFFSET_RADIANS = 5.67266;
public static final int GYRO_ORIENTATION = 1; // might be able to merge with kGyroReversed
public static final double FIELD_LENGTH_INCHES = 54 * 12 + 1; // 54ft 1in
public static final double FIELD_WIDTH_INCHES = 26 * 12 + 7; // 26ft 7in
private SwerveModule m_frontLeft;
private SwerveModule m_frontRight;
private SwerveModule m_rearLeft;
private SwerveModule m_rearRight;
private AHRS m_gyro;
private double m_currentRotation = 0.0;
private double m_currentTranslationDir = 0.0;
private double m_currentTranslationMag = 0.0;
private SlewRateLimiter m_magLimiter = new SlewRateLimiter(DrivetrainConstants.MAGNITUDE_SLEW_RATE);
private SlewRateLimiter m_rotLimiter = new SlewRateLimiter(DrivetrainConstants.ROTATIONAL_SLEW_RATE);
private double m_prevTime = WPIUtilJNI.now() * 1e-6;
private SwerveDriveOdometry m_odometry;
Field2d field = new Field2d();
/** Creates a new Drivetrain. */
public DriveSubsystem() {
}
// Bad look on scope needs to be fixed
// public Pose3d createPose3d() {
// Pose2d initial = m_odometry.getPoseMeters();
// return new Pose3d(new Translation3d(initial.getX(), initial.getY(), 0.0),
// new Rotation3d(Units.degreesToRadians(m_gyro.getRoll()),
// Units.degreesToRadians(m_gyro.getPitch()),
// Units.degreesToRadians(m_gyro.getYaw() * -1)));
// }
private double getGyroAngle() {
return m_gyro.getAngle() + 0;
}
@Override
public void periodic() {
if (ENABLED) {
field.setRobotPose(m_odometry.getPoseMeters());
SmartDashboard.putData("Odometry Pose Field", field);
SmartDashboard.putNumberArray("modules pose angles", new double[] {
m_frontLeft.getPosition().angle.getDegrees(),
m_frontRight.getPosition().angle.getDegrees(),
m_rearLeft.getPosition().angle.getDegrees(),
m_rearRight.getPosition().angle.getDegrees()
});
SmartDashboard.putNumberArray("modules pose meters", new double[] {
m_frontLeft.getPosition().distanceMeters,
m_frontRight.getPosition().distanceMeters,
m_rearLeft.getPosition().distanceMeters,
m_rearRight.getPosition().distanceMeters
});
SmartDashboard.putNumberArray("Virtual abs encoders", new double[] {
m_frontLeft.getTurningAbsoluteEncoder().getVirtualPosition(),
m_frontRight.getTurningAbsoluteEncoder().getVirtualPosition(),
m_rearLeft.getTurningAbsoluteEncoder().getVirtualPosition(),
m_rearRight.getTurningAbsoluteEncoder().getVirtualPosition()
});
SmartDashboard.putNumberArray("Raw abs encoders", new double[] {
m_frontLeft.getTurningAbsoluteEncoder().getPosition(),
m_frontRight.getTurningAbsoluteEncoder().getPosition(),
m_rearLeft.getTurningAbsoluteEncoder().getPosition(),
m_rearRight.getTurningAbsoluteEncoder().getPosition()
});
SmartDashboard.putNumber("LEFT", m_rearRight.getTurningAbsoluteEncoder().getPosition());
SmartDashboard.putData("NAVX", m_gyro);
// Update the odometry in the periodic block
m_odometry.update(
Rotation2d.fromDegrees(GYRO_ORIENTATION * m_gyro.getAngle()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
});
}
}
/**
* Returns the currently-estimated pose of the robot.
*
* @return The pose.
*/
public Optional<Pose2d> getPose() {
return ENABLED ? Optional.of(m_odometry.getPoseMeters()) : Optional.empty();
}
/**
* Resets the odometry to the specified pose.
*
* @param pose The pose to which to set the odometry.
*/
public void resetOdometry(Pose2d pose) {
if (ENABLED) {
m_odometry.resetPosition(
Rotation2d.fromDegrees(GYRO_ORIENTATION * m_gyro.getAngle()),
new SwerveModulePosition[] {
m_frontLeft.getPosition(),
m_frontRight.getPosition(),
m_rearLeft.getPosition(),
m_rearRight.getPosition()
},
pose);
}
}
/**
* Method to drive the robot using joystick info.
*
* @param xSpeed Speed of the robot in the x direction (forward).
* @param ySpeed Speed of the robot in the y direction (sideways).
* @param rot Angular rate of the robot.
* @param fieldRelative Whether the provided x and y speeds are relative to the
* field.
* @param rateLimit Whether to enable rate limiting for smoother control.
*/
public void drive(double xSpeed, double ySpeed, double rot, boolean fieldRelative, boolean rateLimit) {
if (ENABLED) {
double xSpeedCommanded;
double ySpeedCommanded;
if (rateLimit) {
// Convert XY to polar for rate limiting
double inputTranslationDir = Math.atan2(ySpeed, xSpeed);
double inputTranslationMag = Math.sqrt(Math.pow(xSpeed, 2) + Math.pow(ySpeed, 2));
// Calculate the direction slew rate based on an estimate of the lateral
// acceleration
double directionSlewRate;
if (m_currentTranslationMag != 0.0) {
directionSlewRate = Math.abs(DrivetrainConstants.DIRECTION_SLEW_RATE / m_currentTranslationMag);
} else {
directionSlewRate = 500.0; // some high number that means the slew rate is effectively instantaneous
}
double currentTime = WPIUtilJNI.now() * 1e-6;
double elapsedTime = currentTime - m_prevTime; | double angleDif = SwerveUtils.AngleDifference(inputTranslationDir, m_currentTranslationDir); | 4 | 2023-11-21 01:49:41+00:00 | 12k |
Staffilon/KestraDataOrchestrator | IoT Simulator/src/main/java/net/acesinc/data/json/generator/JsonDataGenerator.java | [
{
"identifier": "JSONConfigReader",
"path": "IoT Simulator/src/main/java/net/acesinc/data/json/generator/config/JSONConfigReader.java",
"snippet": "public class JSONConfigReader {\n private static final Logger log = LogManager.getLogger(JSONConfigReader.class);\n \n public static String getJsonC... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.pulsar.client.api.PulsarClientException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;
import net.acesinc.data.json.generator.config.JSONConfigReader;
import net.acesinc.data.json.generator.config.SimulationConfig;
import net.acesinc.data.json.generator.log.AzureIoTHubLogger;
import net.acesinc.data.json.generator.log.EventLogger;
import net.acesinc.data.json.generator.log.FileLogger;
import net.acesinc.data.json.generator.log.HttpPostLogger;
import net.acesinc.data.json.generator.log.KafkaLogger;
import net.acesinc.data.json.generator.log.KinesisLogger;
import net.acesinc.data.json.generator.log.Log4JLogger;
import net.acesinc.data.json.generator.log.MqttLogger;
import net.acesinc.data.json.generator.log.NatsLogger;
import net.acesinc.data.json.generator.log.PulsarLogger;
import net.acesinc.data.json.generator.log.TranquilityLogger;
import net.acesinc.data.json.generator.log.WampLogger; | 10,546 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.acesinc.data.json.generator;
/**
*
* @author andrewserff
*/
@RestController
public class JsonDataGenerator {
@Autowired
Environment environment;
private static final Logger log = LogManager.getLogger(JsonDataGenerator.class);
private SimulationRunner simRunner;
private String simConfigFile;
public JsonDataGenerator() {
}
public String getFilePath(String file) {
String filePath = getSimulationContentPath() + "/" + file;
return filePath;
}
public String getSimulationContentPath() {
String folder = null;
if (environment != null)
environment.getProperty("myApp.folder", "conf");
else
folder = System.getProperty("myApp.folder", "conf");
return folder;
}
public JsonDataGenerator setUpSimulation(String simConfigString) {
simConfigFile = simConfigString;
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
try {
log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]");
SimulationConfig simConfig = getSimConfig();
List<EventLogger> loggers = new ArrayList<>();
for (Map<String, Object> elProps : simConfig.getProducers()) {
String elType = (String) elProps.get("type");
switch (elType) {
case "logger": {
log.info("Adding Log4JLogger Producer");
loggers.add(new Log4JLogger());
break;
}
case "file": {
log.info("Adding File Logger with properties: " + elProps);
loggers.add(new FileLogger(queue, elProps));
break;
}
case "kafka": {
log.info("Adding Kafka Producer with properties: " + elProps);
loggers.add(new KafkaLogger(queue, elProps));
break;
}
case "tranquility": {
log.info("Adding Tranqulity Logger with properties: " + elProps);
loggers.add(new TranquilityLogger(queue, elProps));
break;
}
case "nats": {
log.info("Adding NATS Logger with properties: " + elProps);
loggers.add(new NatsLogger(queue, elProps));
break;
}
case "http-post": {
log.info("Adding HTTP Post Logger with properties: " + elProps);
try { | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.acesinc.data.json.generator;
/**
*
* @author andrewserff
*/
@RestController
public class JsonDataGenerator {
@Autowired
Environment environment;
private static final Logger log = LogManager.getLogger(JsonDataGenerator.class);
private SimulationRunner simRunner;
private String simConfigFile;
public JsonDataGenerator() {
}
public String getFilePath(String file) {
String filePath = getSimulationContentPath() + "/" + file;
return filePath;
}
public String getSimulationContentPath() {
String folder = null;
if (environment != null)
environment.getProperty("myApp.folder", "conf");
else
folder = System.getProperty("myApp.folder", "conf");
return folder;
}
public JsonDataGenerator setUpSimulation(String simConfigString) {
simConfigFile = simConfigString;
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();
try {
log.debug("Creating Simulation Runner using Simulation Config [ " + simConfigString + " ]");
SimulationConfig simConfig = getSimConfig();
List<EventLogger> loggers = new ArrayList<>();
for (Map<String, Object> elProps : simConfig.getProducers()) {
String elType = (String) elProps.get("type");
switch (elType) {
case "logger": {
log.info("Adding Log4JLogger Producer");
loggers.add(new Log4JLogger());
break;
}
case "file": {
log.info("Adding File Logger with properties: " + elProps);
loggers.add(new FileLogger(queue, elProps));
break;
}
case "kafka": {
log.info("Adding Kafka Producer with properties: " + elProps);
loggers.add(new KafkaLogger(queue, elProps));
break;
}
case "tranquility": {
log.info("Adding Tranqulity Logger with properties: " + elProps);
loggers.add(new TranquilityLogger(queue, elProps));
break;
}
case "nats": {
log.info("Adding NATS Logger with properties: " + elProps);
loggers.add(new NatsLogger(queue, elProps));
break;
}
case "http-post": {
log.info("Adding HTTP Post Logger with properties: " + elProps);
try { | loggers.add(new HttpPostLogger(queue, elProps)); | 5 | 2023-11-26 10:57:17+00:00 | 12k |
Invadermonky/JustEnoughMagiculture | src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERThaumcraft.java | [
{
"identifier": "JEMConfig",
"path": "src/main/java/com/invadermonky/justenoughmagiculture/configs/JEMConfig.java",
"snippet": "@LangKey(\"config.\" + JustEnoughMagiculture.MOD_ALIAS + \":\" + JustEnoughMagiculture.MOD_ALIAS)\n@Config(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustE... | import com.invadermonky.justenoughmagiculture.configs.JEMConfig;
import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigThaumcraft;
import com.invadermonky.justenoughmagiculture.integrations.jei.categories.lootbag.LootBagEntry;
import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration;
import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase;
import com.invadermonky.justenoughmagiculture.registry.LootBagRegistry;
import com.invadermonky.justenoughmagiculture.util.BiomeHelper;
import com.invadermonky.justenoughmagiculture.util.ModIds;
import com.invadermonky.justenoughmagiculture.util.StringHelper;
import jeresources.api.conditionals.Conditional;
import jeresources.api.conditionals.LightLevel;
import jeresources.api.drop.LootDrop;
import jeresources.util.LootTableHelper;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.FurnaceRecipes;
import net.minecraft.world.EnumDifficulty;
import net.minecraft.world.storage.loot.*;
import net.minecraft.world.storage.loot.conditions.LootCondition;
import net.minecraft.world.storage.loot.functions.LootFunction;
import net.minecraft.world.storage.loot.functions.SetCount;
import net.minecraft.world.storage.loot.functions.SetMetadata;
import net.minecraft.world.storage.loot.functions.SetNBT;
import net.minecraftforge.common.BiomeDictionary.Type;
import thaumcraft.api.ThaumcraftApiHelper;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.blocks.BlocksTC;
import thaumcraft.api.internal.WeightedRandomLoot;
import thaumcraft.api.items.ItemsTC;
import thaumcraft.common.blocks.world.BlockLoot;
import thaumcraft.common.config.ConfigItems;
import thaumcraft.common.entities.monster.*;
import thaumcraft.common.entities.monster.boss.*;
import thaumcraft.common.entities.monster.cult.EntityCultist;
import thaumcraft.common.entities.monster.cult.EntityCultistCleric;
import thaumcraft.common.entities.monster.cult.EntityCultistKnight;
import thaumcraft.common.entities.monster.tainted.*;
import thecodex6824.thaumicaugmentation.api.TALootTables;
import java.util.ArrayList; | 9,346 | package com.invadermonky.justenoughmagiculture.integrations.jer.mods;
public class JERThaumcraft extends JERBase implements IJERIntegration {
private static JERThaumcraft instance; | package com.invadermonky.justenoughmagiculture.integrations.jer.mods;
public class JERThaumcraft extends JERBase implements IJERIntegration {
private static JERThaumcraft instance; | private static final JEMConfigThaumcraft.JER jerConfig = JEMConfig.THAUMCRAFT.JUST_ENOUGH_RESOURCES; | 0 | 2023-11-19 23:09:14+00:00 | 12k |
Provismet/ProviHealth | src/main/java/com/provismet/provihealth/hud/TargetHealthBar.java | [
{
"identifier": "ProviHealthClient",
"path": "src/main/java/com/provismet/provihealth/ProviHealthClient.java",
"snippet": "public class ProviHealthClient implements ClientModInitializer {\n public static final String MODID = \"provihealth\";\n public static final Logger LOGGER = LoggerFactory.getL... | import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
import org.joml.Quaternionf;
import org.joml.Vector3f;
import com.mojang.blaze3d.systems.RenderSystem;
import com.provismet.provihealth.ProviHealthClient;
import com.provismet.provihealth.config.Options;
import com.provismet.provihealth.config.Options.HUDPosition;
import com.provismet.provihealth.config.Options.HUDType;
import com.provismet.provihealth.util.Visibility;
import com.provismet.provihealth.world.EntityHealthBar;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.render.DiffuseLighting;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityPose;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper; | 8,629 | package com.provismet.provihealth.hud;
public class TargetHealthBar implements HudRenderCallback {
public static boolean disabledLabels = false;
private static final Identifier BARS = ProviHealthClient.identifier("textures/gui/healthbars/bars.png");
private static final Identifier COMPAT_BARS = ProviHealthClient.identifier("textures/gui/healthbars/bars_coloured.png");
private static final Identifier HEART = ProviHealthClient.identifier("textures/gui/healthbars/icons/heart.png");
private static final Identifier MOUNT_HEART = ProviHealthClient.identifier("textures/gui/healthbars/icons/mount_heart.png");
private static final Identifier ARMOUR = ProviHealthClient.identifier("textures/gui/healthbars/icons/armour.png");
private static int OFFSET_X = 0;
private static int OFFSET_Y = 0;
private static final int BAR_WIDTH = 128;
private static final int BAR_HEIGHT = 10;
private static final int MOUNT_BAR_HEIGHT = 6;
private static final int MOUNT_BAR_WIDTH = 121;
private static final int FRAME_LENGTH = 48;
private static final int LEFT_TEXT_X = FRAME_LENGTH + 2;
private static int BAR_X = FRAME_LENGTH - 5;
private static int BAR_Y = OFFSET_Y + FRAME_LENGTH / 2 - (BAR_HEIGHT + MOUNT_BAR_HEIGHT) / 2;
private static final float BAR_V2 = ((float)BAR_HEIGHT / (float)(BAR_HEIGHT + MOUNT_BAR_HEIGHT)) / 2f; // Accounting for index.
private static final float MOUNT_BAR_U2 = (float)MOUNT_BAR_WIDTH / (float)BAR_WIDTH;
private static final float MOUNT_BAR_V1 = ((float)BAR_HEIGHT / (float)(BAR_HEIGHT + MOUNT_BAR_HEIGHT)) / 2f;
private static final float MOUNT_BAR_V2 = 0.5f; // Accounting for index.
private static final int BAR_WIDTH_DIFF = BAR_WIDTH - MOUNT_BAR_WIDTH;
private LivingEntity target = null;
private float healthBarDuration = 0f;
private int currentHealthWidth;
private int currentVehicleHealthWidth;
@SuppressWarnings("resource")
@Override
public void onHudRender (DrawContext drawContext, float tickDelta) {
if (this.healthBarDuration > 0f) this.healthBarDuration -= tickDelta;
else this.reset();
if (!MinecraftClient.isHudEnabled() || MinecraftClient.getInstance().getDebugHud().shouldShowDebugHud() || MinecraftClient.getInstance().player.isSpectator()) return;
boolean isNew = false;
if (MinecraftClient.getInstance().targetedEntity instanceof LivingEntity living) {
if (!Visibility.isVisible(living)) return;
if (!living.equals(this.target)) isNew = true;
this.target = living;
this.healthBarDuration = Options.maxHealthBarTicks;
}
if (this.healthBarDuration > 0f) {
if (this.target == null) {
this.reset();
return;
}
this.adjustForScreenSize();
HUDType hudType = Options.getHUDFor(this.target);
float healthPercent = MathHelper.clamp(this.target.getHealth() / this.target.getMaxHealth(), 0f, 1f);
float vehicleHealthDeep = 0f;
float vehicleMaxHealthDeep = 0f;
Entity currentEntity = this.target.getVehicle();
while (currentEntity != null) {
if (currentEntity instanceof LivingEntity currentLiving) {
vehicleHealthDeep += currentLiving.getHealth();
vehicleMaxHealthDeep += currentLiving.getMaxHealth();
}
currentEntity = currentEntity.getVehicle();
}
float vehicleHealthPercent = vehicleMaxHealthDeep > 0f ? MathHelper.clamp(vehicleHealthDeep / vehicleMaxHealthDeep, 0f, 1f) : 0f;
int healthWidth = Math.round(BAR_WIDTH * healthPercent);
int vehicleHealthWidth = Math.round(MOUNT_BAR_WIDTH * vehicleHealthPercent);
if (isNew) {
this.currentHealthWidth = healthWidth;
this.currentVehicleHealthWidth = vehicleHealthWidth;
}
final int nameWidth = MinecraftClient.getInstance().textRenderer.getWidth(this.getName(this.target));
if (hudType == HUDType.FULL) {
// Render bars
this.renderBar(drawContext, BAR_WIDTH, 1); // Empty space
this.renderBar(drawContext, glideHealth(healthWidth, tickDelta * Options.hudGlide), 0); // Health
if (vehicleMaxHealthDeep > 0f) {
this.renderMountBar(drawContext, MOUNT_BAR_WIDTH, 1); // Empty space
this.renderMountBar(drawContext, glideVehicleHealth(vehicleHealthWidth, tickDelta * Options.hudGlide), 0); // Health
}
int infoLeftX = LEFT_TEXT_X; | package com.provismet.provihealth.hud;
public class TargetHealthBar implements HudRenderCallback {
public static boolean disabledLabels = false;
private static final Identifier BARS = ProviHealthClient.identifier("textures/gui/healthbars/bars.png");
private static final Identifier COMPAT_BARS = ProviHealthClient.identifier("textures/gui/healthbars/bars_coloured.png");
private static final Identifier HEART = ProviHealthClient.identifier("textures/gui/healthbars/icons/heart.png");
private static final Identifier MOUNT_HEART = ProviHealthClient.identifier("textures/gui/healthbars/icons/mount_heart.png");
private static final Identifier ARMOUR = ProviHealthClient.identifier("textures/gui/healthbars/icons/armour.png");
private static int OFFSET_X = 0;
private static int OFFSET_Y = 0;
private static final int BAR_WIDTH = 128;
private static final int BAR_HEIGHT = 10;
private static final int MOUNT_BAR_HEIGHT = 6;
private static final int MOUNT_BAR_WIDTH = 121;
private static final int FRAME_LENGTH = 48;
private static final int LEFT_TEXT_X = FRAME_LENGTH + 2;
private static int BAR_X = FRAME_LENGTH - 5;
private static int BAR_Y = OFFSET_Y + FRAME_LENGTH / 2 - (BAR_HEIGHT + MOUNT_BAR_HEIGHT) / 2;
private static final float BAR_V2 = ((float)BAR_HEIGHT / (float)(BAR_HEIGHT + MOUNT_BAR_HEIGHT)) / 2f; // Accounting for index.
private static final float MOUNT_BAR_U2 = (float)MOUNT_BAR_WIDTH / (float)BAR_WIDTH;
private static final float MOUNT_BAR_V1 = ((float)BAR_HEIGHT / (float)(BAR_HEIGHT + MOUNT_BAR_HEIGHT)) / 2f;
private static final float MOUNT_BAR_V2 = 0.5f; // Accounting for index.
private static final int BAR_WIDTH_DIFF = BAR_WIDTH - MOUNT_BAR_WIDTH;
private LivingEntity target = null;
private float healthBarDuration = 0f;
private int currentHealthWidth;
private int currentVehicleHealthWidth;
@SuppressWarnings("resource")
@Override
public void onHudRender (DrawContext drawContext, float tickDelta) {
if (this.healthBarDuration > 0f) this.healthBarDuration -= tickDelta;
else this.reset();
if (!MinecraftClient.isHudEnabled() || MinecraftClient.getInstance().getDebugHud().shouldShowDebugHud() || MinecraftClient.getInstance().player.isSpectator()) return;
boolean isNew = false;
if (MinecraftClient.getInstance().targetedEntity instanceof LivingEntity living) {
if (!Visibility.isVisible(living)) return;
if (!living.equals(this.target)) isNew = true;
this.target = living;
this.healthBarDuration = Options.maxHealthBarTicks;
}
if (this.healthBarDuration > 0f) {
if (this.target == null) {
this.reset();
return;
}
this.adjustForScreenSize();
HUDType hudType = Options.getHUDFor(this.target);
float healthPercent = MathHelper.clamp(this.target.getHealth() / this.target.getMaxHealth(), 0f, 1f);
float vehicleHealthDeep = 0f;
float vehicleMaxHealthDeep = 0f;
Entity currentEntity = this.target.getVehicle();
while (currentEntity != null) {
if (currentEntity instanceof LivingEntity currentLiving) {
vehicleHealthDeep += currentLiving.getHealth();
vehicleMaxHealthDeep += currentLiving.getMaxHealth();
}
currentEntity = currentEntity.getVehicle();
}
float vehicleHealthPercent = vehicleMaxHealthDeep > 0f ? MathHelper.clamp(vehicleHealthDeep / vehicleMaxHealthDeep, 0f, 1f) : 0f;
int healthWidth = Math.round(BAR_WIDTH * healthPercent);
int vehicleHealthWidth = Math.round(MOUNT_BAR_WIDTH * vehicleHealthPercent);
if (isNew) {
this.currentHealthWidth = healthWidth;
this.currentVehicleHealthWidth = vehicleHealthWidth;
}
final int nameWidth = MinecraftClient.getInstance().textRenderer.getWidth(this.getName(this.target));
if (hudType == HUDType.FULL) {
// Render bars
this.renderBar(drawContext, BAR_WIDTH, 1); // Empty space
this.renderBar(drawContext, glideHealth(healthWidth, tickDelta * Options.hudGlide), 0); // Health
if (vehicleMaxHealthDeep > 0f) {
this.renderMountBar(drawContext, MOUNT_BAR_WIDTH, 1); // Empty space
this.renderMountBar(drawContext, glideVehicleHealth(vehicleHealthWidth, tickDelta * Options.hudGlide), 0); // Health
}
int infoLeftX = LEFT_TEXT_X; | if (Options.hudPosition == HUDPosition.LEFT) { | 2 | 2023-11-26 02:46:37+00:00 | 12k |
EnigmaGuest/fnk-server | service-common/service-common-db/src/main/java/fun/isite/service/common/db/impl/BaseService.java | [
{
"identifier": "LogicException",
"path": "service-common/service-common-bean/src/main/java/fun/isite/service/common/bean/exception/LogicException.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class LogicException extends RuntimeException{\n private String message;\n\n pri... | import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun.isite.service.common.bean.exception.LogicException;
import fun.isite.service.common.db.dto.SplitPageDTO;
import fun.isite.service.common.db.entity.BaseEntity;
import fun.isite.service.common.db.interf.CustomBasicPageQuery;
import fun.isite.service.common.db.service.IBaseService;
import fun.isite.service.common.db.vo.PageVO;
import fun.isite.service.common.tools.lang.AssertUtils;
import fun.isite.service.common.tools.utils.RedisUtils;
import jakarta.annotation.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; | 7,784 | }
return new PageVO<>(this.page(new Page<>(dto.getPage(), pageSize), wrapper));
}
@Override
public void resetBaseField(T t) {
if (t != null) {
t.setId(null);
t.setCreateTime(null);
t.setUpdateTime(null);
t.setDeleted((short) 0);
}
}
private LambdaQueryWrapper<T> getIdCustomQueryConsumer(String id, Consumer<LambdaQueryWrapper<T>> consumer) {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())
.eq(T::getId, id);
if (consumer != null) {
consumer.accept(wrapper);
}
return wrapper;
}
@Override
public T create(T req) {
this.resetBaseField(req);
AssertUtils.isFalse(req.insert(), "创建" + getServiceModelName() + "失败");
this.redisHashSet(false, req);
return req;
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<T> create(List<T> reqs) {
reqs.forEach(this::resetBaseField);
AssertUtils.isFalse(this.saveBatch(reqs), "批量创建" + getServiceModelName() + "失败");
this.redisHashSet(false, reqs, null);
return reqs;
}
@Override
public T update(String id, T req) {
return this.update(id, req, null);
}
@Override
public T update(String id, T req, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
T model = this.detail(id, query);
BeanUtils.copyProperties(req, model, BASE_ENTITY_FIELDS);
AssertUtils.isFalse(model.updateById(), "更新" + getServiceModelName() + "失败");
this.redisHashSet(false, req);
return model;
}
@Override
public void removeSingle(String id) {
this.removeSingle(id, null);
}
@Override
public void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
String msg = "删除" + getServiceModelName() + "失败";
if (query == null) {
AssertUtils.isFalse(this.removeById(id), msg);
} else {
AssertUtils.isFalse(this.remove(this.getIdCustomQueryConsumer(id, query)), msg);
}
this.redisHashSet(true, null, CollUtil.newArrayList(id));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> idList) {
this.remove(idList, null);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
String msg = "批量" + getServiceModelName() + "删除失败";
if (query == null) {
AssertUtils.isFalse(this.removeBatchByIds(idList), msg);
} else {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())
.in(T::getId, idList);
query.accept(wrapper);
AssertUtils.isFalse(this.remove(wrapper), msg);
}
this.redisHashSet(true, null, idList);
}
@Override
public T detail(String id) {
return this.detail(id, null);
}
@Override
public T detail(Consumer<LambdaQueryWrapper<T>> consumer) {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass());
consumer.accept(wrapper);
return this.getFirst(wrapper);
}
@Override
public T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
T model;
if (query == null) {
model = this.redisHashGet(id);
if (model != null) {
return model;
}
model = this.getById(id);
} else {
model = this.getFirst(this.getIdCustomQueryConsumer(id, query));
}
AssertUtils.isNull(model, "目标" + getServiceModelName() + "不存在");
return model;
}
private T redisHashGet(String id) {
String cacheKey = this.getModelHashCacheKey(); | package fun.isite.service.common.db.impl;
/**
* @author Enigma
*/
public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> {
public final static String[] BASE_ENTITY_FIELDS = {"id", "create_time", "update_time", "deleted"};
public final static String LIMIT_ONE = "limit 1";
@Override
public T getFirst(QueryWrapper<T> queryWrapper) {
if (queryWrapper != null) {
queryWrapper.last(LIMIT_ONE);
}
return this.getOne(queryWrapper);
}
@Override
public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())
.eq(T::getId, id);
if(wrapperConsumer!=null){
wrapperConsumer.accept(wrapper);
}
wrapper.last(LIMIT_ONE);
return this.getOne(wrapper);
}
@Override
public T getFirst(LambdaQueryWrapper<T> queryWrapper) {
if (queryWrapper != null) {
queryWrapper.last(LIMIT_ONE);
}
return this.getOne(queryWrapper);
}
@Override
public T getByField(SFunction<T, ?> field, String value) {
return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value));
}
@Override
public PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery) {
QueryWrapper<T> wrapper = new QueryWrapper<>();
wrapper.like(dto.getId() != null, "id", dto.getId());
wrapper.ge(StrUtil.isNotBlank(dto.getCreateTime()), "create_time", dto.getCreateTime());
wrapper.ge(StrUtil.isNotBlank(dto.getUpdateTime()), "update_time", dto.getUpdateTime());
LambdaQueryWrapper<T> lambdaQueryWrapper = wrapper.lambda();
lambdaQueryWrapper.orderBy(orderByField != null, dto.isAsc(), orderByField);
if (customQuery != null) {
customQuery.query(lambdaQueryWrapper);
}
int pageSize = dto.getPageSize();
if (pageSize < 0) {
pageSize = 1000;
}
return new PageVO<>(this.page(new Page<>(dto.getPage(), pageSize), wrapper));
}
@Override
public void resetBaseField(T t) {
if (t != null) {
t.setId(null);
t.setCreateTime(null);
t.setUpdateTime(null);
t.setDeleted((short) 0);
}
}
private LambdaQueryWrapper<T> getIdCustomQueryConsumer(String id, Consumer<LambdaQueryWrapper<T>> consumer) {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())
.eq(T::getId, id);
if (consumer != null) {
consumer.accept(wrapper);
}
return wrapper;
}
@Override
public T create(T req) {
this.resetBaseField(req);
AssertUtils.isFalse(req.insert(), "创建" + getServiceModelName() + "失败");
this.redisHashSet(false, req);
return req;
}
@Override
@Transactional(rollbackFor = Exception.class)
public List<T> create(List<T> reqs) {
reqs.forEach(this::resetBaseField);
AssertUtils.isFalse(this.saveBatch(reqs), "批量创建" + getServiceModelName() + "失败");
this.redisHashSet(false, reqs, null);
return reqs;
}
@Override
public T update(String id, T req) {
return this.update(id, req, null);
}
@Override
public T update(String id, T req, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
T model = this.detail(id, query);
BeanUtils.copyProperties(req, model, BASE_ENTITY_FIELDS);
AssertUtils.isFalse(model.updateById(), "更新" + getServiceModelName() + "失败");
this.redisHashSet(false, req);
return model;
}
@Override
public void removeSingle(String id) {
this.removeSingle(id, null);
}
@Override
public void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
String msg = "删除" + getServiceModelName() + "失败";
if (query == null) {
AssertUtils.isFalse(this.removeById(id), msg);
} else {
AssertUtils.isFalse(this.remove(this.getIdCustomQueryConsumer(id, query)), msg);
}
this.redisHashSet(true, null, CollUtil.newArrayList(id));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> idList) {
this.remove(idList, null);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
String msg = "批量" + getServiceModelName() + "删除失败";
if (query == null) {
AssertUtils.isFalse(this.removeBatchByIds(idList), msg);
} else {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass())
.in(T::getId, idList);
query.accept(wrapper);
AssertUtils.isFalse(this.remove(wrapper), msg);
}
this.redisHashSet(true, null, idList);
}
@Override
public T detail(String id) {
return this.detail(id, null);
}
@Override
public T detail(Consumer<LambdaQueryWrapper<T>> consumer) {
LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass());
consumer.accept(wrapper);
return this.getFirst(wrapper);
}
@Override
public T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) {
T model;
if (query == null) {
model = this.redisHashGet(id);
if (model != null) {
return model;
}
model = this.getById(id);
} else {
model = this.getFirst(this.getIdCustomQueryConsumer(id, query));
}
AssertUtils.isNull(model, "目标" + getServiceModelName() + "不存在");
return model;
}
private T redisHashGet(String id) {
String cacheKey = this.getModelHashCacheKey(); | RedisUtils redisUtil = RedisUtils.getINSTANCE(); | 7 | 2023-12-26 01:55:01+00:00 | 12k |
codingmiao/hppt | sc/src/main/java/org/wowtools/hppt/sc/StartSc.java | [
{
"identifier": "AesCipherUtil",
"path": "common/src/main/java/org/wowtools/hppt/common/util/AesCipherUtil.java",
"snippet": "@Slf4j\npublic class AesCipherUtil {\n\n public final Encryptor encryptor;\n\n public final Descriptor descriptor;\n\n\n public AesCipherUtil(String strKey, long ts) {\n... | import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.apache.logging.log4j.core.config.Configurator;
import org.wowtools.common.utils.ResourcesReader;
import org.wowtools.hppt.common.util.AesCipherUtil;
import org.wowtools.hppt.common.util.BytesUtil;
import org.wowtools.hppt.common.util.Constant;
import org.wowtools.hppt.common.util.HttpUtil;
import org.wowtools.hppt.sc.pojo.ScConfig;
import org.wowtools.hppt.sc.service.ClientPort;
import org.wowtools.hppt.sc.service.ClientSession;
import org.wowtools.hppt.sc.service.ClientSessionManager;
import org.wowtools.hppt.sc.service.ClientSessionService;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; | 9,112 | package org.wowtools.hppt.sc;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSc {
public static final ScConfig config;
public static final AesCipherUtil aesCipherUtil;
public static final String loginCode;
static {
Configurator.reconfigure(new File(ResourcesReader.getRootPath(StartSc.class) + "/log4j2.xml").toURI());
try {
config = Constant.ymlMapper.readValue(ResourcesReader.readStr(StartSc.class, "sc.yml"), ScConfig.class);
} catch (Exception e) {
throw new RuntimeException("读取配置文件异常", e);
}
AesCipherUtil _aesCipherUtil = login();
if (null == _aesCipherUtil) {
//排除整点附近登录失败的情况
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
_aesCipherUtil = login();
}
if (null == _aesCipherUtil) {
throw new RuntimeException("登录失败");
}
aesCipherUtil = _aesCipherUtil;
loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
log.info("登录成功");
}
//获取服务端时间-本地时间的差值
private static long getDt() {
long localTs = System.currentTimeMillis();
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/time")) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
long serverTs = Long.parseLong(res);
return serverTs - localTs;
}
private static AesCipherUtil login() {
long dt = getDt();
AesCipherUtil aesCipherUtil = new AesCipherUtil(StartSc.config.clientId, System.currentTimeMillis() + dt);
String loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/login?c="
+ URLEncoder.encode(loginCode, StandardCharsets.UTF_8))) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
if ("1".equals(res)) {
return aesCipherUtil;
} else {
log.warn("登录失败 " + res);
return null;
}
}
public static void main(String[] args) throws Exception {
for (ScConfig.Forward forward : config.forwards) {
new ClientPort(forward.localPort, (_clientPort, channelHandlerContext) -> {
/* 1、用户发起连接,ClientPort收到连接信息后向ServerPort发起连接请求,ServerPort返回一个唯一的sessionId; */
//去服务端拿sessionId
int sessionId;
try {
sessionId = ClientSessionService.initServerSession(forward.remoteHost, forward.remotePort);
log.info("新会话建立 {} {} --> {} --> {}:{}",
sessionId, channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
} catch (Exception e) {
log.info("建立会话异常,主动关闭 {} --> {} --> {}:{}",
channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
channelHandlerContext.close();
return;
}
/* 2、ClientPort根据sessionId新建一个ClientSession,ServerPort根据sessionId新建一个ServerSession;*/ | package org.wowtools.hppt.sc;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSc {
public static final ScConfig config;
public static final AesCipherUtil aesCipherUtil;
public static final String loginCode;
static {
Configurator.reconfigure(new File(ResourcesReader.getRootPath(StartSc.class) + "/log4j2.xml").toURI());
try {
config = Constant.ymlMapper.readValue(ResourcesReader.readStr(StartSc.class, "sc.yml"), ScConfig.class);
} catch (Exception e) {
throw new RuntimeException("读取配置文件异常", e);
}
AesCipherUtil _aesCipherUtil = login();
if (null == _aesCipherUtil) {
//排除整点附近登录失败的情况
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
_aesCipherUtil = login();
}
if (null == _aesCipherUtil) {
throw new RuntimeException("登录失败");
}
aesCipherUtil = _aesCipherUtil;
loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
log.info("登录成功");
}
//获取服务端时间-本地时间的差值
private static long getDt() {
long localTs = System.currentTimeMillis();
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/time")) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
long serverTs = Long.parseLong(res);
return serverTs - localTs;
}
private static AesCipherUtil login() {
long dt = getDt();
AesCipherUtil aesCipherUtil = new AesCipherUtil(StartSc.config.clientId, System.currentTimeMillis() + dt);
String loginCode = BytesUtil.bytes2base64(aesCipherUtil.encryptor.encrypt(StartSc.config.clientId.getBytes(StandardCharsets.UTF_8)));
String res;
try (Response response = HttpUtil.doPost(StartSc.config.serverUrl + "/login?c="
+ URLEncoder.encode(loginCode, StandardCharsets.UTF_8))) {
assert response.body() != null;
res = response.body().string();
} catch (Exception e) {
throw new RuntimeException("获取服务器时间异常", e);
}
if ("1".equals(res)) {
return aesCipherUtil;
} else {
log.warn("登录失败 " + res);
return null;
}
}
public static void main(String[] args) throws Exception {
for (ScConfig.Forward forward : config.forwards) {
new ClientPort(forward.localPort, (_clientPort, channelHandlerContext) -> {
/* 1、用户发起连接,ClientPort收到连接信息后向ServerPort发起连接请求,ServerPort返回一个唯一的sessionId; */
//去服务端拿sessionId
int sessionId;
try {
sessionId = ClientSessionService.initServerSession(forward.remoteHost, forward.remotePort);
log.info("新会话建立 {} {} --> {} --> {}:{}",
sessionId, channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
} catch (Exception e) {
log.info("建立会话异常,主动关闭 {} --> {} --> {}:{}",
channelHandlerContext.channel().remoteAddress(),
forward.localPort,
forward.remoteHost, forward.remotePort);
channelHandlerContext.close();
return;
}
/* 2、ClientPort根据sessionId新建一个ClientSession,ServerPort根据sessionId新建一个ServerSession;*/ | ClientSession clientSession = ClientSessionManager.createClientSession(sessionId, _clientPort, channelHandlerContext); | 6 | 2023-12-22 14:14:27+00:00 | 12k |
3arthqu4ke/phobot | src/main/java/me/earth/phobot/PhobotPlugin.java | [
{
"identifier": "GotoCommand",
"path": "src/main/java/me/earth/phobot/commands/GotoCommand.java",
"snippet": "public class GotoCommand extends AbstractPhobotCommand {\n public GotoCommand(Phobot phobot) {\n super(\"goto\", \"Go to the specified location.\", phobot);\n }\n\n @Override\n ... | import me.earth.phobot.commands.GotoCommand;
import me.earth.phobot.commands.KitCommand;
import me.earth.phobot.commands.TeleportCommand;
import me.earth.phobot.holes.HoleManager;
import me.earth.phobot.modules.client.*;
import me.earth.phobot.modules.client.anticheat.AntiCheat;
import me.earth.phobot.modules.combat.*;
import me.earth.phobot.modules.combat.autocrystal.AutoCrystal;
import me.earth.phobot.modules.misc.*;
import me.earth.phobot.modules.movement.*;
import me.earth.phobot.pathfinder.Pathfinder;
import me.earth.phobot.pathfinder.algorithm.AlgorithmRenderer;
import me.earth.phobot.pathfinder.mesh.NavigationMeshManager;
import me.earth.phobot.services.*;
import me.earth.phobot.services.inventory.InventoryService;
import me.earth.phobot.util.collections.XZMap;
import me.earth.pingbypass.PingBypass;
import me.earth.pingbypass.api.event.api.Subscriber;
import me.earth.pingbypass.api.plugin.impl.AbstractUnloadablePlugin;
import me.earth.pingbypass.api.plugin.impl.PluginUnloadingService;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger; | 7,402 | package me.earth.phobot;
@SuppressWarnings("unused")
public class PhobotPlugin extends AbstractUnloadablePlugin {
private Phobot phobot;
@Override
public void load(PingBypass pingBypass, PluginUnloadingService unloadingService) {
ExecutorService executor = getExecutorService();
Phobot phobot = initalizePhobot(pingBypass, executor, unloadingService);
registerCommands(pingBypass, phobot, unloadingService);
registerModules(pingBypass, phobot, unloadingService);
unloadingService.runOnUnload(executor::shutdown);
PhobotApi.setPhobot(phobot);
this.phobot = phobot;
}
@Override
public void unload() {
super.unload();
if (Objects.equals(PhobotApi.getPhobot(), phobot)) {
if (phobot != null) {
phobot.getInventoryService().releasePlayerUpdateLock();
}
PhobotApi.setPhobot(null);
this.phobot = null;
}
}
private Phobot initalizePhobot(PingBypass pingBypass, ExecutorService executor, PluginUnloadingService unloadingService) {
WorldVersionService worldVersionService = subscribe(unloadingService, new WorldVersionService());
MovementService movementService = new MovementService();
Holes holes = new Holes(pingBypass, executor);
unloadingService.registerModule(holes);
HoleManager holeManager = subscribe(unloadingService, new HoleManager(holes, new ConcurrentHashMap<>()));
new HolesRenderListener(holeManager, holes).getListeners().forEach(holes::listen);
ProtectionCacheService protectionCacheService = subscribe(unloadingService, new ProtectionCacheService(pingBypass.getMinecraft()));
AttackService attackService = subscribe(unloadingService, new AttackService(pingBypass.getMinecraft()));
TotemPopService totemPopService = subscribe(unloadingService, new TotemPopService(pingBypass.getMinecraft()));
DamageService damageService = subscribe(unloadingService, new DamageService(protectionCacheService, pingBypass.getMinecraft()));
Pathfinding pathfinding = new Pathfinding(pingBypass, executor);
unloadingService.registerModule(pathfinding);
NavigationMeshManager navigationMeshManager = subscribe(unloadingService,
new NavigationMeshManager(pathfinding, movementService.getMovement(), new ConcurrentHashMap<>(), new XZMap<>(new ConcurrentHashMap<>())));
pathfinding.listen(new GraphDebugRenderer(navigationMeshManager, pathfinding, pingBypass.getMinecraft()));
| package me.earth.phobot;
@SuppressWarnings("unused")
public class PhobotPlugin extends AbstractUnloadablePlugin {
private Phobot phobot;
@Override
public void load(PingBypass pingBypass, PluginUnloadingService unloadingService) {
ExecutorService executor = getExecutorService();
Phobot phobot = initalizePhobot(pingBypass, executor, unloadingService);
registerCommands(pingBypass, phobot, unloadingService);
registerModules(pingBypass, phobot, unloadingService);
unloadingService.runOnUnload(executor::shutdown);
PhobotApi.setPhobot(phobot);
this.phobot = phobot;
}
@Override
public void unload() {
super.unload();
if (Objects.equals(PhobotApi.getPhobot(), phobot)) {
if (phobot != null) {
phobot.getInventoryService().releasePlayerUpdateLock();
}
PhobotApi.setPhobot(null);
this.phobot = null;
}
}
private Phobot initalizePhobot(PingBypass pingBypass, ExecutorService executor, PluginUnloadingService unloadingService) {
WorldVersionService worldVersionService = subscribe(unloadingService, new WorldVersionService());
MovementService movementService = new MovementService();
Holes holes = new Holes(pingBypass, executor);
unloadingService.registerModule(holes);
HoleManager holeManager = subscribe(unloadingService, new HoleManager(holes, new ConcurrentHashMap<>()));
new HolesRenderListener(holeManager, holes).getListeners().forEach(holes::listen);
ProtectionCacheService protectionCacheService = subscribe(unloadingService, new ProtectionCacheService(pingBypass.getMinecraft()));
AttackService attackService = subscribe(unloadingService, new AttackService(pingBypass.getMinecraft()));
TotemPopService totemPopService = subscribe(unloadingService, new TotemPopService(pingBypass.getMinecraft()));
DamageService damageService = subscribe(unloadingService, new DamageService(protectionCacheService, pingBypass.getMinecraft()));
Pathfinding pathfinding = new Pathfinding(pingBypass, executor);
unloadingService.registerModule(pathfinding);
NavigationMeshManager navigationMeshManager = subscribe(unloadingService,
new NavigationMeshManager(pathfinding, movementService.getMovement(), new ConcurrentHashMap<>(), new XZMap<>(new ConcurrentHashMap<>())));
pathfinding.listen(new GraphDebugRenderer(navigationMeshManager, pathfinding, pingBypass.getMinecraft()));
| Pathfinder pathfinder = subscribe(unloadingService, new Pathfinder(pingBypass, navigationMeshManager, movementService, executor)); | 6 | 2023-12-22 14:32:16+00:00 | 12k |
ArmanKhanDev/FakepixelDungeonHelper | build/sources/main/java/io/github/quantizr/core/AutoRoom.java | [
{
"identifier": "DungeonRooms",
"path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java",
"snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"... | import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.github.quantizr.DungeonRooms;
import io.github.quantizr.handlers.TextRenderer;
import io.github.quantizr.utils.Utils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.BlockPos;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors; | 8,166 | /*
Copyright 2021 Quantizr(_risk)
This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>)
DRM 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.
DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>.
*/
package io.github.quantizr.core;
public class AutoRoom {
Minecraft mc = Minecraft.getMinecraft();
static int tickAmount = 1;
public static List<String> autoTextOutput = null;
public static boolean chatToggled = false;
public static boolean guiToggled = true;
public static boolean coordToggled = false;
public static String lastRoomHash = null;
public static JsonObject lastRoomJson;
public static String lastRoomName = null;
private static boolean newRoom = false;
public static int worldLoad = 0;
public static int scaleX = 50;
public static int scaleY = 5;
private final Executor executor = Executors.newFixedThreadPool(5);
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (event.phase != TickEvent.Phase.START) return;
World world = mc.theWorld;
EntityPlayerSP player = mc.thePlayer;
tickAmount++;
if (worldLoad < 200) { //10 seconds
worldLoad++;
}
// Checks every 1.5 seconds | /*
Copyright 2021 Quantizr(_risk)
This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>)
DRM 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.
DRM 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 DRM. If not, see <https://www.gnu.org/licenses/>.
*/
package io.github.quantizr.core;
public class AutoRoom {
Minecraft mc = Minecraft.getMinecraft();
static int tickAmount = 1;
public static List<String> autoTextOutput = null;
public static boolean chatToggled = false;
public static boolean guiToggled = true;
public static boolean coordToggled = false;
public static String lastRoomHash = null;
public static JsonObject lastRoomJson;
public static String lastRoomName = null;
private static boolean newRoom = false;
public static int worldLoad = 0;
public static int scaleX = 50;
public static int scaleY = 5;
private final Executor executor = Executors.newFixedThreadPool(5);
@SubscribeEvent
public void onTick(TickEvent.ClientTickEvent event) {
if (event.phase != TickEvent.Phase.START) return;
World world = mc.theWorld;
EntityPlayerSP player = mc.thePlayer;
tickAmount++;
if (worldLoad < 200) { //10 seconds
worldLoad++;
}
// Checks every 1.5 seconds | if (tickAmount % 30 == 0 && Utils.inDungeons && worldLoad == 200) { | 2 | 2023-12-22 04:44:39+00:00 | 12k |
HChenX/ClipboardList | app/src/main/java/com/hchen/clipboardlist/HookMain.java | [
{
"identifier": "ClipboardList",
"path": "app/src/main/java/com/hchen/clipboardlist/clipboard/ClipboardList.java",
"snippet": "public class ClipboardList extends Hook {\n public static ArrayList<?> lastArray = new ArrayList<>();\n\n public static String lastFilePath;\n public ArrayList<?> mClip... | import android.content.Context;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import com.hchen.clipboardlist.clipboard.ClipboardList;
import com.hchen.clipboardlist.hook.Hook;
import com.hchen.clipboardlist.hook.Log;
import com.hchen.clipboardlist.unlockIme.UnlockIme;
import java.util.ArrayList;
import java.util.List;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam; | 10,110 | package com.hchen.clipboardlist;
public class HookMain implements IXposedHookLoadPackage {
public static List<String> mAppsUsingInputMethod = new ArrayList<>();
@Override
public void handleLoadPackage(LoadPackageParam lpparam) {
if (mAppsUsingInputMethod.isEmpty()) {
mAppsUsingInputMethod = getAppsUsingInputMethod(Hook.findContext());
}
String pkg = lpparam.packageName;
initHook(new ClipboardList(), lpparam, isInputMethod(pkg)); | package com.hchen.clipboardlist;
public class HookMain implements IXposedHookLoadPackage {
public static List<String> mAppsUsingInputMethod = new ArrayList<>();
@Override
public void handleLoadPackage(LoadPackageParam lpparam) {
if (mAppsUsingInputMethod.isEmpty()) {
mAppsUsingInputMethod = getAppsUsingInputMethod(Hook.findContext());
}
String pkg = lpparam.packageName;
initHook(new ClipboardList(), lpparam, isInputMethod(pkg)); | initHook(new UnlockIme(), lpparam, isInputMethod(pkg)); | 3 | 2023-12-22 15:07:33+00:00 | 12k |
danielfeitopin/MUNICS-SAPP-P1 | src/main/java/es/storeapp/web/controller/OrderController.java | [
{
"identifier": "CreditCard",
"path": "src/main/java/es/storeapp/business/entities/CreditCard.java",
"snippet": "@Embeddable\npublic class CreditCard implements Serializable {\n\n private String card;\n \n private Integer cvv;\n \n private Integer expirationMonth;\n \n private Integ... | import es.storeapp.business.entities.CreditCard;
import es.storeapp.business.entities.Order;
import es.storeapp.business.entities.Product;
import es.storeapp.business.entities.User;
import es.storeapp.business.exceptions.InstanceNotFoundException;
import es.storeapp.business.exceptions.InvalidStateException;
import es.storeapp.business.services.OrderService;
import es.storeapp.common.Constants;
import es.storeapp.web.exceptions.ErrorHandlingUtils;
import es.storeapp.web.forms.OrderForm;
import es.storeapp.web.forms.PaymentForm;
import es.storeapp.web.session.ShoppingCart;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import es.storeapp.common.EscapingLoggerWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; | 7,659 | package es.storeapp.web.controller;
@Controller
public class OrderController {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(OrderController.class);
@Autowired
private OrderService orderService;
@Autowired
private MessageSource messageSource;
@Autowired | package es.storeapp.web.controller;
@Controller
public class OrderController {
private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(OrderController.class);
@Autowired
private OrderService orderService;
@Autowired
private MessageSource messageSource;
@Autowired | ErrorHandlingUtils errorHandlingUtils; | 8 | 2023-12-24 19:24:49+00:00 | 12k |
RoderickQiu/SUSTech_CSE_Projects | CS109_2022_Fall/Chess/Main.java | [
{
"identifier": "ChessColor",
"path": "CS109_2022_Fall/Chess/model/ChessColor.java",
"snippet": "public enum ChessColor {\r\n BLACK(\"BLACK\", Color.decode(\"#251f1e\")), RED(\"RED\", Color.decode(\"#e83505\")), NONE(\"No Player\", Color.WHITE);\r\n\r\n private final String name;\r\n private fi... | import Chess.model.ChessColor;
import Chess.utils.FileUtils;
import Chess.view.ChessGameFrame;
import Chess.view.RankFrame;
import Chess.view.StartFrame;
import com.formdev.flatlaf.FlatLightLaf;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.swing.*;
import java.awt.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static Chess.utils.GeneralUtils.log;
| 7,322 | package Chess;
public class Main {
private static ChessGameFrame gameFrame = null;
private static StartFrame startFrame = null;
public static Font titleFont, sansFont, serifFont;
public static String theme = "像素", currentUser = "";
public static final String[] themeList = {"典雅", "激情", "像素"};
| package Chess;
public class Main {
private static ChessGameFrame gameFrame = null;
private static StartFrame startFrame = null;
public static Font titleFont, sansFont, serifFont;
public static String theme = "像素", currentUser = "";
public static final String[] themeList = {"典雅", "激情", "像素"};
| private static RankFrame rankFrame = null;
| 3 | 2023-12-31 05:50:13+00:00 | 12k |
psobiech/opengr8on | vclu/src/main/java/pl/psobiech/opengr8on/vclu/Main.java | [
{
"identifier": "CLUFiles",
"path": "lib/src/main/java/pl/psobiech/opengr8on/client/CLUFiles.java",
"snippet": "public enum CLUFiles {\n USER_LUA(\"a\", \"USER.LUA\"),\n OM_LUA(\"a\", \"OM.LUA\"),\n MAIN_LUA(\"a\", \"MAIN.LUA\"),\n //\n EMERGNCY_LUA(\"a\", \"EMERGNCY.LUA\"),\n //\n ... | import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto;
import pl.psobiech.opengr8on.util.ObjectMapperFactory;
import java.net.Inet4Address;
import java.nio.file.Path;
import java.nio.file.Paths;
import pl.psobiech.opengr8on.client.CLUFiles;
import pl.psobiech.opengr8on.client.CipherKey;
import pl.psobiech.opengr8on.client.device.CLUDevice;
import pl.psobiech.opengr8on.client.device.CLUDeviceConfig;
import pl.psobiech.opengr8on.client.device.CipherTypeEnum;
import pl.psobiech.opengr8on.exceptions.UnexpectedException;
import pl.psobiech.opengr8on.util.FileUtil;
import pl.psobiech.opengr8on.util.IPv4AddressUtil; | 10,267 | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.vclu;
public class Main {
static {
System.setProperty("jdk.virtualThreadScheduler.parallelism", "8");
System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "8");
System.setProperty("jdk.virtualThreadScheduler.minRunnable", "2");
System.setProperty("jdk.tracePinnedThreads", "full/short");
}
private Main() {
// NOP
}
public static void main(String[] args) throws Exception {
final Path rootDirectory = Paths.get("./runtime/root").toAbsolutePath();
final Path aDriveDirectory = rootDirectory.resolve("a"); | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.vclu;
public class Main {
static {
System.setProperty("jdk.virtualThreadScheduler.parallelism", "8");
System.setProperty("jdk.virtualThreadScheduler.maxPoolSize", "8");
System.setProperty("jdk.virtualThreadScheduler.minRunnable", "2");
System.setProperty("jdk.tracePinnedThreads", "full/short");
}
private Main() {
// NOP
}
public static void main(String[] args) throws Exception {
final Path rootDirectory = Paths.get("./runtime/root").toAbsolutePath();
final Path aDriveDirectory = rootDirectory.resolve("a"); | FileUtil.mkdir(aDriveDirectory); | 6 | 2023-12-23 09:56:14+00:00 | 12k |
Pigmice2733/frc-2024 | src/main/java/frc/robot/subsystems/Vision.java | [
{
"identifier": "Constants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public final class Constants {\n public static final ShuffleboardTab DRIVER_TAB = Shuffleboard.getTab(\"Driver\");\n public static final ShuffleboardTab SWERVE_TAB = Shuffleboard.getTab(\"Drivetrain\");\n ... | import com.pigmice.frc.lib.shuffleboard_helper.ShuffleboardHelper;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.wpilibj2.command.SubsystemBase;
import frc.robot.Constants;
import frc.robot.LimelightHelpers;
import frc.robot.Constants.VisionConfig;
import frc.robot.LimelightHelpers.LimelightResults;
import frc.robot.LimelightHelpers.LimelightTarget_Fiducial;
import frc.robot.LimelightHelpers.Results; | 10,090 | package frc.robot.subsystems;
public class Vision extends SubsystemBase {
private static String camName = VisionConfig.CAM_NAME;
private Results targetingResults;
private LimelightTarget_Fiducial bestTarget;
private boolean hasTarget;
public Vision() { | package frc.robot.subsystems;
public class Vision extends SubsystemBase {
private static String camName = VisionConfig.CAM_NAME;
private Results targetingResults;
private LimelightTarget_Fiducial bestTarget;
private boolean hasTarget;
public Vision() { | ShuffleboardHelper.addOutput("Target X", Constants.VISION_TAB, | 0 | 2023-12-30 06:06:45+00:00 | 12k |
Deenu143/GradleParser | app/src/main/java/org/deenu/gradle/script/GradleScript.java | [
{
"identifier": "Dependency",
"path": "app/src/main/java/org/deenu/gradle/models/Dependency.java",
"snippet": "public class Dependency {\n\n private String configuration;\n private String group;\n private String name;\n private String version;\n\n public Dependency(String group, String name, String... | import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.List;
import org.codehaus.groovy.ast.ASTNode;
import org.codehaus.groovy.ast.GroovyCodeVisitor;
import org.codehaus.groovy.ast.builder.AstBuilder;
import org.deenu.gradle.models.Dependency;
import org.deenu.gradle.models.FlatDir;
import org.deenu.gradle.models.Include;
import org.deenu.gradle.models.Plugin;
import org.deenu.gradle.models.Repository;
import org.deenu.gradle.parser.exception.UnsupportedFileException;
import org.deenu.gradle.script.visitors.GradleScriptVisitor; | 7,945 | package org.deenu.gradle.script;
public class GradleScript {
private File gradleFile;
private AstBuilder astBuilder;
private List<ASTNode> aSTNodes;
private String scriptContents;
private GradleScriptVisitor gradleScriptVisitor;
public GradleScript(File gradleFile) throws Exception, FileNotFoundException {
this.gradleFile = gradleFile;
if (gradleFile == null || !gradleFile.exists()) {
throw new FileNotFoundException("Failed to get '.gradle' or '.gradle.kts' file.");
} else if (gradleFile != null) {
String fileName = gradleFile.getName();
String[] fileExtensions = new String[] {".gradle", ".gradle.kts"};
if (fileName != null) {
if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) { | package org.deenu.gradle.script;
public class GradleScript {
private File gradleFile;
private AstBuilder astBuilder;
private List<ASTNode> aSTNodes;
private String scriptContents;
private GradleScriptVisitor gradleScriptVisitor;
public GradleScript(File gradleFile) throws Exception, FileNotFoundException {
this.gradleFile = gradleFile;
if (gradleFile == null || !gradleFile.exists()) {
throw new FileNotFoundException("Failed to get '.gradle' or '.gradle.kts' file.");
} else if (gradleFile != null) {
String fileName = gradleFile.getName();
String[] fileExtensions = new String[] {".gradle", ".gradle.kts"};
if (fileName != null) {
if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) { | throw new UnsupportedFileException("Unsupported file: " + gradleFile.getAbsolutePath()); | 5 | 2023-12-27 10:10:31+00:00 | 12k |
Prototik/TheConfigLib | common/src/main/java/dev/tcl/gui/controllers/ColorController.java | [
{
"identifier": "Option",
"path": "common/src/main/java/dev/tcl/api/Option.java",
"snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option... | import com.google.common.collect.ImmutableList;
import dev.tcl.api.Option;
import dev.tcl.api.utils.Dimension;
import dev.tcl.api.utils.MutableDimension;
import dev.tcl.gui.controllers.string.IStringController;
import dev.tcl.gui.controllers.string.StringControllerElement;
import dev.tcl.gui.AbstractWidget;
import dev.tcl.gui.TCLScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import java.awt.*;
import java.util.List; | 9,922 | package dev.tcl.gui.controllers;
/**
* A color controller that uses a hex color field as input.
*/
public class ColorController implements IStringController<Color> {
private final Option<Color> option;
private final boolean allowAlpha;
/**
* Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false
*
* @param option bound option
*/
public ColorController(Option<Color> option) {
this(option, false);
}
/**
* Constructs a color controller
*
* @param option bound option
* @param allowAlpha allows the color input to accept alpha values
*/
public ColorController(Option<Color> option, boolean allowAlpha) {
this.option = option;
this.allowAlpha = allowAlpha;
}
/**
* {@inheritDoc}
*/
@Override
public Option<Color> option() {
return option;
}
public boolean allowAlpha() {
return allowAlpha;
}
@Override
public String getString() {
return formatValue().getString();
}
@Override
public Component formatValue() {
MutableComponent text = Component.literal("#");
text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED));
text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN));
text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.BLUE));
if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha()));
return text;
}
private String toHex(int value) {
String hex = Integer.toString(value, 16).toUpperCase();
if (hex.length() == 1)
hex = "0" + hex;
return hex;
}
@Override
public void setFromString(String value) {
if (value.startsWith("#"))
value = value.substring(1);
int red = Integer.parseInt(value.substring(0, 2), 16);
int green = Integer.parseInt(value.substring(2, 4), 16);
int blue = Integer.parseInt(value.substring(4, 6), 16);
if (allowAlpha()) {
int alpha = Integer.parseInt(value.substring(6, 8), 16);
option().requestSet(new Color(red, green, blue, alpha));
} else {
option().requestSet(new Color(red, green, blue));
}
}
@Override | package dev.tcl.gui.controllers;
/**
* A color controller that uses a hex color field as input.
*/
public class ColorController implements IStringController<Color> {
private final Option<Color> option;
private final boolean allowAlpha;
/**
* Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false
*
* @param option bound option
*/
public ColorController(Option<Color> option) {
this(option, false);
}
/**
* Constructs a color controller
*
* @param option bound option
* @param allowAlpha allows the color input to accept alpha values
*/
public ColorController(Option<Color> option, boolean allowAlpha) {
this.option = option;
this.allowAlpha = allowAlpha;
}
/**
* {@inheritDoc}
*/
@Override
public Option<Color> option() {
return option;
}
public boolean allowAlpha() {
return allowAlpha;
}
@Override
public String getString() {
return formatValue().getString();
}
@Override
public Component formatValue() {
MutableComponent text = Component.literal("#");
text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED));
text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN));
text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.BLUE));
if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha()));
return text;
}
private String toHex(int value) {
String hex = Integer.toString(value, 16).toUpperCase();
if (hex.length() == 1)
hex = "0" + hex;
return hex;
}
@Override
public void setFromString(String value) {
if (value.startsWith("#"))
value = value.substring(1);
int red = Integer.parseInt(value.substring(0, 2), 16);
int green = Integer.parseInt(value.substring(2, 4), 16);
int blue = Integer.parseInt(value.substring(4, 6), 16);
if (allowAlpha()) {
int alpha = Integer.parseInt(value.substring(6, 8), 16);
option().requestSet(new Color(red, green, blue, alpha));
} else {
option().requestSet(new Color(red, green, blue));
}
}
@Override | public AbstractWidget provideWidget(TCLScreen screen, dev.tcl.api.utils.Dimension<Integer> widgetDimension) { | 1 | 2023-12-25 14:48:27+00:00 | 12k |
Man2Dev/N-Queen | lib/jfreechart-1.0.19/tests/org/jfree/chart/renderer/xy/HighLowRendererTest.java | [
{
"identifier": "TestUtilities",
"path": "lib/jfreechart-1.0.19/tests/org/jfree/chart/TestUtilities.java",
"snippet": "public class TestUtilities {\n\n /**\n * Returns <code>true</code> if the collections contains any object that\n * is an instance of the specified class, and <code>false</cod... | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.awt.Color;
import java.util.Date;
import org.jfree.chart.TestUtilities;
import org.jfree.data.Range;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.OHLCDataItem;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.util.PublicCloneable;
import org.junit.Test; | 8,941 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ------------------------
* HighLowRendererTest.java
* ------------------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 22-Oct-2003 : Added hashCode test (DG);
* 01-Nov-2005 : Added tests for new fields (DG);
* 17-Aug-2006 : Added testFindRangeBounds() method (DG);
* 22-Apr-2008 : Added testPublicCloneable (DG);
* 29-Apr-2008 : Extended testEquals() for new field (DG);
*
*/
package org.jfree.chart.renderer.xy;
/**
* Tests for the {@link HighLowRenderer} class.
*/
public class HighLowRendererTest {
/**
* Check that the equals() method distinguishes all fields.
*/
@Test
public void testEquals() {
HighLowRenderer r1 = new HighLowRenderer();
HighLowRenderer r2 = new HighLowRenderer();
assertEquals(r1, r2);
// drawOpenTicks
r1.setDrawOpenTicks(false);
assertFalse(r1.equals(r2));
r2.setDrawOpenTicks(false);
assertTrue(r1.equals(r2));
// drawCloseTicks
r1.setDrawCloseTicks(false);
assertFalse(r1.equals(r2));
r2.setDrawCloseTicks(false);
assertTrue(r1.equals(r2));
// openTickPaint
r1.setOpenTickPaint(Color.red);
assertFalse(r1.equals(r2));
r2.setOpenTickPaint(Color.red);
assertTrue(r1.equals(r2));
// closeTickPaint
r1.setCloseTickPaint(Color.blue);
assertFalse(r1.equals(r2));
r2.setCloseTickPaint(Color.blue);
assertTrue(r1.equals(r2));
// tickLength
r1.setTickLength(99.9);
assertFalse(r1.equals(r2));
r2.setTickLength(99.9);
assertTrue(r1.equals(r2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashcode() {
HighLowRenderer r1 = new HighLowRenderer();
HighLowRenderer r2 = new HighLowRenderer();
assertTrue(r1.equals(r2));
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
HighLowRenderer r1 = new HighLowRenderer();
r1.setCloseTickPaint(Color.green);
HighLowRenderer r2 = (HighLowRenderer) r1.clone();
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
/**
* Verify that this class implements {@link PublicCloneable}.
*/
@Test
public void testPublicCloneable() {
HighLowRenderer r1 = new HighLowRenderer();
assertTrue(r1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
HighLowRenderer r1 = new HighLowRenderer();
r1.setCloseTickPaint(Color.green);
HighLowRenderer r2 = (HighLowRenderer) TestUtilities.serialised(r1);
assertEquals(r1, r2);
}
/**
* Some checks for the findRangeBounds() method.
*/
@Test
public void testFindRangeBounds() {
HighLowRenderer renderer = new HighLowRenderer();
OHLCDataItem item1 = new OHLCDataItem(new Date(1L), 2.0, 4.0, 1.0, 3.0,
100); | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ------------------------
* HighLowRendererTest.java
* ------------------------
* (C) Copyright 2003-2013, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 25-Mar-2003 : Version 1 (DG);
* 22-Oct-2003 : Added hashCode test (DG);
* 01-Nov-2005 : Added tests for new fields (DG);
* 17-Aug-2006 : Added testFindRangeBounds() method (DG);
* 22-Apr-2008 : Added testPublicCloneable (DG);
* 29-Apr-2008 : Extended testEquals() for new field (DG);
*
*/
package org.jfree.chart.renderer.xy;
/**
* Tests for the {@link HighLowRenderer} class.
*/
public class HighLowRendererTest {
/**
* Check that the equals() method distinguishes all fields.
*/
@Test
public void testEquals() {
HighLowRenderer r1 = new HighLowRenderer();
HighLowRenderer r2 = new HighLowRenderer();
assertEquals(r1, r2);
// drawOpenTicks
r1.setDrawOpenTicks(false);
assertFalse(r1.equals(r2));
r2.setDrawOpenTicks(false);
assertTrue(r1.equals(r2));
// drawCloseTicks
r1.setDrawCloseTicks(false);
assertFalse(r1.equals(r2));
r2.setDrawCloseTicks(false);
assertTrue(r1.equals(r2));
// openTickPaint
r1.setOpenTickPaint(Color.red);
assertFalse(r1.equals(r2));
r2.setOpenTickPaint(Color.red);
assertTrue(r1.equals(r2));
// closeTickPaint
r1.setCloseTickPaint(Color.blue);
assertFalse(r1.equals(r2));
r2.setCloseTickPaint(Color.blue);
assertTrue(r1.equals(r2));
// tickLength
r1.setTickLength(99.9);
assertFalse(r1.equals(r2));
r2.setTickLength(99.9);
assertTrue(r1.equals(r2));
}
/**
* Two objects that are equal are required to return the same hashCode.
*/
@Test
public void testHashcode() {
HighLowRenderer r1 = new HighLowRenderer();
HighLowRenderer r2 = new HighLowRenderer();
assertTrue(r1.equals(r2));
int h1 = r1.hashCode();
int h2 = r2.hashCode();
assertEquals(h1, h2);
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
HighLowRenderer r1 = new HighLowRenderer();
r1.setCloseTickPaint(Color.green);
HighLowRenderer r2 = (HighLowRenderer) r1.clone();
assertTrue(r1 != r2);
assertTrue(r1.getClass() == r2.getClass());
assertTrue(r1.equals(r2));
}
/**
* Verify that this class implements {@link PublicCloneable}.
*/
@Test
public void testPublicCloneable() {
HighLowRenderer r1 = new HighLowRenderer();
assertTrue(r1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
HighLowRenderer r1 = new HighLowRenderer();
r1.setCloseTickPaint(Color.green);
HighLowRenderer r2 = (HighLowRenderer) TestUtilities.serialised(r1);
assertEquals(r1, r2);
}
/**
* Some checks for the findRangeBounds() method.
*/
@Test
public void testFindRangeBounds() {
HighLowRenderer renderer = new HighLowRenderer();
OHLCDataItem item1 = new OHLCDataItem(new Date(1L), 2.0, 4.0, 1.0, 3.0,
100); | OHLCDataset dataset = new DefaultOHLCDataset("S1", | 2 | 2023-12-24 12:36:47+00:00 | 12k |
CodecNomad/MayOBees | src/main/java/com/github/may2beez/mayobees/module/impl/other/Failsafes.java | [
{
"identifier": "MayOBeesConfig",
"path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java",
"snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatica... | import com.github.may2beez.mayobees.config.MayOBeesConfig;
import com.github.may2beez.mayobees.event.PacketEvent;
import com.github.may2beez.mayobees.module.IModuleActive;
import com.github.may2beez.mayobees.module.ModuleManager;
import com.github.may2beez.mayobees.util.LogUtils;
import com.github.may2beez.mayobees.util.helper.AudioManager;
import net.minecraft.client.Minecraft;
import net.minecraft.network.play.server.S08PacketPlayerPosLook;
import net.minecraftforge.event.world.WorldEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; | 9,416 | package com.github.may2beez.mayobees.module.impl.other;
public class Failsafes {
private static Failsafes instance;
public static Failsafes getInstance() {
if (instance == null) {
instance = new Failsafes();
}
return instance;
}
private static final Minecraft mc = Minecraft.getMinecraft();
private static final String[] teleportItems = new String[] {"Void", "Hyperion", "Aspect"};
@SubscribeEvent
public void onWorldChange(WorldEvent.Unload event) {
if (!MayOBeesConfig.stopMacrosOnWorldChange) return;
| package com.github.may2beez.mayobees.module.impl.other;
public class Failsafes {
private static Failsafes instance;
public static Failsafes getInstance() {
if (instance == null) {
instance = new Failsafes();
}
return instance;
}
private static final Minecraft mc = Minecraft.getMinecraft();
private static final String[] teleportItems = new String[] {"Void", "Hyperion", "Aspect"};
@SubscribeEvent
public void onWorldChange(WorldEvent.Unload event) {
if (!MayOBeesConfig.stopMacrosOnWorldChange) return;
| List<IModuleActive> activeModules = ModuleManager.getInstance().getModules().stream().filter(mod -> mod instanceof IModuleActive && mod.isRunning()).map(mod -> (IModuleActive) mod).collect(Collectors.toList()); | 2 | 2023-12-24 15:39:11+00:00 | 12k |
viceice/verbrauchsapp | app/src/main/java/de/anipe/verbrauchsapp/GDriveStoreActivity.java | [
{
"identifier": "ConsumptionDataSource",
"path": "app/src/main/java/de/anipe/verbrauchsapp/db/ConsumptionDataSource.java",
"snippet": "public class ConsumptionDataSource implements Serializable {\n\n\tprivate static ConsumptionDataSource dataSouce;\n\n\tprivate static final long serialVersionUID = 36801... | import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.DriveResource.MetadataResult;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.MetadataChangeSet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import de.anipe.verbrauchsapp.db.ConsumptionDataSource;
import de.anipe.verbrauchsapp.io.FileSystemAccessor;
import de.anipe.verbrauchsapp.io.GDriveAsyncTask;
import de.anipe.verbrauchsapp.io.XMLHandler;
import de.anipe.verbrauchsapp.objects.Car; | 8,656 | package de.anipe.verbrauchsapp;
public class GDriveStoreActivity extends GDriveBaseActivity {
private File outputFile;
private long carId;
private FileSystemAccessor accessor;
private ConsumptionDataSource dataSource;
private static final int REQUEST_CODE_CREATOR = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
carId = bundle.getLong("carid");
setContentView(R.layout.activity_gdrive_upload);
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
accessor = FileSystemAccessor.getInstance();
dataSource = ConsumptionDataSource.getInstance(this);
try {
dataSource.open();
} catch (SQLException e) {
Toast.makeText(GDriveStoreActivity.this,
"Fehler beim Öffnen der Datenbank!", Toast.LENGTH_LONG)
.show();
}
// Step 1: write to local XML file
writeXMLFileToLocalFileSystem();
if (outputFile == null) {
Log.e("GDriveStoreActivity", "Output file is null. Nothing to write to Google Drive. Aborting Activity.");
finish();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// @Override
// protected void onResume() {
// super.onResume();
//
// // Step 1: write to local XML file
// writeXMLFileToLocalFileSystem();
//
// // Step 2: upload to the cloud
// if (outputFile != null) {
// if (getGoogleApiClient() == null) {
// mGoogleApiClient = new GoogleApiClient.Builder(this)
// .addApi(Drive.API).addScope(Drive.SCOPE_FILE)
// .addScope(Drive.SCOPE_APPFOLDER)
// .addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this).build();
// }
// mGoogleApiClient.connect();
// } else {
// finish();
// }
// }
private void writeXMLFileToLocalFileSystem() {
Car car = dataSource.getCarForId(carId);
XMLHandler handler = new XMLHandler(null, car,
dataSource.getOverallConsumptionForCar(carId),
dataSource.getConsumptionCycles(carId));
try {
outputFile = accessor.writeXMLFileToStorage(this,
handler.createConsumptionDocument(),
MainActivity.STORAGE_DIR,
car.getBrand() + "_" + car.getType());
TextView xmlTv = findViewById(R.id.xmlExportValueLine);
xmlTv.setBackgroundColor(Color.GREEN);
xmlTv.setTextColor(Color.BLACK);
xmlTv.setText("OK");
} catch (Exception e) {
Toast.makeText(
GDriveStoreActivity.this,
"Fehler beim Schreiben der XML-Datei. Grund: "
+ e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
TextView xmlTv = findViewById(R.id.xmlExportValueLine);
xmlTv.setBackgroundColor(Color.RED);
xmlTv.setTextColor(Color.BLACK);
xmlTv.setText("FEHLER");
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.i("GDriveStoreActivity", "GoogleApiClient connected");
try {
new CreateFileAsyncTask(this).execute();
} catch (Exception e) {
Toast.makeText(
GDriveStoreActivity.this,
"Fehler beim Upload der XML-Datei. Grund: "
+ e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
TextView xmlTv = findViewById(R.id.cloudExportValueLine);
xmlTv.setBackgroundColor(Color.RED);
xmlTv.setTextColor(Color.BLACK);
xmlTv.setText("FEHLER");
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.e("GDriveStoreActivity", "GoogleApiClient connection failed: "
+ result.toString());
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_CREATOR);
} catch (SendIntentException e) {
Log.e("GDriveStoreActivity",
"Exception while starting resolution activity", e);
}
TextView cloudTv = findViewById(R.id.cloudExportValueLine);
cloudTv.setBackgroundColor(Color.RED);
cloudTv.setTextColor(Color.BLACK);
cloudTv.setText("FEHLER");
showMessage("Verbindungsaufbau zu Google Drive fehlgeschlagen!");
finish();
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private byte[] read(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
try (InputStream ios = new FileInputStream(file)) {
if (ios.read(buffer) == -1) {
throw new IOException(
"EOF reached while trying to read the whole file");
}
}
return buffer;
}
public class CreateFileAsyncTask extends | package de.anipe.verbrauchsapp;
public class GDriveStoreActivity extends GDriveBaseActivity {
private File outputFile;
private long carId;
private FileSystemAccessor accessor;
private ConsumptionDataSource dataSource;
private static final int REQUEST_CODE_CREATOR = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
carId = bundle.getLong("carid");
setContentView(R.layout.activity_gdrive_upload);
Toolbar myToolbar = findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
accessor = FileSystemAccessor.getInstance();
dataSource = ConsumptionDataSource.getInstance(this);
try {
dataSource.open();
} catch (SQLException e) {
Toast.makeText(GDriveStoreActivity.this,
"Fehler beim Öffnen der Datenbank!", Toast.LENGTH_LONG)
.show();
}
// Step 1: write to local XML file
writeXMLFileToLocalFileSystem();
if (outputFile == null) {
Log.e("GDriveStoreActivity", "Output file is null. Nothing to write to Google Drive. Aborting Activity.");
finish();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// @Override
// protected void onResume() {
// super.onResume();
//
// // Step 1: write to local XML file
// writeXMLFileToLocalFileSystem();
//
// // Step 2: upload to the cloud
// if (outputFile != null) {
// if (getGoogleApiClient() == null) {
// mGoogleApiClient = new GoogleApiClient.Builder(this)
// .addApi(Drive.API).addScope(Drive.SCOPE_FILE)
// .addScope(Drive.SCOPE_APPFOLDER)
// .addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this).build();
// }
// mGoogleApiClient.connect();
// } else {
// finish();
// }
// }
private void writeXMLFileToLocalFileSystem() {
Car car = dataSource.getCarForId(carId);
XMLHandler handler = new XMLHandler(null, car,
dataSource.getOverallConsumptionForCar(carId),
dataSource.getConsumptionCycles(carId));
try {
outputFile = accessor.writeXMLFileToStorage(this,
handler.createConsumptionDocument(),
MainActivity.STORAGE_DIR,
car.getBrand() + "_" + car.getType());
TextView xmlTv = findViewById(R.id.xmlExportValueLine);
xmlTv.setBackgroundColor(Color.GREEN);
xmlTv.setTextColor(Color.BLACK);
xmlTv.setText("OK");
} catch (Exception e) {
Toast.makeText(
GDriveStoreActivity.this,
"Fehler beim Schreiben der XML-Datei. Grund: "
+ e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
TextView xmlTv = findViewById(R.id.xmlExportValueLine);
xmlTv.setBackgroundColor(Color.RED);
xmlTv.setTextColor(Color.BLACK);
xmlTv.setText("FEHLER");
}
}
@Override
public void onConnected(Bundle connectionHint) {
Log.i("GDriveStoreActivity", "GoogleApiClient connected");
try {
new CreateFileAsyncTask(this).execute();
} catch (Exception e) {
Toast.makeText(
GDriveStoreActivity.this,
"Fehler beim Upload der XML-Datei. Grund: "
+ e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
TextView xmlTv = findViewById(R.id.cloudExportValueLine);
xmlTv.setBackgroundColor(Color.RED);
xmlTv.setTextColor(Color.BLACK);
xmlTv.setText("FEHLER");
}
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.e("GDriveStoreActivity", "GoogleApiClient connection failed: "
+ result.toString());
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_CREATOR);
} catch (SendIntentException e) {
Log.e("GDriveStoreActivity",
"Exception while starting resolution activity", e);
}
TextView cloudTv = findViewById(R.id.cloudExportValueLine);
cloudTv.setBackgroundColor(Color.RED);
cloudTv.setTextColor(Color.BLACK);
cloudTv.setText("FEHLER");
showMessage("Verbindungsaufbau zu Google Drive fehlgeschlagen!");
finish();
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private byte[] read(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
try (InputStream ios = new FileInputStream(file)) {
if (ios.read(buffer) == -1) {
throw new IOException(
"EOF reached while trying to read the whole file");
}
}
return buffer;
}
public class CreateFileAsyncTask extends | GDriveAsyncTask<Void, Void, Metadata> { | 2 | 2023-12-28 12:33:52+00:00 | 12k |
strokegmd/StrokeClient | stroke/client/modules/render/StorageESP.java | [
{
"identifier": "StrokeClient",
"path": "stroke/client/StrokeClient.java",
"snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpubli... | import java.awt.Color;
import net.minecraft.block.BlockChest;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.tileentity.TileEntityDispenser;
import net.minecraft.tileentity.TileEntityDropper;
import net.minecraft.tileentity.TileEntityEnderChest;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraft.tileentity.TileEntityShulkerBox;
import net.stroke.client.StrokeClient;
import net.stroke.client.clickgui.Setting;
import net.stroke.client.modules.BaseModule;
import net.stroke.client.modules.ModuleCategory;
import net.stroke.client.util.RenderUtils;
| 8,137 | package net.stroke.client.modules.render;
public class StorageESP extends BaseModule {
public StorageESP() {
super("StorageESP", "Highlights storages", 0x00, ModuleCategory.Render, false);
StrokeClient.instance.settingsManager.rSetting(new Setting("Chests", this, true));
StrokeClient.instance.settingsManager.rSetting(new Setting("Shulker Boxes", this, true));
StrokeClient.instance.settingsManager.rSetting(new Setting("Dispensers", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Hoppers", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Droppers", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Furnaces", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Ender Chests", this, false));
}
public void onRender3D() {
boolean chests = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Chests").getValBoolean();
boolean shulkers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Shulker Boxes").getValBoolean();
boolean dispensers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Dispensers").getValBoolean();
boolean hoppers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Hoppers").getValBoolean();
boolean droppers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Droppers").getValBoolean();
boolean furnaces = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Furnaces").getValBoolean();
boolean enderChests = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Ender Chests").getValBoolean();
for(TileEntity entity : mc.world.loadedTileEntityList) {
if (entity instanceof TileEntityChest && chests) {
TileEntityChest chest = (TileEntityChest) entity;
this.drawChestESP(chest, chest.getPos().getX(), chest.getPos().getY(), chest.getPos().getZ());
}
if (entity instanceof TileEntityDispenser && dispensers) {
| package net.stroke.client.modules.render;
public class StorageESP extends BaseModule {
public StorageESP() {
super("StorageESP", "Highlights storages", 0x00, ModuleCategory.Render, false);
StrokeClient.instance.settingsManager.rSetting(new Setting("Chests", this, true));
StrokeClient.instance.settingsManager.rSetting(new Setting("Shulker Boxes", this, true));
StrokeClient.instance.settingsManager.rSetting(new Setting("Dispensers", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Hoppers", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Droppers", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Furnaces", this, false));
StrokeClient.instance.settingsManager.rSetting(new Setting("Ender Chests", this, false));
}
public void onRender3D() {
boolean chests = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Chests").getValBoolean();
boolean shulkers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Shulker Boxes").getValBoolean();
boolean dispensers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Dispensers").getValBoolean();
boolean hoppers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Hoppers").getValBoolean();
boolean droppers = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Droppers").getValBoolean();
boolean furnaces = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Furnaces").getValBoolean();
boolean enderChests = StrokeClient.instance.settingsManager.getSettingByName(this.name, "Ender Chests").getValBoolean();
for(TileEntity entity : mc.world.loadedTileEntityList) {
if (entity instanceof TileEntityChest && chests) {
TileEntityChest chest = (TileEntityChest) entity;
this.drawChestESP(chest, chest.getPos().getX(), chest.getPos().getY(), chest.getPos().getZ());
}
if (entity instanceof TileEntityDispenser && dispensers) {
| RenderUtils.blockESP(entity.getPos(), Color.white, 1.0, 1.0);
| 4 | 2023-12-31 10:56:59+00:00 | 12k |
piovas-lu/condominio | src/main/java/app/condominio/service/PessoaServiceImpl.java | [
{
"identifier": "PessoaDao",
"path": "src/main/java/app/condominio/dao/PessoaDao.java",
"snippet": "public interface PessoaDao extends PagingAndSortingRepository<Pessoa, Long> {\r\n\r\n\t// LATER ordenação do sobrenome?\r\n\tPage<Pessoa> findAllByCondominioOrderByNome(Condominio condominio, Pageable pag... | import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import app.condominio.dao.PessoaDao;
import app.condominio.dao.PessoaFisicaDao;
import app.condominio.dao.PessoaJuridicaDao;
import app.condominio.domain.Condominio;
import app.condominio.domain.Moradia;
import app.condominio.domain.Pessoa;
import app.condominio.domain.PessoaFisica;
import app.condominio.domain.PessoaJuridica;
import app.condominio.domain.Relacao;
import app.condominio.domain.enums.TipoRelacao;
| 8,850 | package app.condominio.service;
@Service
@Transactional
public class PessoaServiceImpl implements PessoaService {
@Autowired
private PessoaDao pessoaDao;
@Autowired
private PessoaFisicaDao pessoaFisicaDao;
@Autowired
private PessoaJuridicaDao pessoaJuridicaDao;
@Autowired
private UsuarioService usuarioService;
@Override
public void salvar(Pessoa entidade) {
if (entidade.getIdPessoa() == null) {
padronizar(entidade);
pessoaDao.save(entidade);
}
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Pessoa ler(Long id) {
return pessoaDao.findById(id).get();
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<Pessoa> listar() {
Condominio condominio = usuarioService.lerLogado().getCondominio();
if (condominio == null) {
return new ArrayList<>();
}
return condominio.getPessoas();
}
@Override
public Page<Pessoa> listarPagina(Pageable pagina) {
Condominio condominio = usuarioService.lerLogado().getCondominio();
if (condominio == null) {
return Page.empty(pagina);
}
return pessoaDao.findAllByCondominioOrderByNome(condominio, pagina);
}
@Override
public void editar(Pessoa entidade) {
padronizar(entidade);
pessoaDao.save(entidade);
}
@Override
public void excluir(Pessoa entidade) {
pessoaDao.delete(entidade);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public void validar(Pessoa entidade, BindingResult validacao) {
// VALIDAÇÕES NA INCLUSÃO
if (entidade.getIdPessoa() == null) {
if (entidade instanceof PessoaFisica) {
if (((PessoaFisica) entidade).getCpf() != null && pessoaFisicaDao.existsByCpfAndCondominio(
((PessoaFisica) entidade).getCpf(), usuarioService.lerLogado().getCondominio())) {
validacao.rejectValue("cpf", "Unique");
}
| package app.condominio.service;
@Service
@Transactional
public class PessoaServiceImpl implements PessoaService {
@Autowired
private PessoaDao pessoaDao;
@Autowired
private PessoaFisicaDao pessoaFisicaDao;
@Autowired
private PessoaJuridicaDao pessoaJuridicaDao;
@Autowired
private UsuarioService usuarioService;
@Override
public void salvar(Pessoa entidade) {
if (entidade.getIdPessoa() == null) {
padronizar(entidade);
pessoaDao.save(entidade);
}
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public Pessoa ler(Long id) {
return pessoaDao.findById(id).get();
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<Pessoa> listar() {
Condominio condominio = usuarioService.lerLogado().getCondominio();
if (condominio == null) {
return new ArrayList<>();
}
return condominio.getPessoas();
}
@Override
public Page<Pessoa> listarPagina(Pageable pagina) {
Condominio condominio = usuarioService.lerLogado().getCondominio();
if (condominio == null) {
return Page.empty(pagina);
}
return pessoaDao.findAllByCondominioOrderByNome(condominio, pagina);
}
@Override
public void editar(Pessoa entidade) {
padronizar(entidade);
pessoaDao.save(entidade);
}
@Override
public void excluir(Pessoa entidade) {
pessoaDao.delete(entidade);
}
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public void validar(Pessoa entidade, BindingResult validacao) {
// VALIDAÇÕES NA INCLUSÃO
if (entidade.getIdPessoa() == null) {
if (entidade instanceof PessoaFisica) {
if (((PessoaFisica) entidade).getCpf() != null && pessoaFisicaDao.existsByCpfAndCondominio(
((PessoaFisica) entidade).getCpf(), usuarioService.lerLogado().getCondominio())) {
validacao.rejectValue("cpf", "Unique");
}
| } else if (entidade instanceof PessoaJuridica) {
| 7 | 2023-12-29 22:19:42+00:00 | 12k |
HuXin0817/shop_api | framework/src/main/java/cn/lili/modules/connect/request/BaseAuthAlipayRequest.java | [
{
"identifier": "Cache",
"path": "framework/src/main/java/cn/lili/cache/Cache.java",
"snippet": "public interface Cache<T> {\n\n /**\n * Get an item from the cache, nontransactionally\n *\n * @param key 缓存key\n * @return the cached object or <tt>null</tt>\n */\n T get(Object ke... | import cn.hutool.core.convert.Convert;
import cn.lili.cache.Cache;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.utils.UrlBuilder;
import cn.lili.modules.connect.config.AuthConfig;
import cn.lili.modules.connect.config.ConnectAuthEnum;
import cn.lili.modules.connect.entity.dto.AuthCallback;
import cn.lili.modules.connect.entity.dto.AuthResponse;
import cn.lili.modules.connect.entity.dto.AuthToken;
import cn.lili.modules.connect.entity.dto.ConnectAuthUser;
import cn.lili.modules.connect.entity.enums.AuthResponseStatus;
import cn.lili.modules.connect.entity.enums.AuthUserGender;
import cn.lili.modules.connect.entity.enums.ConnectEnum;
import cn.lili.modules.connect.entity.enums.SourceEnum;
import cn.lili.modules.connect.exception.AuthException;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse; | 9,849 | package cn.lili.modules.connect.request;
/**
* 支付宝登录
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.0.1
*/
public class BaseAuthAlipayRequest extends BaseAuthRequest {
private final AlipayClient alipayClient;
public BaseAuthAlipayRequest(AuthConfig config, Cache cache) {
super(config, ConnectAuthEnum.ALIPAY, cache);
this.alipayClient = new DefaultAlipayClient(ConnectAuthEnum.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config
.getAlipayPublicKey(), "RSA2");
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(authCallback.getAuthCode());
AlipaySystemOauthTokenResponse response = null;
try {
response = this.alipayClient.execute(request);
} catch (Exception e) {
throw new AuthException(e);
}
if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg());
}
return AuthToken.builder()
.accessToken(response.getAccessToken())
.uid(response.getUserId())
.expireIn(Convert.toInt(response.getExpiresIn()))
.refreshToken(response.getRefreshToken())
.build();
}
/**
* 刷新access token (续期)
*
* @param authToken 登录成功后返回的Token信息
* @return AuthResponse
*/
@Override
public AuthResponse refresh(AuthToken authToken) {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("refresh_token");
request.setRefreshToken(authToken.getRefreshToken());
AlipaySystemOauthTokenResponse response = null;
try {
response = this.alipayClient.execute(request);
} catch (Exception e) {
throw new AuthException(e);
}
if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg());
}
return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode())
.data(AuthToken.builder()
.accessToken(response.getAccessToken())
.uid(response.getUserId())
.expireIn(Convert.toInt(response.getExpiresIn()))
.refreshToken(response.getRefreshToken())
.build())
.build();
}
@Override
protected ConnectAuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken();
AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response = null;
try {
response = this.alipayClient.execute(request, accessToken);
} catch (AlipayApiException e) {
throw new AuthException(e.getErrMsg(), e);
}
if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg());
}
String province = response.getProvince(), city = response.getCity();
String location = String.format("%s %s", StringUtils.isEmpty(province) ? "" : province, StringUtils.isEmpty(city) ? "" : city);
return ConnectAuthUser.builder()
.rawUserInfo(JSONObject.parseObject(JSONObject.toJSONString(response)))
.uuid(response.getUserId())
.username(StringUtils.isEmpty(response.getUserName()) ? response.getNickName() : response.getUserName())
.nickname(response.getNickName())
.avatar(response.getAvatar())
.location(location)
.gender(AuthUserGender.getRealGender(response.getGender()))
.token(authToken)
.source(ConnectEnum.ALIPAY)
.build();
}
/**
* 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
*
* @param state state 验证授权流程的参数,可以防止csrf
* @return 返回授权地址
* @since 1.9.3
*/
@Override
public String authorize(String state) { | package cn.lili.modules.connect.request;
/**
* 支付宝登录
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @since 1.0.1
*/
public class BaseAuthAlipayRequest extends BaseAuthRequest {
private final AlipayClient alipayClient;
public BaseAuthAlipayRequest(AuthConfig config, Cache cache) {
super(config, ConnectAuthEnum.ALIPAY, cache);
this.alipayClient = new DefaultAlipayClient(ConnectAuthEnum.ALIPAY.accessToken(), config.getClientId(), config.getClientSecret(), "json", "UTF-8", config
.getAlipayPublicKey(), "RSA2");
}
@Override
protected AuthToken getAccessToken(AuthCallback authCallback) {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("authorization_code");
request.setCode(authCallback.getAuthCode());
AlipaySystemOauthTokenResponse response = null;
try {
response = this.alipayClient.execute(request);
} catch (Exception e) {
throw new AuthException(e);
}
if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg());
}
return AuthToken.builder()
.accessToken(response.getAccessToken())
.uid(response.getUserId())
.expireIn(Convert.toInt(response.getExpiresIn()))
.refreshToken(response.getRefreshToken())
.build();
}
/**
* 刷新access token (续期)
*
* @param authToken 登录成功后返回的Token信息
* @return AuthResponse
*/
@Override
public AuthResponse refresh(AuthToken authToken) {
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setGrantType("refresh_token");
request.setRefreshToken(authToken.getRefreshToken());
AlipaySystemOauthTokenResponse response = null;
try {
response = this.alipayClient.execute(request);
} catch (Exception e) {
throw new AuthException(e);
}
if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg());
}
return AuthResponse.builder()
.code(AuthResponseStatus.SUCCESS.getCode())
.data(AuthToken.builder()
.accessToken(response.getAccessToken())
.uid(response.getUserId())
.expireIn(Convert.toInt(response.getExpiresIn()))
.refreshToken(response.getRefreshToken())
.build())
.build();
}
@Override
protected ConnectAuthUser getUserInfo(AuthToken authToken) {
String accessToken = authToken.getAccessToken();
AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response = null;
try {
response = this.alipayClient.execute(request, accessToken);
} catch (AlipayApiException e) {
throw new AuthException(e.getErrMsg(), e);
}
if (!response.isSuccess()) {
throw new AuthException(response.getSubMsg());
}
String province = response.getProvince(), city = response.getCity();
String location = String.format("%s %s", StringUtils.isEmpty(province) ? "" : province, StringUtils.isEmpty(city) ? "" : city);
return ConnectAuthUser.builder()
.rawUserInfo(JSONObject.parseObject(JSONObject.toJSONString(response)))
.uuid(response.getUserId())
.username(StringUtils.isEmpty(response.getUserName()) ? response.getNickName() : response.getUserName())
.nickname(response.getNickName())
.avatar(response.getAvatar())
.location(location)
.gender(AuthUserGender.getRealGender(response.getGender()))
.token(authToken)
.source(ConnectEnum.ALIPAY)
.build();
}
/**
* 返回带{@code state}参数的授权url,授权回调时会带上这个{@code state}
*
* @param state state 验证授权流程的参数,可以防止csrf
* @return 返回授权地址
* @since 1.9.3
*/
@Override
public String authorize(String state) { | return UrlBuilder.fromBaseUrl(source.authorize()) | 2 | 2023-12-24 19:45:18+00:00 | 12k |
bta-team-port/moon-mod | src/main/java/teamport/moonmod/MoonMod.java | [
{
"identifier": "BiomeProviderMoon",
"path": "src/main/java/teamport/moonmod/world/BiomeProviderMoon.java",
"snippet": "public class BiomeProviderMoon extends BiomeProvider {\n\tprivate static final BiomeRangeMap brm = new BiomeRangeMap();\n\tprivate final PerlinSimplexNoise temperatureNoise;\n\tprivate... | import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint;
import net.minecraft.core.world.type.WorldType;
import net.minecraft.core.world.type.WorldTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import teamport.moonmod.world.BiomeProviderMoon;
import teamport.moonmod.world.ModDimensions;
import teamport.moonmod.world.WorldTypeMoon;
import teamport.moonmod.world.biome.MoonBiomes;
import teamport.moonmod.entity.EntityUFO;
import teamport.moonmod.entity.render.UFOModel;
import teamport.moonmod.entity.render.UFORenderer;
import teamport.moonmod.block.MoonModBlocks;
import teamport.moonmod.item.MoonModItems;
import net.minecraft.client.sound.block.BlockSound;
import net.minecraft.core.block.Block;
import net.minecraft.core.block.material.Material;
import net.minecraft.core.block.tag.BlockTags;
import teamport.moonmod.block.MoonModBlocks;
import teamport.moonmod.item.MoonModItems;
import turniplabs.halplibe.helper.BlockBuilder;
import turniplabs.halplibe.helper.EntityHelper;
import turniplabs.halplibe.util.GameStartEntrypoint;
import turniplabs.halplibe.util.RecipeEntrypoint;
import useless.dragonfly.helper.ModelHelper; | 8,843 | package teamport.moonmod;
public class MoonMod implements ModInitializer, GameStartEntrypoint, RecipeEntrypoint, PreLaunchEntrypoint {
public static final String MOD_ID = "moonmod";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static WorldType MOON_WORLD;
@Override
public void onInitialize() {
new MoonModBlocks().initializeBlocks();
new MoonModItems().initializeItems();
EntityHelper.createEntity(EntityUFO.class,
new UFORenderer(ModelHelper.getOrCreateEntityModel(MOD_ID, "entity/ufo.json", UFOModel.class)),
300,
"UFO");
LOGGER.info("MoonMod has been initialized. Have fun, brave astronaut!");
}
@Override
public void beforeGameStart() {
}
@Override
public void afterGameStart() {
}
@Override
public void onRecipesReady() {
}
@Override
public void onPreLaunch() {
new MoonBiomes().initializeBiomes();
BiomeProviderMoon.init(); | package teamport.moonmod;
public class MoonMod implements ModInitializer, GameStartEntrypoint, RecipeEntrypoint, PreLaunchEntrypoint {
public static final String MOD_ID = "moonmod";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static WorldType MOON_WORLD;
@Override
public void onInitialize() {
new MoonModBlocks().initializeBlocks();
new MoonModItems().initializeItems();
EntityHelper.createEntity(EntityUFO.class,
new UFORenderer(ModelHelper.getOrCreateEntityModel(MOD_ID, "entity/ufo.json", UFOModel.class)),
300,
"UFO");
LOGGER.info("MoonMod has been initialized. Have fun, brave astronaut!");
}
@Override
public void beforeGameStart() {
}
@Override
public void afterGameStart() {
}
@Override
public void onRecipesReady() {
}
@Override
public void onPreLaunch() {
new MoonBiomes().initializeBiomes();
BiomeProviderMoon.init(); | MOON_WORLD = WorldTypes.register(MoonMod.MOD_ID+":moon", new WorldTypeMoon("moonmod.worldtype.moon")); | 2 | 2023-12-24 14:52:01+00:00 | 12k |
LeeKyeongYong/SBookStudy | src/main/java/com/multibook/bookorder/global/initData/NotProd.java | [
{
"identifier": "Book",
"path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java",
"snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n... | import com.multibook.bookorder.domain.book.book.entity.Book;
import com.multibook.bookorder.domain.book.book.service.BookService;
import com.multibook.bookorder.domain.cash.cash.entity.CashLog;
import com.multibook.bookorder.domain.cash.withdraw.service.WithdrawService;
import com.multibook.bookorder.domain.member.member.entity.Member;
import com.multibook.bookorder.domain.member.member.service.MemberService;
import com.multibook.bookorder.domain.product.cart.service.CartService;
import com.multibook.bookorder.domain.product.order.entity.Order;
import com.multibook.bookorder.domain.product.order.service.OrderService;
import com.multibook.bookorder.domain.product.product.entity.Product;
import com.multibook.bookorder.domain.product.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import com.multibook.bookorder.domain.product.order.entity.Order;
import org.springframework.transaction.annotation.Transactional; | 7,703 | package com.multibook.bookorder.global.initData;
@Configuration
@RequiredArgsConstructor
public class NotProd {
@Autowired
@Lazy
private NotProd self;
private final MemberService memberService;
private final BookService bookService;
private final ProductService productService;
private final CartService cartService;
private final OrderService orderService;
private final WithdrawService withdrawService;
@Bean
@org.springframework.core.annotation.Order(3)
ApplicationRunner initNotProd() {
return args -> {
self.work1();
self.work2();
};
}
@Transactional
public void work1() {
if (memberService.findByUsername("admin").isPresent()) return;
Member memberAdmin = memberService.join("admin", "1234", "관리자").getData();
Member memberUser1 = memberService.join("user1", "1234", "유저1").getData();
Member memberUser2 = memberService.join("user2", "1234", "유저2").getData();
Member memberUser3 = memberService.join("user3", "1234", "유저3").getData();
Member memberUser4 = memberService.join("user4", "1234", "유저4").getData();
Member memberUser5 = memberService.join("user5", "1234", "유저5").getData();
Book book1 = bookService.createBook(memberUser1, "책 제목 1", "책 내용 1", 10_000, true);
Book book2 = bookService.createBook(memberUser2, "책 제목 2", "책 내용 2", 20_000, true);
Book book3 = bookService.createBook(memberUser2, "책 제목 3", "책 내용 3", 30_000, true);
Book book4 = bookService.createBook(memberUser3, "책 제목 4", "책 내용 4", 40_000, true);
Book book5 = bookService.createBook(memberUser3, "책 제목 5", "책 내용 5", 15_000, true);
Book book6 = bookService.createBook(memberUser3, "책 제목 6", "책 내용 6", 20_000, true);
Product product1 = productService.createProduct(book3, true);
Product product2 = productService.createProduct(book4, true);
Product product3 = productService.createProduct(book5, true);
Product product4 = productService.createProduct(book5, true);
cartService.addItem(memberUser1, product1);
cartService.addItem(memberUser1, product2);
cartService.addItem(memberUser1, product3);
cartService.addItem(memberUser2, product1);
cartService.addItem(memberUser2, product2);
cartService.addItem(memberUser2, product3);
cartService.addItem(memberUser3, product1);
cartService.addItem(memberUser3, product2);
cartService.addItem(memberUser3, product3);
| package com.multibook.bookorder.global.initData;
@Configuration
@RequiredArgsConstructor
public class NotProd {
@Autowired
@Lazy
private NotProd self;
private final MemberService memberService;
private final BookService bookService;
private final ProductService productService;
private final CartService cartService;
private final OrderService orderService;
private final WithdrawService withdrawService;
@Bean
@org.springframework.core.annotation.Order(3)
ApplicationRunner initNotProd() {
return args -> {
self.work1();
self.work2();
};
}
@Transactional
public void work1() {
if (memberService.findByUsername("admin").isPresent()) return;
Member memberAdmin = memberService.join("admin", "1234", "관리자").getData();
Member memberUser1 = memberService.join("user1", "1234", "유저1").getData();
Member memberUser2 = memberService.join("user2", "1234", "유저2").getData();
Member memberUser3 = memberService.join("user3", "1234", "유저3").getData();
Member memberUser4 = memberService.join("user4", "1234", "유저4").getData();
Member memberUser5 = memberService.join("user5", "1234", "유저5").getData();
Book book1 = bookService.createBook(memberUser1, "책 제목 1", "책 내용 1", 10_000, true);
Book book2 = bookService.createBook(memberUser2, "책 제목 2", "책 내용 2", 20_000, true);
Book book3 = bookService.createBook(memberUser2, "책 제목 3", "책 내용 3", 30_000, true);
Book book4 = bookService.createBook(memberUser3, "책 제목 4", "책 내용 4", 40_000, true);
Book book5 = bookService.createBook(memberUser3, "책 제목 5", "책 내용 5", 15_000, true);
Book book6 = bookService.createBook(memberUser3, "책 제목 6", "책 내용 6", 20_000, true);
Product product1 = productService.createProduct(book3, true);
Product product2 = productService.createProduct(book4, true);
Product product3 = productService.createProduct(book5, true);
Product product4 = productService.createProduct(book5, true);
cartService.addItem(memberUser1, product1);
cartService.addItem(memberUser1, product2);
cartService.addItem(memberUser1, product3);
cartService.addItem(memberUser2, product1);
cartService.addItem(memberUser2, product2);
cartService.addItem(memberUser2, product3);
cartService.addItem(memberUser3, product1);
cartService.addItem(memberUser3, product2);
cartService.addItem(memberUser3, product3);
| memberService.addCash(memberUser1, 150_000, CashLog.EvenType.충전__무통장입금, memberUser1); | 2 | 2023-12-26 14:58:59+00:00 | 12k |
SDeVuyst/pingys-waddles-1.20.1 | src/main/java/com/sdevuyst/pingyswaddles/item/custom/SurfboardItem.java | [
{
"identifier": "AbstractSurfboard",
"path": "src/main/java/com/sdevuyst/pingyswaddles/entity/custom/AbstractSurfboard.java",
"snippet": "public abstract class AbstractSurfboard extends Entity {\n\n private static final EntityDataAccessor<Integer> DATA_ID_HURT;\n private static final EntityDataAcc... | import com.sdevuyst.pingyswaddles.entity.custom.AbstractSurfboard;
import com.sdevuyst.pingyswaddles.entity.custom.SurfboardEntity;
import net.minecraft.stats.Stats;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySelector;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import java.util.List;
import java.util.function.Predicate; | 8,565 | package com.sdevuyst.pingyswaddles.item.custom;
public class SurfboardItem extends Item {
private static final Predicate<Entity> ENTITY_PREDICATE; | package com.sdevuyst.pingyswaddles.item.custom;
public class SurfboardItem extends Item {
private static final Predicate<Entity> ENTITY_PREDICATE; | private final AbstractSurfboard.Type type; | 0 | 2023-12-31 09:54:03+00:00 | 12k |
quarkiverse/quarkus-langchain4j | openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/OpenAiRecorder.java | [
{
"identifier": "firstOrDefault",
"path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java",
"snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) ... | import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.function.Supplier;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiEmbeddingModel;
import dev.langchain4j.model.openai.OpenAiModerationModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import io.quarkiverse.langchain4j.openai.QuarkusOpenAiClient;
import io.quarkiverse.langchain4j.openai.QuarkusOpenAiImageModel;
import io.quarkiverse.langchain4j.openai.runtime.config.ChatModelConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.EmbeddingModelConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.ImageModelConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.Langchain4jOpenAiConfig;
import io.quarkiverse.langchain4j.openai.runtime.config.ModerationModelConfig;
import io.quarkus.runtime.ShutdownContext;
import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.config.ConfigValidationException; | 10,514 | }
EmbeddingModelConfig embeddingModelConfig = runtimeConfig.embeddingModel();
var builder = OpenAiEmbeddingModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, embeddingModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, embeddingModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(embeddingModelConfig.modelName());
if (embeddingModelConfig.user().isPresent()) {
builder.user(embeddingModelConfig.user().get());
}
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> moderationModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ModerationModelConfig moderationModelConfig = runtimeConfig.moderationModel();
var builder = OpenAiModerationModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, moderationModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, moderationModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(moderationModelConfig.modelName());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> imageModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ImageModelConfig imageModelConfig = runtimeConfig.imageModel();
var builder = QuarkusOpenAiImageModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, imageModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, imageModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(imageModelConfig.modelName())
.size(imageModelConfig.size())
.quality(imageModelConfig.quality())
.style(imageModelConfig.style())
.responseFormat(imageModelConfig.responseFormat())
.user(imageModelConfig.user());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
// we persist if the directory was set explicitly and the boolean flag was not set to false
// or if the boolean flag was set explicitly to true
Optional<Path> persistDirectory = Optional.empty();
if (imageModelConfig.persist().isPresent()) {
if (imageModelConfig.persist().get()) {
persistDirectory = imageModelConfig.persistDirectory()
.or(new Supplier<>() {
@Override
public Optional<? extends Path> get() {
return Optional.of(Paths.get(System.getProperty("java.io.tmpdir"), "dall-e-images"));
}
});
}
} else {
if (imageModelConfig.persistDirectory().isPresent()) {
persistDirectory = imageModelConfig.persistDirectory();
}
}
builder.persistDirectory(persistDirectory);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
private ConfigValidationException.Problem[] createApiKeyConfigProblems() {
return createConfigProblems("api-key");
}
private ConfigValidationException.Problem[] createConfigProblems(String key) {
return new ConfigValidationException.Problem[] { createConfigProblem(key) };
}
private ConfigValidationException.Problem createConfigProblem(String key) {
return new ConfigValidationException.Problem(String.format(
"SRCFG00014: The config property quarkus.langchain4j.openai.%s is required but it could not be found in any config source",
key));
}
public void cleanUp(ShutdownContext shutdown) {
shutdown.addShutdownTask(new Runnable() {
@Override
public void run() { | package io.quarkiverse.langchain4j.openai.runtime;
@Recorder
public class OpenAiRecorder {
public Supplier<?> chatModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = OpenAiChatModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(chatModelConfig.modelName())
.temperature(chatModelConfig.temperature())
.topP(chatModelConfig.topP())
.presencePenalty(chatModelConfig.presencePenalty())
.frequencyPenalty(chatModelConfig.frequencyPenalty());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
if (chatModelConfig.maxTokens().isPresent()) {
builder.maxTokens(chatModelConfig.maxTokens().get());
}
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> streamingChatModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ChatModelConfig chatModelConfig = runtimeConfig.chatModel();
var builder = OpenAiStreamingChatModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(chatModelConfig.modelName())
.temperature(chatModelConfig.temperature())
.topP(chatModelConfig.topP())
.presencePenalty(chatModelConfig.presencePenalty())
.frequencyPenalty(chatModelConfig.frequencyPenalty());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
if (chatModelConfig.maxTokens().isPresent()) {
builder.maxTokens(chatModelConfig.maxTokens().get());
}
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> embeddingModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
EmbeddingModelConfig embeddingModelConfig = runtimeConfig.embeddingModel();
var builder = OpenAiEmbeddingModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, embeddingModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, embeddingModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(embeddingModelConfig.modelName());
if (embeddingModelConfig.user().isPresent()) {
builder.user(embeddingModelConfig.user().get());
}
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> moderationModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ModerationModelConfig moderationModelConfig = runtimeConfig.moderationModel();
var builder = OpenAiModerationModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, moderationModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, moderationModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(moderationModelConfig.modelName());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
public Supplier<?> imageModel(Langchain4jOpenAiConfig runtimeConfig) {
Optional<String> apiKeyOpt = runtimeConfig.apiKey();
if (apiKeyOpt.isEmpty()) {
throw new ConfigValidationException(createApiKeyConfigProblems());
}
ImageModelConfig imageModelConfig = runtimeConfig.imageModel();
var builder = QuarkusOpenAiImageModel.builder()
.baseUrl(runtimeConfig.baseUrl())
.apiKey(apiKeyOpt.get())
.timeout(runtimeConfig.timeout())
.maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, imageModelConfig.logRequests(), runtimeConfig.logRequests()))
.logResponses(firstOrDefault(false, imageModelConfig.logResponses(), runtimeConfig.logResponses()))
.modelName(imageModelConfig.modelName())
.size(imageModelConfig.size())
.quality(imageModelConfig.quality())
.style(imageModelConfig.style())
.responseFormat(imageModelConfig.responseFormat())
.user(imageModelConfig.user());
runtimeConfig.organizationId().ifPresent(builder::organizationId);
// we persist if the directory was set explicitly and the boolean flag was not set to false
// or if the boolean flag was set explicitly to true
Optional<Path> persistDirectory = Optional.empty();
if (imageModelConfig.persist().isPresent()) {
if (imageModelConfig.persist().get()) {
persistDirectory = imageModelConfig.persistDirectory()
.or(new Supplier<>() {
@Override
public Optional<? extends Path> get() {
return Optional.of(Paths.get(System.getProperty("java.io.tmpdir"), "dall-e-images"));
}
});
}
} else {
if (imageModelConfig.persistDirectory().isPresent()) {
persistDirectory = imageModelConfig.persistDirectory();
}
}
builder.persistDirectory(persistDirectory);
return new Supplier<>() {
@Override
public Object get() {
return builder.build();
}
};
}
private ConfigValidationException.Problem[] createApiKeyConfigProblems() {
return createConfigProblems("api-key");
}
private ConfigValidationException.Problem[] createConfigProblems(String key) {
return new ConfigValidationException.Problem[] { createConfigProblem(key) };
}
private ConfigValidationException.Problem createConfigProblem(String key) {
return new ConfigValidationException.Problem(String.format(
"SRCFG00014: The config property quarkus.langchain4j.openai.%s is required but it could not be found in any config source",
key));
}
public void cleanUp(ShutdownContext shutdown) {
shutdown.addShutdownTask(new Runnable() {
@Override
public void run() { | QuarkusOpenAiClient.clearCache(); | 1 | 2023-11-13 09:10:27+00:00 | 12k |
qiusunshine/xiu | VideoPlayModule-Lite/src/main/java/chuangyuan/ycj/videolibrary/video/VideoPlayerManager.java | [
{
"identifier": "AnimUtils",
"path": "VideoUi/src/main/java/com/google/android/exoplayer2/ui/AnimUtils.java",
"snippet": "public class AnimUtils {\n\n public static ViewPropertyAnimatorCompat setOutAnim(View view, boolean ab) {\n return ViewCompat.animate(view).translationY(ab ? view.getHeight... | import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.net.Uri;
import android.view.View;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.Size;
import com.google.android.exoplayer2.ui.AnimUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import chuangyuan.ycj.videolibrary.listener.DataSourceListener;
import chuangyuan.ycj.videolibrary.listener.ItemVideo;
import chuangyuan.ycj.videolibrary.listener.OnGestureBrightnessListener;
import chuangyuan.ycj.videolibrary.listener.OnGestureProgressListener;
import chuangyuan.ycj.videolibrary.listener.OnGestureVolumeListener;
import chuangyuan.ycj.videolibrary.listener.VideoInfoListener;
import chuangyuan.ycj.videolibrary.listener.VideoWindowListener;
import chuangyuan.ycj.videolibrary.widget.VideoPlayerView; | 8,573 | package chuangyuan.ycj.videolibrary.video;
/**
* author yangc
* date 2017/2/27
* E-Mail:1007181167@qq.com
* Description: video播放列表控制类
*/
public class VideoPlayerManager {
private ManualPlayer mVideoPlayer;
private boolean isClick = false;
public static float PLAY_SPEED = 1f;
public static boolean tempFastPlay;
public static int FAST_PLAY_TIMES = 2;
private VideoPlayerManager() {
}
/**
* Gets instance.
*
* @return the instance
*/
public static VideoPlayerManager getInstance() {
return Holder.holder;
}
private static class Holder {
static VideoPlayerManager holder = new VideoPlayerManager();
}
/***
* 设置当前播放 控制类
*
* @param videoPlayer 播放页
*/
public void setCurrentVideoPlayer(@NonNull ManualPlayer videoPlayer) {
if (mVideoPlayer == null || !videoPlayer.toString().equals(mVideoPlayer.toString())) {
releaseVideoPlayer();
}
this.mVideoPlayer = videoPlayer;
}
/***
* 释放当前播放
*/
public void releaseVideoPlayer() {
if (mVideoPlayer != null) {
mVideoPlayer.reset();
mVideoPlayer = null;
}
}
/***
* d手机屏幕旋转配置
* @param newConfig newConfig
*/
public void onConfigurationChanged(Configuration newConfig) {
if (mVideoPlayer != null) {
mVideoPlayer.onConfigurationChanged(newConfig);
}
}
/***
* 设置返回建监听
*
* @return boolean boolean
*/
public boolean onBackPressed() {
return mVideoPlayer == null || mVideoPlayer.onBackPressed();
}
/**
* 页面暂停播放暂停
*
* @param isReset isReset 没有特殊情况 默认 true 释放
*/
public void onPause(boolean isReset) {
if (mVideoPlayer != null) {
mVideoPlayer.onListPause(isReset);
}
}
/**
* 页面恢复
*/
public void onResume() {
if (mVideoPlayer != null) {
mVideoPlayer.onResume();
}
}
/**
* 页面销毁
*/
public void onDestroy() {
if (mVideoPlayer != null) {
mVideoPlayer.onDestroy();
mVideoPlayer = null;
}
}
/**
* 获取当前播放类
*
* @return ManualPlayer video player
*/
@Nullable
public ManualPlayer getVideoPlayer() {
if (mVideoPlayer != null && mVideoPlayer.getPlayer() != null) {
return mVideoPlayer;
}
return null;
}
/**
* 获取当前状态
*
* @return ManualPlayer boolean
*/
boolean isClick() {
return isClick;
}
/**
* 获取当前播放类
*
* @param click 实例
*/
public void setClick(boolean click) {
isClick = click;
}
/*****
* @param player 播放控制器
*@param newPlayerView 新的view
*@param isPlay isPlay 是否播放
* ****/
public void switchTargetView(@NonNull ManualPlayer player, @Nullable VideoPlayerView newPlayerView, boolean isPlay) {
VideoPlayerView oldPlayerView = player.getVideoPlayerView();
if (oldPlayerView == newPlayerView) {
return;
}
if (newPlayerView != null) {
newPlayerView.getPlayerView().setPlayer(player.getPlayer());
player.setVideoPlayerView(newPlayerView);
}
if (oldPlayerView != null) {
oldPlayerView.resets();
oldPlayerView.getPlayerView().setPlayer(null);
}
if (isPlay) {
player.setStartOrPause(true);
} else {
if (newPlayerView != null) {
player.reset();
player.resetInit();
}
}
}
public static final int TYPE_PLAY_USER = 0;
public static final int TYPE_PLAY_GESTURE = 1;
public static final int TYPE_PLAY_MANUAL = 2;
@IntDef({TYPE_PLAY_USER, TYPE_PLAY_GESTURE, TYPE_PLAY_MANUAL})
@Retention(RetentionPolicy.SOURCE)
@interface PlayerType {
}
/***
* 构建内部构建者
* **/
public static class Builder {
private Activity context;
private VideoPlayerView view; | package chuangyuan.ycj.videolibrary.video;
/**
* author yangc
* date 2017/2/27
* E-Mail:1007181167@qq.com
* Description: video播放列表控制类
*/
public class VideoPlayerManager {
private ManualPlayer mVideoPlayer;
private boolean isClick = false;
public static float PLAY_SPEED = 1f;
public static boolean tempFastPlay;
public static int FAST_PLAY_TIMES = 2;
private VideoPlayerManager() {
}
/**
* Gets instance.
*
* @return the instance
*/
public static VideoPlayerManager getInstance() {
return Holder.holder;
}
private static class Holder {
static VideoPlayerManager holder = new VideoPlayerManager();
}
/***
* 设置当前播放 控制类
*
* @param videoPlayer 播放页
*/
public void setCurrentVideoPlayer(@NonNull ManualPlayer videoPlayer) {
if (mVideoPlayer == null || !videoPlayer.toString().equals(mVideoPlayer.toString())) {
releaseVideoPlayer();
}
this.mVideoPlayer = videoPlayer;
}
/***
* 释放当前播放
*/
public void releaseVideoPlayer() {
if (mVideoPlayer != null) {
mVideoPlayer.reset();
mVideoPlayer = null;
}
}
/***
* d手机屏幕旋转配置
* @param newConfig newConfig
*/
public void onConfigurationChanged(Configuration newConfig) {
if (mVideoPlayer != null) {
mVideoPlayer.onConfigurationChanged(newConfig);
}
}
/***
* 设置返回建监听
*
* @return boolean boolean
*/
public boolean onBackPressed() {
return mVideoPlayer == null || mVideoPlayer.onBackPressed();
}
/**
* 页面暂停播放暂停
*
* @param isReset isReset 没有特殊情况 默认 true 释放
*/
public void onPause(boolean isReset) {
if (mVideoPlayer != null) {
mVideoPlayer.onListPause(isReset);
}
}
/**
* 页面恢复
*/
public void onResume() {
if (mVideoPlayer != null) {
mVideoPlayer.onResume();
}
}
/**
* 页面销毁
*/
public void onDestroy() {
if (mVideoPlayer != null) {
mVideoPlayer.onDestroy();
mVideoPlayer = null;
}
}
/**
* 获取当前播放类
*
* @return ManualPlayer video player
*/
@Nullable
public ManualPlayer getVideoPlayer() {
if (mVideoPlayer != null && mVideoPlayer.getPlayer() != null) {
return mVideoPlayer;
}
return null;
}
/**
* 获取当前状态
*
* @return ManualPlayer boolean
*/
boolean isClick() {
return isClick;
}
/**
* 获取当前播放类
*
* @param click 实例
*/
public void setClick(boolean click) {
isClick = click;
}
/*****
* @param player 播放控制器
*@param newPlayerView 新的view
*@param isPlay isPlay 是否播放
* ****/
public void switchTargetView(@NonNull ManualPlayer player, @Nullable VideoPlayerView newPlayerView, boolean isPlay) {
VideoPlayerView oldPlayerView = player.getVideoPlayerView();
if (oldPlayerView == newPlayerView) {
return;
}
if (newPlayerView != null) {
newPlayerView.getPlayerView().setPlayer(player.getPlayer());
player.setVideoPlayerView(newPlayerView);
}
if (oldPlayerView != null) {
oldPlayerView.resets();
oldPlayerView.getPlayerView().setPlayer(null);
}
if (isPlay) {
player.setStartOrPause(true);
} else {
if (newPlayerView != null) {
player.reset();
player.resetInit();
}
}
}
public static final int TYPE_PLAY_USER = 0;
public static final int TYPE_PLAY_GESTURE = 1;
public static final int TYPE_PLAY_MANUAL = 2;
@IntDef({TYPE_PLAY_USER, TYPE_PLAY_GESTURE, TYPE_PLAY_MANUAL})
@Retention(RetentionPolicy.SOURCE)
@interface PlayerType {
}
/***
* 构建内部构建者
* **/
public static class Builder {
private Activity context;
private VideoPlayerView view; | private DataSourceListener listener; | 1 | 2023-11-10 14:28:40+00:00 | 12k |
noear/folkmq | folkmq-test/src/test/java/features/cases/TestCase09_persistent.java | [
{
"identifier": "MqClientDefault",
"path": "folkmq/src/main/java/org/noear/folkmq/client/MqClientDefault.java",
"snippet": "public class MqClientDefault implements MqClientInternal {\n private static final Logger log = LoggerFactory.getLogger(MqClientDefault.class);\n\n //服务端地址\n private final ... | import org.noear.folkmq.client.MqClientDefault;
import org.noear.folkmq.client.MqMessage;
import org.noear.folkmq.server.MqServerDefault;
import org.noear.folkmq.server.MqServiceInternal;
import org.noear.folkmq.server.MqQueue;
import org.noear.folkmq.server.pro.MqWatcherSnapshot;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; | 7,709 | package features.cases;
/**
* @author noear
* @since 1.0
*/
public class TestCase09_persistent extends BaseTestCase {
public TestCase09_persistent(int port) {
super(port);
}
@Override
public void start() throws Exception {
super.start();
//服务端
server = new MqServerDefault()
.watcher(new MqWatcherSnapshot())
.start(getPort());
//客户端
CountDownLatch countDownLatch = new CountDownLatch(4);
| package features.cases;
/**
* @author noear
* @since 1.0
*/
public class TestCase09_persistent extends BaseTestCase {
public TestCase09_persistent(int port) {
super(port);
}
@Override
public void start() throws Exception {
super.start();
//服务端
server = new MqServerDefault()
.watcher(new MqWatcherSnapshot())
.start(getPort());
//客户端
CountDownLatch countDownLatch = new CountDownLatch(4);
| client = new MqClientDefault("folkmq://127.0.0.1:" + getPort()) | 0 | 2023-11-18 19:09:28+00:00 | 12k |
BlyznytsiaOrg/bring | web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/DispatcherServlet.java | [
{
"identifier": "MissingApplicationMappingException",
"path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/exception/MissingApplicationMappingException.java",
"snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND)\npublic class MissingApplicationMappingException extends RuntimeExcepti... | import io.github.blyznytsiaorg.bring.core.annotation.Component;
import io.github.blyznytsiaorg.bring.web.servlet.annotation.PathVariable;
import io.github.blyznytsiaorg.bring.web.servlet.annotation.RequestBody;
import io.github.blyznytsiaorg.bring.web.servlet.annotation.RequestHeader;
import io.github.blyznytsiaorg.bring.web.servlet.annotation.RequestParam;
import io.github.blyznytsiaorg.bring.web.servlet.annotation.ResponseStatus;
import io.github.blyznytsiaorg.bring.web.servlet.exception.MissingApplicationMappingException;
import io.github.blyznytsiaorg.bring.web.servlet.exception.MissingRequestParamException;
import io.github.blyznytsiaorg.bring.web.servlet.http.HttpHeaders;
import io.github.blyznytsiaorg.bring.web.servlet.http.HttpStatus;
import io.github.blyznytsiaorg.bring.web.servlet.http.ResponseEntity;
import io.github.blyznytsiaorg.bring.web.servlet.mapping.RestControllerParams;
import io.github.blyznytsiaorg.bring.web.servlet.mapping.RestControllerProcessResult;
import io.github.blyznytsiaorg.bring.web.utils.ReflectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static io.github.blyznytsiaorg.bring.web.utils.HttpServletRequestUtils.getRequestPath;
import static io.github.blyznytsiaorg.bring.web.utils.HttpServletRequestUtils.getShortenedPath;
import static io.github.blyznytsiaorg.bring.web.utils.ParameterTypeUtils.parseToParameterType; | 9,205 | package io.github.blyznytsiaorg.bring.web.servlet;
/**
* The {@code DispatcherServlet} class extends {@code FrameworkServlet} and serves as the central
* dispatcher for handling HTTP requests in a RESTful web application.
* It processes incoming requests, resolves appropriate controllers and manages response generation.
*
* <p>
* The class supports the annotation-based mapping of controllers and provides a flexible mechanism
* for handling various types of parameters in controller methods.
* </p>
*
* <p>
* Key Constants:
* - {@code REST_CONTROLLER_PARAMS}: Key for storing REST controller parameters in the servlet context.
* - {@code REGEX_STATIC_URL}: Regular expression for matching static URLs.
* </p>
*
* <p>
* Key Components:
* - {@code objectMapper}: Object mapper for converting between JSON and Java objects.
* </p>
*
* @see RestControllerContext
* @since 1.0
*/
@Component
@Slf4j
public class DispatcherServlet extends FrameworkServlet {
private static final String MISSING_APPLICATION_MAPPING_MESSAGE = "This application has no explicit mapping for '%s'";
public static final String REST_CONTROLLER_PARAMS = "REST_CONTROLLER_PARAMS";
public static final String REGEX_STATIC_URL = "^/static/.*$";
public static final int HTTP_STATUS_OK = 200;
private final ObjectMapper objectMapper;
public DispatcherServlet(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/**
* Overrides the {@code processRequest} method of {@code FrameworkServlet}.
* Processes incoming HTTP requests by obtaining REST controller parameters and
* delegating the processing to {@code processRestControllerRequest}.
*
* @param req HttpServletRequest object representing the HTTP request.
* @param resp HttpServletResponse object representing the HTTP response.
*/
@Override
public void processRequest(HttpServletRequest req, HttpServletResponse resp) {
log.info("Got a {} request by path: {}", req.getMethod(), req.getRequestURI());
RestControllerParams restControllerParams = getRestControllerParams(req);
processRestControllerRequest(restControllerParams, req, resp);
}
/**
* Retrieves the {@code RestControllerParams} for the given {@code HttpServletRequest}.
* The method uses the request's method and path to find the corresponding controller parameters
* stored in the servlet context. It filters the parameters based on the path and path variables,
* then returns the first match. If no match is found, it throws a {@code MissingApplicationMappingException}.
*
* @param req HttpServletRequest object representing the HTTP request.
* @return The matched {@code RestControllerParams} for the request.
* @throws MissingApplicationMappingException If no explicit mapping is found for the request.
*/
@SuppressWarnings("unchecked")
private RestControllerParams getRestControllerParams(HttpServletRequest req) {
String requestPath = getRequestPath(req);
String methodName = req.getMethod();
var restControllerParams = (Map<String, List<RestControllerParams>>) req.getServletContext()
.getAttribute(REST_CONTROLLER_PARAMS);
return restControllerParams.getOrDefault(methodName, Collections.emptyList())
.stream()
.filter(params -> checkParams(requestPath, params))
.findFirst()
.orElseThrow(() -> {
log.warn(String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req)));
return new MissingApplicationMappingException(
String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req)), null, true, false);
});
}
/**
* Checks if the given {@code RestControllerParams} match the provided request path.
* If the controller method has path variables, it shortens the request path accordingly.
* The method returns true if the paths match, considering path variables and static URLs.
*
* @param requestPath The path of the HTTP request.
* @param params The {@code RestControllerParams} to check against.
* @return True if the paths match; false otherwise.
*/
private boolean checkParams(String requestPath, RestControllerParams params) {
Method method = params.method();
Parameter[] parameters = method.getParameters();
if (checkIfPathVariableAnnotationIsPresent(parameters)) {
String requestPathShortened = getShortenedPath(requestPath);
return requestPathShortened.equals(params.path());
}
return requestPath.equals(params.path()) || checkIfUrlIsStatic(requestPath, params.path());
}
/**
* Processes the HTTP request for a specific {@code RestControllerParams}.
* Invokes the corresponding controller method with the provided arguments and handles the resulting response.
*
* @param params The {@code RestControllerParams} representing the controller method to invoke.
* @param req HttpServletRequest object representing the HTTP request.
* @param resp HttpServletResponse object representing the HTTP response.
*/
@SneakyThrows
private void processRestControllerRequest(RestControllerParams params,
HttpServletRequest req,
HttpServletResponse resp) {
String requestPath = getRequestPath(req);
Object instance = params.instance();
Method method = params.method();
Object[] args = (method.getParameterCount() == 0)
? new Object[0]
: prepareArgs(req, resp, requestPath, method);
getRestControllerProcessResult(instance, method, resp, args);
}
/**
* Invokes the controller method with the provided arguments and handles the resulting response.
* If the method returns a non-null result, it is passed to the {@code performResponse} method
* along with method metadata (e.g., annotations). The response is then written to the provided {@code HttpServletResponse}.
*
* @param instance The instance of the controller.
* @param method The controller method to invoke.
* @param resp The {@code HttpServletResponse} object representing the HTTP response.
* @param args The arguments to be passed to the controller method.
* @throws IllegalAccessException If the method is inaccessible.
* @throws InvocationTargetException If the invoked method throws an exception.
*/
private void getRestControllerProcessResult(
Object instance, Method method, HttpServletResponse resp, Object... args)
throws IllegalAccessException, InvocationTargetException {
log.trace("Invoking {} method {}", instance.getClass().getSimpleName(), method.getName());
Optional.ofNullable(method.invoke(instance, args))
.ifPresent(result -> performResponse(new RestControllerProcessResult(method, result), resp));
}
/**
* Handles the response generated by a controller method.
* Checks if the response is an instance of {@code ResponseEntity}.
* If it is, processes the response entity, including HTTP status and headers.
* Writes the final response (including possible modifications) to the provided {@code HttpServletResponse}.
*
* @param processResult The result of the controller method execution, including metadata.
* @param resp The {@code HttpServletResponse} object representing the HTTP response.
*/
@SneakyThrows
private void performResponse(RestControllerProcessResult processResult,
HttpServletResponse resp) {
Object response = processResult.result();
Object body; | package io.github.blyznytsiaorg.bring.web.servlet;
/**
* The {@code DispatcherServlet} class extends {@code FrameworkServlet} and serves as the central
* dispatcher for handling HTTP requests in a RESTful web application.
* It processes incoming requests, resolves appropriate controllers and manages response generation.
*
* <p>
* The class supports the annotation-based mapping of controllers and provides a flexible mechanism
* for handling various types of parameters in controller methods.
* </p>
*
* <p>
* Key Constants:
* - {@code REST_CONTROLLER_PARAMS}: Key for storing REST controller parameters in the servlet context.
* - {@code REGEX_STATIC_URL}: Regular expression for matching static URLs.
* </p>
*
* <p>
* Key Components:
* - {@code objectMapper}: Object mapper for converting between JSON and Java objects.
* </p>
*
* @see RestControllerContext
* @since 1.0
*/
@Component
@Slf4j
public class DispatcherServlet extends FrameworkServlet {
private static final String MISSING_APPLICATION_MAPPING_MESSAGE = "This application has no explicit mapping for '%s'";
public static final String REST_CONTROLLER_PARAMS = "REST_CONTROLLER_PARAMS";
public static final String REGEX_STATIC_URL = "^/static/.*$";
public static final int HTTP_STATUS_OK = 200;
private final ObjectMapper objectMapper;
public DispatcherServlet(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
/**
* Overrides the {@code processRequest} method of {@code FrameworkServlet}.
* Processes incoming HTTP requests by obtaining REST controller parameters and
* delegating the processing to {@code processRestControllerRequest}.
*
* @param req HttpServletRequest object representing the HTTP request.
* @param resp HttpServletResponse object representing the HTTP response.
*/
@Override
public void processRequest(HttpServletRequest req, HttpServletResponse resp) {
log.info("Got a {} request by path: {}", req.getMethod(), req.getRequestURI());
RestControllerParams restControllerParams = getRestControllerParams(req);
processRestControllerRequest(restControllerParams, req, resp);
}
/**
* Retrieves the {@code RestControllerParams} for the given {@code HttpServletRequest}.
* The method uses the request's method and path to find the corresponding controller parameters
* stored in the servlet context. It filters the parameters based on the path and path variables,
* then returns the first match. If no match is found, it throws a {@code MissingApplicationMappingException}.
*
* @param req HttpServletRequest object representing the HTTP request.
* @return The matched {@code RestControllerParams} for the request.
* @throws MissingApplicationMappingException If no explicit mapping is found for the request.
*/
@SuppressWarnings("unchecked")
private RestControllerParams getRestControllerParams(HttpServletRequest req) {
String requestPath = getRequestPath(req);
String methodName = req.getMethod();
var restControllerParams = (Map<String, List<RestControllerParams>>) req.getServletContext()
.getAttribute(REST_CONTROLLER_PARAMS);
return restControllerParams.getOrDefault(methodName, Collections.emptyList())
.stream()
.filter(params -> checkParams(requestPath, params))
.findFirst()
.orElseThrow(() -> {
log.warn(String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req)));
return new MissingApplicationMappingException(
String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req)), null, true, false);
});
}
/**
* Checks if the given {@code RestControllerParams} match the provided request path.
* If the controller method has path variables, it shortens the request path accordingly.
* The method returns true if the paths match, considering path variables and static URLs.
*
* @param requestPath The path of the HTTP request.
* @param params The {@code RestControllerParams} to check against.
* @return True if the paths match; false otherwise.
*/
private boolean checkParams(String requestPath, RestControllerParams params) {
Method method = params.method();
Parameter[] parameters = method.getParameters();
if (checkIfPathVariableAnnotationIsPresent(parameters)) {
String requestPathShortened = getShortenedPath(requestPath);
return requestPathShortened.equals(params.path());
}
return requestPath.equals(params.path()) || checkIfUrlIsStatic(requestPath, params.path());
}
/**
* Processes the HTTP request for a specific {@code RestControllerParams}.
* Invokes the corresponding controller method with the provided arguments and handles the resulting response.
*
* @param params The {@code RestControllerParams} representing the controller method to invoke.
* @param req HttpServletRequest object representing the HTTP request.
* @param resp HttpServletResponse object representing the HTTP response.
*/
@SneakyThrows
private void processRestControllerRequest(RestControllerParams params,
HttpServletRequest req,
HttpServletResponse resp) {
String requestPath = getRequestPath(req);
Object instance = params.instance();
Method method = params.method();
Object[] args = (method.getParameterCount() == 0)
? new Object[0]
: prepareArgs(req, resp, requestPath, method);
getRestControllerProcessResult(instance, method, resp, args);
}
/**
* Invokes the controller method with the provided arguments and handles the resulting response.
* If the method returns a non-null result, it is passed to the {@code performResponse} method
* along with method metadata (e.g., annotations). The response is then written to the provided {@code HttpServletResponse}.
*
* @param instance The instance of the controller.
* @param method The controller method to invoke.
* @param resp The {@code HttpServletResponse} object representing the HTTP response.
* @param args The arguments to be passed to the controller method.
* @throws IllegalAccessException If the method is inaccessible.
* @throws InvocationTargetException If the invoked method throws an exception.
*/
private void getRestControllerProcessResult(
Object instance, Method method, HttpServletResponse resp, Object... args)
throws IllegalAccessException, InvocationTargetException {
log.trace("Invoking {} method {}", instance.getClass().getSimpleName(), method.getName());
Optional.ofNullable(method.invoke(instance, args))
.ifPresent(result -> performResponse(new RestControllerProcessResult(method, result), resp));
}
/**
* Handles the response generated by a controller method.
* Checks if the response is an instance of {@code ResponseEntity}.
* If it is, processes the response entity, including HTTP status and headers.
* Writes the final response (including possible modifications) to the provided {@code HttpServletResponse}.
*
* @param processResult The result of the controller method execution, including metadata.
* @param resp The {@code HttpServletResponse} object representing the HTTP response.
*/
@SneakyThrows
private void performResponse(RestControllerProcessResult processResult,
HttpServletResponse resp) {
Object response = processResult.result();
Object body; | if (response instanceof ResponseEntity<?> entity) { | 4 | 2023-11-10 13:42:05+00:00 | 12k |
johndeweyzxc/AWPS-Command | app/src/main/java/com/johndeweydev/awps/view/manualarmafragment/ManualArmaFragment.java | [
{
"identifier": "BAUD_RATE",
"path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java",
"snippet": "public static final int BAUD_RATE = 19200;"
},
{
"identifier": "DATA_BITS",
"path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java",
"snippet": "public static final i... | import static com.johndeweydev.awps.AppConstants.BAUD_RATE;
import static com.johndeweydev.awps.AppConstants.DATA_BITS;
import static com.johndeweydev.awps.AppConstants.PARITY_NONE;
import static com.johndeweydev.awps.AppConstants.STOP_BITS;
import android.content.Context;
import android.content.IntentSender;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.Priority;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.Task;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.johndeweydev.awps.R;
import com.johndeweydev.awps.databinding.FragmentManualArmaBinding;
import com.johndeweydev.awps.model.data.AccessPointData;
import com.johndeweydev.awps.model.data.DeviceConnectionParamData;
import com.johndeweydev.awps.model.data.HashInfoEntity;
import com.johndeweydev.awps.model.repo.serial.sessionreposerial.SessionRepoSerial;
import com.johndeweydev.awps.viewmodel.hashinfoviewmodel.HashInfoViewModel;
import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionViewModel;
import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionViewModelFactory;
import java.util.ArrayList;
import java.util.Objects; | 7,561 | package com.johndeweydev.awps.view.manualarmafragment;
public class ManualArmaFragment extends Fragment {
private FragmentManualArmaBinding binding;
private ManualArmaArgs manualArmaArgs = null; | package com.johndeweydev.awps.view.manualarmafragment;
public class ManualArmaFragment extends Fragment {
private FragmentManualArmaBinding binding;
private ManualArmaArgs manualArmaArgs = null; | private SessionViewModel sessionViewModel; | 6 | 2023-11-15 15:54:39+00:00 | 12k |
Charles7c/continew-starter | continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/base/BaseServiceImpl.java | [
{
"identifier": "ExceptionUtils",
"path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ExceptionUtils.java",
"snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ExceptionUtils {\n\n /**\n * 打印线程异常信息\n *\n * @param runnable 线... | import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import top.charles7c.continew.starter.core.util.ExceptionUtils;
import top.charles7c.continew.starter.core.util.ReflectUtils;
import top.charles7c.continew.starter.core.util.validate.CheckUtils;
import top.charles7c.continew.starter.data.mybatis.plus.base.BaseMapper;
import top.charles7c.continew.starter.data.mybatis.plus.query.QueryHelper;
import top.charles7c.continew.starter.extension.crud.annotation.TreeField;
import top.charles7c.continew.starter.extension.crud.model.query.PageQuery;
import top.charles7c.continew.starter.extension.crud.model.query.SortQuery;
import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp;
import top.charles7c.continew.starter.extension.crud.util.TreeUtils;
import top.charles7c.continew.starter.file.excel.util.ExcelUtils;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List; | 9,849 | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.charles7c.continew.starter.extension.crud.base;
/**
* 业务实现基类
*
* @param <M> Mapper 接口
* @param <T> 实体类
* @param <L> 列表信息
* @param <D> 详情信息
* @param <Q> 查询条件
* @param <C> 创建或修改信息
* @author Charles7c
* @since 1.0.0
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, L, D, Q, C extends BaseReq>
implements BaseService<L, D, Q, C> {
@Autowired
protected M baseMapper;
private final Class<T> entityClass;
private final Class<L> listClass;
private final Class<D> detailClass;
protected BaseServiceImpl() {
this.entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);
this.listClass = (Class<L>) ClassUtil.getTypeArgument(this.getClass(), 2);
this.detailClass = (Class<D>) ClassUtil.getTypeArgument(this.getClass(), 3);
}
@Override
public PageDataResp<L> page(Q query, PageQuery pageQuery) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
IPage<T> page = baseMapper.selectPage(pageQuery.toPage(), queryWrapper);
PageDataResp<L> pageDataResp = PageDataResp.build(page, listClass);
pageDataResp.getList().forEach(this::fill);
return pageDataResp;
}
@Override
public List<Tree<Long>> tree(Q query, SortQuery sortQuery, boolean isSimple) {
List<L> list = this.list(query, sortQuery);
if (CollUtil.isEmpty(list)) {
return new ArrayList<>(0);
}
// 如果构建简单树结构,则不包含基本树结构之外的扩展字段
TreeNodeConfig treeNodeConfig = TreeUtils.DEFAULT_CONFIG;
TreeField treeField = listClass.getDeclaredAnnotation(TreeField.class);
if (!isSimple) {
// 根据 @TreeField 配置生成树结构配置
treeNodeConfig = TreeUtils.genTreeNodeConfig(treeField);
}
// 构建树
return TreeUtils.build(list, treeNodeConfig, (node, tree) -> {
// 转换器
tree.setId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.value())));
tree.setParentId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.parentIdKey())));
tree.setName(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.nameKey())));
tree.setWeight(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.weightKey())));
if (!isSimple) {
List<Field> fieldList = ReflectUtils.getNonStaticFields(listClass);
fieldList.removeIf(f -> StrUtil.containsAnyIgnoreCase(f.getName(), treeField.value(),
treeField.parentIdKey(), treeField.nameKey(), treeField.weightKey(), treeField.childrenKey()));
fieldList
.forEach(f -> tree.putExtra(f.getName(), ReflectUtil.invoke(node, StrUtil.genGetter(f.getName()))));
}
});
}
@Override
public List<L> list(Q query, SortQuery sortQuery) {
List<L> list = this.list(query, sortQuery, listClass);
list.forEach(this::fill);
return list;
}
/**
* 查询列表
*
* @param query 查询条件
* @param sortQuery 排序查询条件
* @param targetClass 指定类型
* @return 列表信息
*/
protected <E> List<E> list(Q query, SortQuery sortQuery, Class<E> targetClass) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
// 设置排序
this.sort(queryWrapper, sortQuery);
List<T> entityList = baseMapper.selectList(queryWrapper);
return BeanUtil.copyToList(entityList, targetClass);
}
/**
* 设置排序
*
* @param queryWrapper 查询 Wrapper
* @param sortQuery 排序查询条件
*/
protected void sort(QueryWrapper<T> queryWrapper, SortQuery sortQuery) {
Sort sort = Opt.ofNullable(sortQuery).orElseGet(SortQuery::new).getSort();
for (Sort.Order order : sort) {
if (null != order) {
queryWrapper.orderBy(true, order.isAscending(), StrUtil.toUnderlineCase(order.getProperty()));
}
}
}
@Override
public D get(Long id) {
T entity = this.getById(id);
D detail = BeanUtil.copyProperties(entity, detailClass);
this.fillDetail(detail);
return detail;
}
@Override
public Long add(C req) {
if (null == req) {
return 0L;
}
T entity = BeanUtil.copyProperties(req, entityClass);
baseMapper.insert(entity);
return entity.getId();
}
@Override
public void update(C req, Long id) {
T entity = this.getById(id);
BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
baseMapper.updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(List<Long> ids) {
baseMapper.deleteBatchIds(ids);
}
@Override
public void export(Q query, SortQuery sortQuery, HttpServletResponse response) {
List<D> list = this.list(query, sortQuery, detailClass);
list.forEach(this::fillDetail);
ExcelUtils.export(list, "导出数据", detailClass, response);
}
/**
* 根据 ID 查询
*
* @param id ID
* @return 实体信息
*/
protected T getById(Object id) {
T entity = baseMapper.selectById(Convert.toStr(id)); | /*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.charles7c.continew.starter.extension.crud.base;
/**
* 业务实现基类
*
* @param <M> Mapper 接口
* @param <T> 实体类
* @param <L> 列表信息
* @param <D> 详情信息
* @param <Q> 查询条件
* @param <C> 创建或修改信息
* @author Charles7c
* @since 1.0.0
*/
public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, L, D, Q, C extends BaseReq>
implements BaseService<L, D, Q, C> {
@Autowired
protected M baseMapper;
private final Class<T> entityClass;
private final Class<L> listClass;
private final Class<D> detailClass;
protected BaseServiceImpl() {
this.entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1);
this.listClass = (Class<L>) ClassUtil.getTypeArgument(this.getClass(), 2);
this.detailClass = (Class<D>) ClassUtil.getTypeArgument(this.getClass(), 3);
}
@Override
public PageDataResp<L> page(Q query, PageQuery pageQuery) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
IPage<T> page = baseMapper.selectPage(pageQuery.toPage(), queryWrapper);
PageDataResp<L> pageDataResp = PageDataResp.build(page, listClass);
pageDataResp.getList().forEach(this::fill);
return pageDataResp;
}
@Override
public List<Tree<Long>> tree(Q query, SortQuery sortQuery, boolean isSimple) {
List<L> list = this.list(query, sortQuery);
if (CollUtil.isEmpty(list)) {
return new ArrayList<>(0);
}
// 如果构建简单树结构,则不包含基本树结构之外的扩展字段
TreeNodeConfig treeNodeConfig = TreeUtils.DEFAULT_CONFIG;
TreeField treeField = listClass.getDeclaredAnnotation(TreeField.class);
if (!isSimple) {
// 根据 @TreeField 配置生成树结构配置
treeNodeConfig = TreeUtils.genTreeNodeConfig(treeField);
}
// 构建树
return TreeUtils.build(list, treeNodeConfig, (node, tree) -> {
// 转换器
tree.setId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.value())));
tree.setParentId(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.parentIdKey())));
tree.setName(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.nameKey())));
tree.setWeight(ReflectUtil.invoke(node, StrUtil.genGetter(treeField.weightKey())));
if (!isSimple) {
List<Field> fieldList = ReflectUtils.getNonStaticFields(listClass);
fieldList.removeIf(f -> StrUtil.containsAnyIgnoreCase(f.getName(), treeField.value(),
treeField.parentIdKey(), treeField.nameKey(), treeField.weightKey(), treeField.childrenKey()));
fieldList
.forEach(f -> tree.putExtra(f.getName(), ReflectUtil.invoke(node, StrUtil.genGetter(f.getName()))));
}
});
}
@Override
public List<L> list(Q query, SortQuery sortQuery) {
List<L> list = this.list(query, sortQuery, listClass);
list.forEach(this::fill);
return list;
}
/**
* 查询列表
*
* @param query 查询条件
* @param sortQuery 排序查询条件
* @param targetClass 指定类型
* @return 列表信息
*/
protected <E> List<E> list(Q query, SortQuery sortQuery, Class<E> targetClass) {
QueryWrapper<T> queryWrapper = QueryHelper.build(query);
// 设置排序
this.sort(queryWrapper, sortQuery);
List<T> entityList = baseMapper.selectList(queryWrapper);
return BeanUtil.copyToList(entityList, targetClass);
}
/**
* 设置排序
*
* @param queryWrapper 查询 Wrapper
* @param sortQuery 排序查询条件
*/
protected void sort(QueryWrapper<T> queryWrapper, SortQuery sortQuery) {
Sort sort = Opt.ofNullable(sortQuery).orElseGet(SortQuery::new).getSort();
for (Sort.Order order : sort) {
if (null != order) {
queryWrapper.orderBy(true, order.isAscending(), StrUtil.toUnderlineCase(order.getProperty()));
}
}
}
@Override
public D get(Long id) {
T entity = this.getById(id);
D detail = BeanUtil.copyProperties(entity, detailClass);
this.fillDetail(detail);
return detail;
}
@Override
public Long add(C req) {
if (null == req) {
return 0L;
}
T entity = BeanUtil.copyProperties(req, entityClass);
baseMapper.insert(entity);
return entity.getId();
}
@Override
public void update(C req, Long id) {
T entity = this.getById(id);
BeanUtil.copyProperties(req, entity, CopyOptions.create().ignoreNullValue());
baseMapper.updateById(entity);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(List<Long> ids) {
baseMapper.deleteBatchIds(ids);
}
@Override
public void export(Q query, SortQuery sortQuery, HttpServletResponse response) {
List<D> list = this.list(query, sortQuery, detailClass);
list.forEach(this::fillDetail);
ExcelUtils.export(list, "导出数据", detailClass, response);
}
/**
* 根据 ID 查询
*
* @param id ID
* @return 实体信息
*/
protected T getById(Object id) {
T entity = baseMapper.selectById(Convert.toStr(id)); | CheckUtils.throwIfNotExists(entity, ClassUtil.getClassName(entityClass, true), "ID", id); | 2 | 2023-11-16 15:48:18+00:00 | 12k |
xIdentified/Devotions | src/main/java/me/xidentified/devotions/storage/ShrineStorage.java | [
{
"identifier": "Deity",
"path": "src/main/java/me/xidentified/devotions/Deity.java",
"snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm... | import me.xidentified.devotions.Deity;
import me.xidentified.devotions.Devotions;
import me.xidentified.devotions.Shrine;
import me.xidentified.devotions.managers.DevotionManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | 9,007 | package me.xidentified.devotions.storage;
public class ShrineStorage {
private final Devotions plugin;
private final File shrineFile;
private final YamlConfiguration yaml;
public ShrineStorage(Devotions plugin, StorageManager storageManager) {
this.plugin = plugin;
shrineFile = new File(storageManager.getStorageFolder(), "shrines.yml");
if (!shrineFile.exists()) {
try {
shrineFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
yaml = YamlConfiguration.loadConfiguration(shrineFile);
}
public void saveShrine(Shrine shrine) {
String key = generateShrineKey(shrine);
String deityName = shrine.getDeity().getName();
// Save the shrine details in a single line format
yaml.set("shrines." + key, deityName);
save();
}
public void removeShrine(Location location, UUID ownerUUID) {
String key = findKeyByLocationAndOwner(location, ownerUUID);
if (key != null) {
yaml.set("shrines." + key, null);
save();
}
}
private String generateShrineKey(Shrine shrine) {
Location location = shrine.getLocation();
UUID ownerUUID = shrine.getOwner();
return location.getWorld().getName() + "," +
location.getBlockX() + "," +
location.getBlockY() + "," +
location.getBlockZ() + "," +
ownerUUID.toString();
}
private String findKeyByLocationAndOwner(Location location, UUID ownerUUID) {
ConfigurationSection shrinesSection = yaml.getConfigurationSection("shrines");
if (shrinesSection == null) return null;
for (String key : shrinesSection.getKeys(false)) {
String[] parts = key.split(",");
if (parts.length < 5) continue; // Skip if the format is incorrect
World world = Bukkit.getWorld(parts[0]);
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
UUID storedOwnerUUID = UUID.fromString(parts[4]);
Location storedLocation = new Location(world, x, y, z);
if (storedLocation.equals(location) && storedOwnerUUID.equals(ownerUUID)) {
return key;
}
}
return null;
}
| package me.xidentified.devotions.storage;
public class ShrineStorage {
private final Devotions plugin;
private final File shrineFile;
private final YamlConfiguration yaml;
public ShrineStorage(Devotions plugin, StorageManager storageManager) {
this.plugin = plugin;
shrineFile = new File(storageManager.getStorageFolder(), "shrines.yml");
if (!shrineFile.exists()) {
try {
shrineFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
yaml = YamlConfiguration.loadConfiguration(shrineFile);
}
public void saveShrine(Shrine shrine) {
String key = generateShrineKey(shrine);
String deityName = shrine.getDeity().getName();
// Save the shrine details in a single line format
yaml.set("shrines." + key, deityName);
save();
}
public void removeShrine(Location location, UUID ownerUUID) {
String key = findKeyByLocationAndOwner(location, ownerUUID);
if (key != null) {
yaml.set("shrines." + key, null);
save();
}
}
private String generateShrineKey(Shrine shrine) {
Location location = shrine.getLocation();
UUID ownerUUID = shrine.getOwner();
return location.getWorld().getName() + "," +
location.getBlockX() + "," +
location.getBlockY() + "," +
location.getBlockZ() + "," +
ownerUUID.toString();
}
private String findKeyByLocationAndOwner(Location location, UUID ownerUUID) {
ConfigurationSection shrinesSection = yaml.getConfigurationSection("shrines");
if (shrinesSection == null) return null;
for (String key : shrinesSection.getKeys(false)) {
String[] parts = key.split(",");
if (parts.length < 5) continue; // Skip if the format is incorrect
World world = Bukkit.getWorld(parts[0]);
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
UUID storedOwnerUUID = UUID.fromString(parts[4]);
Location storedLocation = new Location(world, x, y, z);
if (storedLocation.equals(location) && storedOwnerUUID.equals(ownerUUID)) {
return key;
}
}
return null;
}
| public List<Shrine> loadAllShrines(DevotionManager devotionManager) { | 3 | 2023-11-10 07:03:24+00:00 | 12k |
SplitfireUptown/datalinkx | flinkx/flinkx-kafkacustom/flinkx-kafkacustom-reader/src/main/java/com/dtstack/flinkx/kafkacustom/format/KafkacustomInputFormat.java | [
{
"identifier": "ConstantValue",
"path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/constants/ConstantValue.java",
"snippet": "public class ConstantValue {\n\n public static final String STAR_SYMBOL = \"*\";\n public static final String POINT_SYMBOL = \".\";\n public static final Stri... | import com.dtstack.flinkx.constants.ConstantValue;
import com.dtstack.flinkx.kafkacustom.client.KafkacustomConsumer;
import com.dtstack.flinkx.kafkabase.KafkaInputSplit;
import com.dtstack.flinkx.kafkabase.entity.kafkaState;
import com.dtstack.flinkx.kafkabase.enums.KafkaVersion;
import com.dtstack.flinkx.kafkabase.enums.StartupMode;
import com.dtstack.flinkx.kafkabase.format.KafkaBaseInputFormat;
import com.dtstack.flinkx.kafkabase.util.KafkaUtil;
import com.dtstack.flinkx.reader.MetaColumn;
import com.dtstack.flinkx.restore.FormatState;
import com.dtstack.flinkx.util.RangeSplitUtil;
import com.dtstack.flinkx.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.flink.core.io.InputSplit;
import org.apache.flink.types.Row;
import org.apache.kafka.common.PartitionInfo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties; | 9,999 | /*
* 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 com.dtstack.flinkx.kafkacustom.format;
//import com.dtstack.flinkx.util.ProtoBufUtil;
/**
* Date: 2019/11/21
* Company: www.dtstack.com
*
* @author tudou
*/
public class KafkacustomInputFormat extends KafkaBaseInputFormat {
@Override
protected InputSplit[] createInputSplitsInternal(int minNumSplits) {
List<kafkaState> stateList = new ArrayList<>();
org.apache.kafka.clients.consumer.KafkaConsumer<String, String> consumer = new org.apache.kafka.clients.consumer.KafkaConsumer<>(KafkaUtil.geneConsumerProp(consumerSettings, mode));
if(StartupMode.TIMESTAMP.equals(mode)){
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic);
for (PartitionInfo p : partitionInfoList) {
stateList.add(new kafkaState(p.topic(), p.partition(), null, timestamp));
}
}else if(StartupMode.SPECIFIC_OFFSETS.equals(mode)){
stateList = KafkaUtil.parseSpecificOffsetsString(topic, offset);
}else{
String[] topics = topic.split(ConstantValue.COMMA_SYMBOL);
if(topics.length == 1){
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic);
for (PartitionInfo p : partitionInfoList) {
stateList.add(new kafkaState(p.topic(), p.partition(), null, null));
}
}else{
for (String tp : topics) {
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(tp);
for (PartitionInfo p : partitionInfoList) {
stateList.add(new kafkaState(p.topic(), p.partition(), null, null));
}
}
}
}
List<List<kafkaState>> list = RangeSplitUtil.subListBySegment(stateList, minNumSplits);
InputSplit[] splits = new InputSplit[minNumSplits];
for (int i = 0; i < minNumSplits; i++) {
splits[i] = new KafkaInputSplit(i, list.get(i));
}
return splits;
}
@Override
public void openInputFormat() throws IOException {
super.openInputFormat();
Properties props = KafkaUtil.geneConsumerProp(consumerSettings, mode); | /*
* 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 com.dtstack.flinkx.kafkacustom.format;
//import com.dtstack.flinkx.util.ProtoBufUtil;
/**
* Date: 2019/11/21
* Company: www.dtstack.com
*
* @author tudou
*/
public class KafkacustomInputFormat extends KafkaBaseInputFormat {
@Override
protected InputSplit[] createInputSplitsInternal(int minNumSplits) {
List<kafkaState> stateList = new ArrayList<>();
org.apache.kafka.clients.consumer.KafkaConsumer<String, String> consumer = new org.apache.kafka.clients.consumer.KafkaConsumer<>(KafkaUtil.geneConsumerProp(consumerSettings, mode));
if(StartupMode.TIMESTAMP.equals(mode)){
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic);
for (PartitionInfo p : partitionInfoList) {
stateList.add(new kafkaState(p.topic(), p.partition(), null, timestamp));
}
}else if(StartupMode.SPECIFIC_OFFSETS.equals(mode)){
stateList = KafkaUtil.parseSpecificOffsetsString(topic, offset);
}else{
String[] topics = topic.split(ConstantValue.COMMA_SYMBOL);
if(topics.length == 1){
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(topic);
for (PartitionInfo p : partitionInfoList) {
stateList.add(new kafkaState(p.topic(), p.partition(), null, null));
}
}else{
for (String tp : topics) {
List<PartitionInfo> partitionInfoList = consumer.partitionsFor(tp);
for (PartitionInfo p : partitionInfoList) {
stateList.add(new kafkaState(p.topic(), p.partition(), null, null));
}
}
}
}
List<List<kafkaState>> list = RangeSplitUtil.subListBySegment(stateList, minNumSplits);
InputSplit[] splits = new InputSplit[minNumSplits];
for (int i = 0; i < minNumSplits; i++) {
splits[i] = new KafkaInputSplit(i, list.get(i));
}
return splits;
}
@Override
public void openInputFormat() throws IOException {
super.openInputFormat();
Properties props = KafkaUtil.geneConsumerProp(consumerSettings, mode); | consumer = new KafkacustomConsumer(props); | 1 | 2023-11-16 02:22:52+00:00 | 12k |
12manel123/tsys-my-food-api-1011 | src/main/java/com/myfood/controllers/OrderController.java | [
{
"identifier": "Dish",
"path": "src/main/java/com/myfood/dto/Dish.java",
"snippet": "@Entity\n@Table(name = \"dishes\")\npublic class Dish {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n\t@Column(name = \"name\", nullable =... | import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Pageable;
import com.myfood.dto.Dish;
import com.myfood.dto.ListOrder;
import com.myfood.dto.Order;
import com.myfood.dto.OrderCookDTO;
import com.myfood.dto.OrderUserDTO;
import com.myfood.dto.Slot;
import com.myfood.dto.User;
import com.myfood.services.OrderServiceImpl;
import com.myfood.services.SlotServiceImpl;
import com.myfood.services.UserServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.transaction.Transactional; | 7,855 | package com.myfood.controllers;
@RestController
@RequestMapping("api/v1")
public class OrderController {
@Autowired
private OrderServiceImpl orderService;
@Autowired
private SlotServiceImpl slotService;
@Autowired
private UserServiceImpl userService;
/**
* Retrieves a paginated list of user orders with Dishes. It's for the ADMIN
*
* @param page The page number (default is 0).
* @param size The number of orders per page (default is 10).
* @return ResponseEntity containing a paginated list of {@link OrderUserDTO}.
* @see OrderService#getAllOrdersWithPagination(Pageable)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersWithDish(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrders();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
/**
* Retrieves details of a specific order identified by its ID. It's for the ADMIN
*
* @param id The unique identifier of the order.
* @return ResponseEntity containing the details of the order as an {@link OrderUserDTO}.
* @throws DataNotFoundException If the specified order does not exist.
* @see OrderService#getOneOrder(Long)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/order/{id}")
public ResponseEntity<?> getOneOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate());
return ResponseEntity.ok(orderUserDTO);
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Creates a new order based on the provided order details. It's for the ADMIN
*
* @param entity The order details provided in the request body.
* @return ResponseEntity containing the details of the created order as an {@link OrderUserDTO}.
* {@link OrderUserDTO} and returned in the ResponseEntity with status 200 (OK).
* @see OrderService#createOrder(Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/order")
public ResponseEntity<OrderUserDTO> saveOrder(@RequestBody Order entity) {
Order savedOrder = orderService.createOrder(entity);
OrderUserDTO orderUserDTO = new OrderUserDTO(savedOrder.getId(), savedOrder.isMaked(), savedOrder.getSlot(),savedOrder.getTotalPrice(),savedOrder.getActualDate());
return ResponseEntity.ok(orderUserDTO);
}
/**
* Updates an existing order with the provided order details. It's for ADMIN
*
* @param id The identifier of the order to be updated.
* @param entity The updated order details provided in the request body.
* @return ResponseEntity containing a message and the details of the updated
* order as an {@link OrderUserDTO}.
* @see OrderService#getOneOrder(Long)
* @see OrderService#updateOrder(Long, Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PutMapping("/order/{id}")
public ResponseEntity<?> updateOrder(@PathVariable(name = "id") Long id, @RequestBody Order entity) {
Optional<Order> entityOld = orderService.getOneOrder(id);
if (entityOld.isPresent()) {
return ResponseEntity.ok(Map.of("Message", "Updated order", "order",
new OrderUserDTO(id, entity.isMaked(), entity.getSlot(),entity.getTotalPrice(),entity.getActualDate())));
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Deletes an existing order based on the provided order ID. It's for ADMIN
*
* @param id The identifier of the order to be deleted.
* @return ResponseEntity indicating the success or failure of the delete operation.
* @see OrderService#getOneOrder(Long)
* @see OrderService#deleteOrder(Long)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/order/{id}")
public ResponseEntity<?> deleteOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
order.setActualDate(null);
order.setSlot(null);
orderService.deleteOrder(id);
return ResponseEntity.status(204).body(Map.of("Message", "Order deleted"));
} else {
return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST);
}
}
/**
* Retrieves a paginated list of orders suitable for a cook, including
* associated dishes. It's for CHEF
*
* @param page The page number for pagination (default is 0).
* @param size The number of orders per page (default is 8).
* @return ResponseEntity containing a paginated list of OrderCookDTO objects.
* @see OrderService#getAllOrdersForCook()
* @see OrderController#mapToOrderCookDTO(Order)
* @see OrderController#paginate(List, Pageable)
* @see OrderCookDTO
*/
@Transactional
@Operation(summary = "Endpoint for CHEF and ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders/chef")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersForChef(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrdersForCook();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
private OrderCookDTO mapToOrderCookDTOWithDishes(Order order) {
OrderCookDTO orderCookDTO = new OrderCookDTO();
orderCookDTO.setOrderId(order.getId());
orderCookDTO.setMaked(order.isMaked());
orderCookDTO.setSlot(order.getSlot());
orderCookDTO.setActualDate(order.getActualDate());
orderCookDTO.setTotalPrice(order.getTotalPrice()); | package com.myfood.controllers;
@RestController
@RequestMapping("api/v1")
public class OrderController {
@Autowired
private OrderServiceImpl orderService;
@Autowired
private SlotServiceImpl slotService;
@Autowired
private UserServiceImpl userService;
/**
* Retrieves a paginated list of user orders with Dishes. It's for the ADMIN
*
* @param page The page number (default is 0).
* @param size The number of orders per page (default is 10).
* @return ResponseEntity containing a paginated list of {@link OrderUserDTO}.
* @see OrderService#getAllOrdersWithPagination(Pageable)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersWithDish(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrders();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
/**
* Retrieves details of a specific order identified by its ID. It's for the ADMIN
*
* @param id The unique identifier of the order.
* @return ResponseEntity containing the details of the order as an {@link OrderUserDTO}.
* @throws DataNotFoundException If the specified order does not exist.
* @see OrderService#getOneOrder(Long)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/order/{id}")
public ResponseEntity<?> getOneOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate());
return ResponseEntity.ok(orderUserDTO);
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Creates a new order based on the provided order details. It's for the ADMIN
*
* @param entity The order details provided in the request body.
* @return ResponseEntity containing the details of the created order as an {@link OrderUserDTO}.
* {@link OrderUserDTO} and returned in the ResponseEntity with status 200 (OK).
* @see OrderService#createOrder(Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/order")
public ResponseEntity<OrderUserDTO> saveOrder(@RequestBody Order entity) {
Order savedOrder = orderService.createOrder(entity);
OrderUserDTO orderUserDTO = new OrderUserDTO(savedOrder.getId(), savedOrder.isMaked(), savedOrder.getSlot(),savedOrder.getTotalPrice(),savedOrder.getActualDate());
return ResponseEntity.ok(orderUserDTO);
}
/**
* Updates an existing order with the provided order details. It's for ADMIN
*
* @param id The identifier of the order to be updated.
* @param entity The updated order details provided in the request body.
* @return ResponseEntity containing a message and the details of the updated
* order as an {@link OrderUserDTO}.
* @see OrderService#getOneOrder(Long)
* @see OrderService#updateOrder(Long, Order)
*/
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@PutMapping("/order/{id}")
public ResponseEntity<?> updateOrder(@PathVariable(name = "id") Long id, @RequestBody Order entity) {
Optional<Order> entityOld = orderService.getOneOrder(id);
if (entityOld.isPresent()) {
return ResponseEntity.ok(Map.of("Message", "Updated order", "order",
new OrderUserDTO(id, entity.isMaked(), entity.getSlot(),entity.getTotalPrice(),entity.getActualDate())));
} else {
return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND);
}
}
/**
* Deletes an existing order based on the provided order ID. It's for ADMIN
*
* @param id The identifier of the order to be deleted.
* @return ResponseEntity indicating the success or failure of the delete operation.
* @see OrderService#getOneOrder(Long)
* @see OrderService#deleteOrder(Long)
*/
@Transactional
@Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@PreAuthorize("hasRole('ADMIN')")
@DeleteMapping("/order/{id}")
public ResponseEntity<?> deleteOrder(@PathVariable(name = "id") Long id) {
Optional<Order> entity = orderService.getOneOrder(id);
if (entity.isPresent()) {
Order order = entity.get();
order.setActualDate(null);
order.setSlot(null);
orderService.deleteOrder(id);
return ResponseEntity.status(204).body(Map.of("Message", "Order deleted"));
} else {
return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST);
}
}
/**
* Retrieves a paginated list of orders suitable for a cook, including
* associated dishes. It's for CHEF
*
* @param page The page number for pagination (default is 0).
* @param size The number of orders per page (default is 8).
* @return ResponseEntity containing a paginated list of OrderCookDTO objects.
* @see OrderService#getAllOrdersForCook()
* @see OrderController#mapToOrderCookDTO(Order)
* @see OrderController#paginate(List, Pageable)
* @see OrderCookDTO
*/
@Transactional
@Operation(summary = "Endpoint for CHEF and ADMIN", security = @SecurityRequirement(name = "bearerAuth"))
@GetMapping("/orders/chef")
public ResponseEntity<Page<OrderCookDTO>> getAllOrdersForChef(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "8") int size) {
List<Order> ordersForCook = orderService.getAllOrdersForCook();
List<Order> filteredOrders = ordersForCook.stream()
.filter(order -> order.getActualDate() != null)
.collect(Collectors.toList());
Pageable pageable = PageRequest.of(page, size);
Page<Order> paginatedOrders = paginate(filteredOrders, pageable);
List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream()
.map(this::mapToOrderCookDTOWithDishes)
.collect(Collectors.toList());
return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size()));
}
private OrderCookDTO mapToOrderCookDTOWithDishes(Order order) {
OrderCookDTO orderCookDTO = new OrderCookDTO();
orderCookDTO.setOrderId(order.getId());
orderCookDTO.setMaked(order.isMaked());
orderCookDTO.setSlot(order.getSlot());
orderCookDTO.setActualDate(order.getActualDate());
orderCookDTO.setTotalPrice(order.getTotalPrice()); | List<ListOrder> listOrders = order.getListOrder(); | 1 | 2023-11-10 16:09:43+00:00 | 12k |
kotmatross28729/EnviroMine-continuation | src/main/java/enviromine/client/gui/SaveController.java | [
{
"identifier": "HUDRegistry",
"path": "src/main/java/enviromine/client/gui/hud/HUDRegistry.java",
"snippet": "public class HUDRegistry {\n protected static List<HudItem> hudItemList = new ArrayList<HudItem>();\n protected static boolean initialLoadComplete = false;\n protected static List<HudI... | import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import enviromine.client.gui.hud.HUDRegistry;
import enviromine.client.gui.hud.HudItem;
import enviromine.core.EM_ConfigHandler.EnumLogVerbosity;
import enviromine.core.EM_Settings;
import enviromine.core.EnviroMine;
import net.minecraft.client.Minecraft;
import net.minecraft.crash.CrashReport;
import net.minecraft.nbt.CompressedStreamTools;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ReportedException; | 8,118 | package enviromine.client.gui;
@SideOnly(Side.CLIENT)
public class SaveController {
/**
* Configuration version number. If changed the version file will be reset to defaults to prevent glitches
*/
static final String CONFIG_VERSION = "1.0.0";
/**
* The version of the configs last loaded from file. This will be compared to the version number above when determining whether a reset is necessary
*/
static String LOADED_VERSION = "1.0.0";
protected static final String dirName = Minecraft.getMinecraft().mcDataDir + File.separator + "config" + File.separator + "enviromine";
protected static File dir = new File(dirName);
public static String UISettingsData = "UI_Settings";
public static boolean loadConfig(String name) {
return loadConfig(name, null);
}
public static boolean loadConfig(String name, String dirName) {
if (dirName != null) {
dir = new File(Minecraft.getMinecraft().mcDataDir + File.separator + dirName);
}
String fileName = name + ".dat";
File file = new File(dir, fileName);
if (!file.exists())
{
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.warn("Config load canceled, file ("+ file.getAbsolutePath() +") does not exist. This is normal for first run.");
return false;
} else {
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.info("Config load successful.");
}
try {
NBTTagCompound nbt = CompressedStreamTools.readCompressed(new FileInputStream(file));
if (nbt.hasNoTags() || !nbt.hasKey(UISettingsData))
{
return false;
}
UI_Settings.readFromNBT(nbt.getCompoundTag(UISettingsData));
HUDRegistry.readFromNBT(nbt.getCompoundTag(UISettingsData));
LOADED_VERSION = nbt.getCompoundTag(UISettingsData).getString("CONFIG_VERSION");
//UpdateNotification.readFromNBT(nbt.getCompoundTag("Notifications"));
// New HUD Settings will be here
| package enviromine.client.gui;
@SideOnly(Side.CLIENT)
public class SaveController {
/**
* Configuration version number. If changed the version file will be reset to defaults to prevent glitches
*/
static final String CONFIG_VERSION = "1.0.0";
/**
* The version of the configs last loaded from file. This will be compared to the version number above when determining whether a reset is necessary
*/
static String LOADED_VERSION = "1.0.0";
protected static final String dirName = Minecraft.getMinecraft().mcDataDir + File.separator + "config" + File.separator + "enviromine";
protected static File dir = new File(dirName);
public static String UISettingsData = "UI_Settings";
public static boolean loadConfig(String name) {
return loadConfig(name, null);
}
public static boolean loadConfig(String name, String dirName) {
if (dirName != null) {
dir = new File(Minecraft.getMinecraft().mcDataDir + File.separator + dirName);
}
String fileName = name + ".dat";
File file = new File(dir, fileName);
if (!file.exists())
{
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.warn("Config load canceled, file ("+ file.getAbsolutePath() +") does not exist. This is normal for first run.");
return false;
} else {
if (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.info("Config load successful.");
}
try {
NBTTagCompound nbt = CompressedStreamTools.readCompressed(new FileInputStream(file));
if (nbt.hasNoTags() || !nbt.hasKey(UISettingsData))
{
return false;
}
UI_Settings.readFromNBT(nbt.getCompoundTag(UISettingsData));
HUDRegistry.readFromNBT(nbt.getCompoundTag(UISettingsData));
LOADED_VERSION = nbt.getCompoundTag(UISettingsData).getString("CONFIG_VERSION");
//UpdateNotification.readFromNBT(nbt.getCompoundTag("Notifications"));
// New HUD Settings will be here
| for (HudItem item : HUDRegistry.getHudItemList()) { | 1 | 2023-11-16 18:15:29+00:00 | 12k |
spring-projects/spring-rewrite-commons | spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/RewriteProjectParserIntegrationTest.java | [
{
"identifier": "SbmSupportRewriteConfiguration",
"path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/boot/autoconfigure/SbmSupportRewriteConfiguration.java",
"snippet": "@AutoConfiguration\n@Import({ RecipeDiscoveryConfiguration.class, RewriteParserConfiguration.class, Pr... | import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junitpioneer.jupiter.Issue;
import org.openrewrite.java.tree.J;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.rewrite.boot.autoconfigure.SbmSupportRewriteConfiguration;
import org.springframework.rewrite.parsers.maven.RewriteMavenProjectParser;
import org.springframework.rewrite.parsers.maven.SbmTestConfiguration;
import org.springframework.rewrite.test.util.ParserParityTestHelper;
import org.springframework.rewrite.test.util.TestProjectHelper;
import java.nio.file.Path; | 7,277 | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.rewrite.parsers;
/**
* @author Fabian Krüger
*/
@DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.")
@Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12")
@SpringBootTest(classes = { SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class })
public class RewriteProjectParserIntegrationTest {
@Autowired
RewriteProjectParser sut;
@Autowired
ProjectScanner projectScanner;
@Autowired
RewriteMavenProjectParser mavenProjectParser;
@Test
@DisplayName("testFailingProject")
void testFailingProject() {
Path baseDir = Path.of("./testcode/maven-projects/failing");
ParserParityTestHelper.scanProjectDir(baseDir).verifyParity((comparingParsingResult, testedParsingResult) -> {
assertThat(comparingParsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class);
J.CompilationUnit cu = (J.CompilationUnit) comparingParsingResult.sourceFiles().get(1);
assertThat(cu.getTypesInUse()
.getTypesInUse()
.stream()
.map(t -> t.toString())
.anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue();
assertThat(testedParsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class);
J.CompilationUnit cu2 = (J.CompilationUnit) testedParsingResult.sourceFiles().get(1);
assertThat(cu2.getTypesInUse()
.getTypesInUse()
.stream()
.map(t -> t.toString())
.anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue();
});
}
@Test
@DisplayName("parseResources")
void parseResources() { | /*
* Copyright 2021 - 2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.springframework.rewrite.parsers;
/**
* @author Fabian Krüger
*/
@DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.")
@Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12")
@SpringBootTest(classes = { SbmSupportRewriteConfiguration.class, SbmTestConfiguration.class })
public class RewriteProjectParserIntegrationTest {
@Autowired
RewriteProjectParser sut;
@Autowired
ProjectScanner projectScanner;
@Autowired
RewriteMavenProjectParser mavenProjectParser;
@Test
@DisplayName("testFailingProject")
void testFailingProject() {
Path baseDir = Path.of("./testcode/maven-projects/failing");
ParserParityTestHelper.scanProjectDir(baseDir).verifyParity((comparingParsingResult, testedParsingResult) -> {
assertThat(comparingParsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class);
J.CompilationUnit cu = (J.CompilationUnit) comparingParsingResult.sourceFiles().get(1);
assertThat(cu.getTypesInUse()
.getTypesInUse()
.stream()
.map(t -> t.toString())
.anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue();
assertThat(testedParsingResult.sourceFiles().get(1)).isInstanceOf(J.CompilationUnit.class);
J.CompilationUnit cu2 = (J.CompilationUnit) testedParsingResult.sourceFiles().get(1);
assertThat(cu2.getTypesInUse()
.getTypesInUse()
.stream()
.map(t -> t.toString())
.anyMatch(t -> t.equals("javax.validation.constraints.Min"))).isTrue();
});
}
@Test
@DisplayName("parseResources")
void parseResources() { | Path baseDir = TestProjectHelper.getMavenProject("resources"); | 4 | 2023-11-14 23:02:37+00:00 | 12k |
exadel-inc/etoolbox-anydiff | core/src/main/java/com/exadel/etoolbox/anydiff/AnyDiff.java | [
{
"identifier": "TaskParameters",
"path": "core/src/main/java/com/exadel/etoolbox/anydiff/comparison/TaskParameters.java",
"snippet": "@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@Builder(builderClassName = \"Builder\")\npublic class TaskParameters {\n\n private static final TaskParameters FOR... | import com.exadel.etoolbox.anydiff.comparison.TaskParameters;
import com.exadel.etoolbox.anydiff.diff.Diff;
import com.exadel.etoolbox.anydiff.diff.DiffEntry;
import com.exadel.etoolbox.anydiff.filter.Filter;
import com.exadel.etoolbox.anydiff.runner.DiffRunner;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | 7,516 | /*
* 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.exadel.etoolbox.anydiff;
/**
* Compares two sets of values and returns a list of differences
* @see Diff
* @see DiffEntry
* @see Filter
*/
public class AnyDiff {
private String[] leftStrings;
private Path[] leftPaths;
private String leftLabel;
private String[] rightStrings;
private Path[] rightPaths;
private String rightLabel;
private Boolean arrangeAttributes;
private ContentType contentType;
private Integer columnWidth;
private Boolean ignoreSpaces;
private Boolean normalize;
private List<Filter> filters;
/* -------
Strings
------- */
// Left
/**
* Assigns the left side of the comparison
* @param value The left-side value to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff left(String value) {
if (value == null) {
return this;
}
return left(new String[]{value});
}
/**
* Assigns the left side of the comparison
* @param value The left-side strings to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff left(String[] value) {
return left(value, null);
}
/**
* Assigns the left side of the comparison
* @param value The left-side strings to compare. Can represent either a simple text, a path, or an URI
* @param label The label to use for the left side of the comparison in the report
* @return This instance
*/
public AnyDiff left(String[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
leftStrings = value;
leftLabel = label;
return this;
}
// Right
/**
* Assigns the right side of the comparison
* @param value The right-side value to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff right(String value) {
if (value == null) {
return this;
}
return right(new String[] {value});
}
/**
* Assigns the right side of the comparison
* @param value The right-side strings to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff right(String[] value) {
return right(value, null);
}
/**
* Assigns the right side of the comparison
* @param value The right-side strings to compare. Can represent either a simple text, a path, or an URI
* @param label The label to use for the right side of the comparison in the report
* @return This instance
*/
public AnyDiff right(String[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
rightStrings = value;
rightLabel = label;
return this;
}
/* -----
Paths
----- */
// Left
/**
* Assigns the left side of the comparison
* @param value A {@link Path} that represents the left-side data to compare
* @param label The label to use for the left side of the comparison in the report
* @return This instance
*/
public AnyDiff left(Path value, String label) {
if (value == null) {
return this;
}
return left(new Path[] {value}, label);
}
/**
* Assigns the left side of the comparison
* @param value An array of {@link Path} objects that represent the left-side data to compare
* @param label The label to use for the left side of the comparison in the report
* @return This instance
*/
public AnyDiff left(Path[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
leftPaths = value;
leftLabel = label;
return this;
}
// Right
/**
* Assigns the right side of the comparison
* @param value A {@link Path} that represents the right-side data to compare
* @param label The label to use for the right side of the comparison in the report
* @return This instance
*/
public AnyDiff right(Path value, String label) {
if (value == null) {
return this;
}
return right(new Path[] {value}, label);
}
/**
* Assigns the right side of the comparison
* @param value An array of {@link Path} objects that represent the right-side data to compare
* @param label The label to use for the right side of the comparison in the report
* @return This instance
*/
public AnyDiff right(Path[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
rightPaths = value;
rightLabel = label;
return this;
}
/* -------
Filters
------- */
/**
* Assigns a {@link Filter} to the comparison
* @param value A {@code Filter} object to use for the comparison
* @return This instance
*/
public AnyDiff filter(Filter value) {
return filter(Collections.singletonList(value));
}
/**
* Assigns a list of {@link Filter} objects to the comparison
* @param value A list of {@code Filter} objects to use for the comparison
* @return This instance
*/
public AnyDiff filter(List<Filter> value) {
if (CollectionUtils.isEmpty(value)) {
return this;
}
if (filters == null) {
filters = new ArrayList<>();
}
filters.addAll(value);
return this;
}
/* --------------
Misc arguments
-------------- */
/**
* Assigns the flag telling whether to arrange tag attributes of markup content before comparison for more accurate
* results
* @param value Boolean value
* @return This instance
*/
public AnyDiff arrangeAttributes(boolean value) {
this.arrangeAttributes = value;
return this;
}
/**
* Assigns the content type to use for the comparison
* @param value A {@link ContentType} value to use for the comparison
* @return This instance
*/
public AnyDiff contentType(ContentType value) {
this.contentType = value;
return this;
}
/**
* Assigns the column width to use for the comparison reports
* @param value A positive integer value
* @return This instance
*/
public AnyDiff columnWidth(int value) {
this.columnWidth = value;
return this;
}
/**
* Assigns the flag telling whether to ignore spaces between words in comparison
* @param value Boolean value
* @return This instance
*/
public AnyDiff ignoreSpaces(boolean value) {
this.ignoreSpaces = value;
return this;
}
/**
* Assigns the flag telling whether to normalize markup content before comparison for more granular results
* @param value Boolean value
* @return This instance
*/
public AnyDiff normalize(boolean value) {
this.normalize = value;
return this;
}
/* -------
Actions
------- */
/**
* Performs the comparison
* @return A list of {@link Diff} objects that represent the differences between the left and right sides of the
* comparison. Can be empty but not {@code null}
*/
public List<Diff> compare() { | /*
* 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.exadel.etoolbox.anydiff;
/**
* Compares two sets of values and returns a list of differences
* @see Diff
* @see DiffEntry
* @see Filter
*/
public class AnyDiff {
private String[] leftStrings;
private Path[] leftPaths;
private String leftLabel;
private String[] rightStrings;
private Path[] rightPaths;
private String rightLabel;
private Boolean arrangeAttributes;
private ContentType contentType;
private Integer columnWidth;
private Boolean ignoreSpaces;
private Boolean normalize;
private List<Filter> filters;
/* -------
Strings
------- */
// Left
/**
* Assigns the left side of the comparison
* @param value The left-side value to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff left(String value) {
if (value == null) {
return this;
}
return left(new String[]{value});
}
/**
* Assigns the left side of the comparison
* @param value The left-side strings to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff left(String[] value) {
return left(value, null);
}
/**
* Assigns the left side of the comparison
* @param value The left-side strings to compare. Can represent either a simple text, a path, or an URI
* @param label The label to use for the left side of the comparison in the report
* @return This instance
*/
public AnyDiff left(String[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
leftStrings = value;
leftLabel = label;
return this;
}
// Right
/**
* Assigns the right side of the comparison
* @param value The right-side value to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff right(String value) {
if (value == null) {
return this;
}
return right(new String[] {value});
}
/**
* Assigns the right side of the comparison
* @param value The right-side strings to compare. Can represent either a simple text, a path, or an URI
* @return This instance
*/
public AnyDiff right(String[] value) {
return right(value, null);
}
/**
* Assigns the right side of the comparison
* @param value The right-side strings to compare. Can represent either a simple text, a path, or an URI
* @param label The label to use for the right side of the comparison in the report
* @return This instance
*/
public AnyDiff right(String[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
rightStrings = value;
rightLabel = label;
return this;
}
/* -----
Paths
----- */
// Left
/**
* Assigns the left side of the comparison
* @param value A {@link Path} that represents the left-side data to compare
* @param label The label to use for the left side of the comparison in the report
* @return This instance
*/
public AnyDiff left(Path value, String label) {
if (value == null) {
return this;
}
return left(new Path[] {value}, label);
}
/**
* Assigns the left side of the comparison
* @param value An array of {@link Path} objects that represent the left-side data to compare
* @param label The label to use for the left side of the comparison in the report
* @return This instance
*/
public AnyDiff left(Path[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
leftPaths = value;
leftLabel = label;
return this;
}
// Right
/**
* Assigns the right side of the comparison
* @param value A {@link Path} that represents the right-side data to compare
* @param label The label to use for the right side of the comparison in the report
* @return This instance
*/
public AnyDiff right(Path value, String label) {
if (value == null) {
return this;
}
return right(new Path[] {value}, label);
}
/**
* Assigns the right side of the comparison
* @param value An array of {@link Path} objects that represent the right-side data to compare
* @param label The label to use for the right side of the comparison in the report
* @return This instance
*/
public AnyDiff right(Path[] value, String label) {
if (ArrayUtils.isEmpty(value)) {
return this;
}
rightPaths = value;
rightLabel = label;
return this;
}
/* -------
Filters
------- */
/**
* Assigns a {@link Filter} to the comparison
* @param value A {@code Filter} object to use for the comparison
* @return This instance
*/
public AnyDiff filter(Filter value) {
return filter(Collections.singletonList(value));
}
/**
* Assigns a list of {@link Filter} objects to the comparison
* @param value A list of {@code Filter} objects to use for the comparison
* @return This instance
*/
public AnyDiff filter(List<Filter> value) {
if (CollectionUtils.isEmpty(value)) {
return this;
}
if (filters == null) {
filters = new ArrayList<>();
}
filters.addAll(value);
return this;
}
/* --------------
Misc arguments
-------------- */
/**
* Assigns the flag telling whether to arrange tag attributes of markup content before comparison for more accurate
* results
* @param value Boolean value
* @return This instance
*/
public AnyDiff arrangeAttributes(boolean value) {
this.arrangeAttributes = value;
return this;
}
/**
* Assigns the content type to use for the comparison
* @param value A {@link ContentType} value to use for the comparison
* @return This instance
*/
public AnyDiff contentType(ContentType value) {
this.contentType = value;
return this;
}
/**
* Assigns the column width to use for the comparison reports
* @param value A positive integer value
* @return This instance
*/
public AnyDiff columnWidth(int value) {
this.columnWidth = value;
return this;
}
/**
* Assigns the flag telling whether to ignore spaces between words in comparison
* @param value Boolean value
* @return This instance
*/
public AnyDiff ignoreSpaces(boolean value) {
this.ignoreSpaces = value;
return this;
}
/**
* Assigns the flag telling whether to normalize markup content before comparison for more granular results
* @param value Boolean value
* @return This instance
*/
public AnyDiff normalize(boolean value) {
this.normalize = value;
return this;
}
/* -------
Actions
------- */
/**
* Performs the comparison
* @return A list of {@link Diff} objects that represent the differences between the left and right sides of the
* comparison. Can be empty but not {@code null}
*/
public List<Diff> compare() { | DiffRunner diffRunner = ArrayUtils.isNotEmpty(leftPaths) && ArrayUtils.isNotEmpty(rightPaths) | 4 | 2023-11-16 14:29:45+00:00 | 12k |
Walter-Stroebel/Jllama | src/main/java/nl/infcomtec/jllama/OllamaChatFrame.java | [
{
"identifier": "ImageObject",
"path": "src/main/java/nl/infcomtec/simpleimage/ImageObject.java",
"snippet": "public class ImageObject extends Image {\n\n private BufferedImage image;\n private final Semaphore lock = new Semaphore(0);\n private final List<ImageObjectListener> listeners = new Li... | import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import nl.infcomtec.simpleimage.ImageObject;
import nl.infcomtec.simpleimage.ImageViewer;
import nl.infcomtec.tools.PandocConverter; | 7,614 | Box bottom = Box.createHorizontalBox();
input.setLineWrap(true);
input.setWrapStyleWord(true);
bottom.add(new JScrollPane(input));
bottom.add(Box.createHorizontalStrut(10));
bottom.add(new JButton(new Interact()));
bottom.add(new JButton(new AbstractAction("\u2191 image") {
@Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedImage originalImage = ImageIO.read(selectedFile);
if (originalImage.getHeight() != 256 || originalImage.getWidth() != 256) {
Image scaledInstance = originalImage.getScaledInstance(256, 256, BufferedImage.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(scaledInstance, 0, 0, null);
g2d.dispose();
uplImage = resizedImage;
} else {
uplImage = originalImage;
}
updateSideBar(null);
} catch (IOException ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
uplImage = null;
}
}
}
}));
bottom.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(135, 206, 250), 5),
"Input"));
cont.add(bottom, BorderLayout.SOUTH);
cont.add(sideBar(), BorderLayout.EAST);
frame.pack();
if (EventQueue.isDispatchThread()) {
finishInit();
} else {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
finishInit();
}
});
} catch (Exception ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
}
private void buttonBar() {
buttons.add(new AbstractAction("Exit") {
@Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
buttons.add(new JToolBar.Separator());
String lsHost = Ollama.config.getLastEndpoint();
for (String e : Ollama.getAvailableModels().keySet()) {
addToHosts(e);
}
client = new OllamaClient(lsHost);
models.removeAllItems();
for (AvailableModels.AvailableModel am : Ollama.getAvailableModels().get(lsHost).models) {
models.addItem(am.name);
}
if (null != Ollama.config.lastModel) {
models.setSelectedItem(Ollama.config.lastModel);
}
models.invalidate();
hosts.setSelectedItem(lsHost);
hosts.addActionListener(new AddSelectHost());
hosts.setEditable(true);
buttons.add(new JLabel("Hosts:"));
buttons.add(hosts);
buttons.add(new JToolBar.Separator());
buttons.add(new JLabel("Models:"));
buttons.add(models);
buttons.add(new JToolBar.Separator());
buttons.add(new AbstractAction("HTML") {
@Override
public void actionPerformed(ActionEvent ae) {
String markDown = chat.getText();
JFrame html = new JFrame("HTML");
html.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
html.getContentPane().setLayout(new BorderLayout());
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
HTMLEditorKit kit = new HTMLEditorKit() {
@Override
public StyleSheet getStyleSheet() {
StyleSheet styleSheet = super.getStyleSheet();
styleSheet.addRule("body { font-family: 'Arial'; font-size: " + Math.round(Ollama.config.fontSize) + "pt; }");
return styleSheet;
}
};
pane.setEditorKit(kit);
pane.setText(new PandocConverter().convertMarkdownToHTML(markDown));
html.getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER);
html.pack();
html.setVisible(true);
}
});
buttons.add(new AbstractAction("Dall-E 3") {
@Override
public void actionPerformed(ActionEvent ae) {
try {
String text = chat.getSelectedText();
DallEClient dale = new DallEClient();
ImageObject io = new ImageObject(dale.getImage(text)); | package nl.infcomtec.jllama;
/**
* This is a FULL Ollama chat window. It allow to chat with any model available
* at will.<p>
* Note that this displays some extra information along with the actual chat
* which allows one to get a good insight in how the model performs.</p>
*
* @author Walter Stroebel
*/
public class OllamaChatFrame {
private final JFrame frame;
private final JToolBar buttons;
private final JTextArea chat;
private final JTextArea input;
private OllamaClient client;
private final JComboBox<String> hosts;
private final JComboBox<String> models;
private JLabel curCtxSize;
private JLabel outTokens;
private JLabel inTokens;
private final AtomicBoolean autoMode = new AtomicBoolean(false);
private final ExecutorService pool = Executors.newCachedThreadPool();
private JLabel tokensSec;
private JLabel modFamily;
private JLabel modFamilies;
private JLabel modFormat;
private JLabel modParmSize;
private JLabel modQuant;
private JLabel prevImage;
private BufferedImage uplImage;
/**
* Ties all the bits and pieces together into a GUI.
*/
public OllamaChatFrame() {
setupGUI(Ollama.config.fontSize);
this.modQuant = new JLabel();
this.modParmSize = new JLabel();
this.modFormat = new JLabel();
this.modFamilies = new JLabel();
this.modFamily = new JLabel();
this.prevImage = new JLabel();
this.models = new JComboBox<>();
this.hosts = new JComboBox<>();
this.buttons = new JToolBar();
this.input = new JTextArea(4, 80);
this.chat = new JTextArea();
frame = new JFrame("Ollama chat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont = frame.getContentPane();
cont.setLayout(new BorderLayout());
buttonBar();
cont.add(buttons, BorderLayout.NORTH);
chat.setLineWrap(true);
chat.setWrapStyleWord(true);
final JPopupMenu popupMenu = new JPopupMenu();
JMenuItem copy = new JMenuItem("Copy");
copy.addActionListener(new AbstractAction("Copy") {
@Override
public void actionPerformed(ActionEvent ae) {
String selectedText = chat.getSelectedText();
if (null != selectedText) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection(selectedText), null);
}
}
});
popupMenu.add(copy);
chat.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
JScrollPane pane = new JScrollPane(chat);
pane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(0, 0, 128), 5),
"Chat"));
cont.add(pane, BorderLayout.CENTER);
Box bottom = Box.createHorizontalBox();
input.setLineWrap(true);
input.setWrapStyleWord(true);
bottom.add(new JScrollPane(input));
bottom.add(Box.createHorizontalStrut(10));
bottom.add(new JButton(new Interact()));
bottom.add(new JButton(new AbstractAction("\u2191 image") {
@Override
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(frame);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
try {
BufferedImage originalImage = ImageIO.read(selectedFile);
if (originalImage.getHeight() != 256 || originalImage.getWidth() != 256) {
Image scaledInstance = originalImage.getScaledInstance(256, 256, BufferedImage.SCALE_SMOOTH);
BufferedImage resizedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resizedImage.createGraphics();
g2d.drawImage(scaledInstance, 0, 0, null);
g2d.dispose();
uplImage = resizedImage;
} else {
uplImage = originalImage;
}
updateSideBar(null);
} catch (IOException ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
uplImage = null;
}
}
}
}));
bottom.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(new Color(135, 206, 250), 5),
"Input"));
cont.add(bottom, BorderLayout.SOUTH);
cont.add(sideBar(), BorderLayout.EAST);
frame.pack();
if (EventQueue.isDispatchThread()) {
finishInit();
} else {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
finishInit();
}
});
} catch (Exception ex) {
Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex);
System.exit(1);
}
}
}
private void buttonBar() {
buttons.add(new AbstractAction("Exit") {
@Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
buttons.add(new JToolBar.Separator());
String lsHost = Ollama.config.getLastEndpoint();
for (String e : Ollama.getAvailableModels().keySet()) {
addToHosts(e);
}
client = new OllamaClient(lsHost);
models.removeAllItems();
for (AvailableModels.AvailableModel am : Ollama.getAvailableModels().get(lsHost).models) {
models.addItem(am.name);
}
if (null != Ollama.config.lastModel) {
models.setSelectedItem(Ollama.config.lastModel);
}
models.invalidate();
hosts.setSelectedItem(lsHost);
hosts.addActionListener(new AddSelectHost());
hosts.setEditable(true);
buttons.add(new JLabel("Hosts:"));
buttons.add(hosts);
buttons.add(new JToolBar.Separator());
buttons.add(new JLabel("Models:"));
buttons.add(models);
buttons.add(new JToolBar.Separator());
buttons.add(new AbstractAction("HTML") {
@Override
public void actionPerformed(ActionEvent ae) {
String markDown = chat.getText();
JFrame html = new JFrame("HTML");
html.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
html.getContentPane().setLayout(new BorderLayout());
JEditorPane pane = new JEditorPane();
pane.setContentType("text/html");
HTMLEditorKit kit = new HTMLEditorKit() {
@Override
public StyleSheet getStyleSheet() {
StyleSheet styleSheet = super.getStyleSheet();
styleSheet.addRule("body { font-family: 'Arial'; font-size: " + Math.round(Ollama.config.fontSize) + "pt; }");
return styleSheet;
}
};
pane.setEditorKit(kit);
pane.setText(new PandocConverter().convertMarkdownToHTML(markDown));
html.getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER);
html.pack();
html.setVisible(true);
}
});
buttons.add(new AbstractAction("Dall-E 3") {
@Override
public void actionPerformed(ActionEvent ae) {
try {
String text = chat.getSelectedText();
DallEClient dale = new DallEClient();
ImageObject io = new ImageObject(dale.getImage(text)); | ImageViewer iv = new ImageViewer(io); | 1 | 2023-11-16 00:37:47+00:00 | 12k |
JustARandomGuyNo512/Gunscraft | src/main/java/sheridan/gunscraft/items/attachments/util/NBTAttachmentsMap.java | [
{
"identifier": "ClientProxy",
"path": "src/main/java/sheridan/gunscraft/ClientProxy.java",
"snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa... | import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.model.ItemCameraTransforms;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*;
import sheridan.gunscraft.ClientProxy;
import sheridan.gunscraft.items.attachments.AttachmentRegistry;
import sheridan.gunscraft.items.attachments.GenericAttachment;
import sheridan.gunscraft.items.attachments.IGenericAttachment;
import sheridan.gunscraft.items.guns.IGenericGun;
import sheridan.gunscraft.model.IAttachmentModel;
import java.util.List; | 8,381 | package sheridan.gunscraft.items.attachments.util;
public class NBTAttachmentsMap{
private static CompoundNBT createEmptySlot(String slotName) {
CompoundNBT slot = new CompoundNBT();
slot.putString("slot_name", slotName);
slot.putBoolean("empty", true);
slot.putInt("attachment_id", GenericAttachment.NONE);
return slot;
}
public static void init(List<GunAttachmentSlot> slots, ItemStack stack, boolean reset) {
CompoundNBT stackNBT = stack.getTag();
if (stackNBT == null) {
return;
}
if (stackNBT.contains("attachments")) {
if (!reset) {return;}
stackNBT.remove("attachments");
}
CompoundNBT slotsNBT = new CompoundNBT();
for (GunAttachmentSlot slot : slots) {
slotsNBT.put(slot.name, createEmptySlot(slot.name));
}
stackNBT.put("attachments", slotsNBT);
}
public static GunRenderContext renderAttachments(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType,
int packedLight, int packedOverlay, int bulletLeft, long lastFireTime, boolean mainHand, int fireMode,ItemStack stack, IGenericGun gun) {
CompoundNBT slots = checkAndGet(stack);
GunRenderContext params = new GunRenderContext();
if (slots != null) {
for (String slotName : slots.keySet()) {
CompoundNBT slot = slots.getCompound(slotName);
if (!slot.getBoolean("empty")) {
int attachmentId = slot.getInt("attachment_id");
IAttachmentModel model = AttachmentRegistry.getModel(attachmentId);
GunAttachmentSlot slotInGun = gun.getSlot(slotName); | package sheridan.gunscraft.items.attachments.util;
public class NBTAttachmentsMap{
private static CompoundNBT createEmptySlot(String slotName) {
CompoundNBT slot = new CompoundNBT();
slot.putString("slot_name", slotName);
slot.putBoolean("empty", true);
slot.putInt("attachment_id", GenericAttachment.NONE);
return slot;
}
public static void init(List<GunAttachmentSlot> slots, ItemStack stack, boolean reset) {
CompoundNBT stackNBT = stack.getTag();
if (stackNBT == null) {
return;
}
if (stackNBT.contains("attachments")) {
if (!reset) {return;}
stackNBT.remove("attachments");
}
CompoundNBT slotsNBT = new CompoundNBT();
for (GunAttachmentSlot slot : slots) {
slotsNBT.put(slot.name, createEmptySlot(slot.name));
}
stackNBT.put("attachments", slotsNBT);
}
public static GunRenderContext renderAttachments(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType,
int packedLight, int packedOverlay, int bulletLeft, long lastFireTime, boolean mainHand, int fireMode,ItemStack stack, IGenericGun gun) {
CompoundNBT slots = checkAndGet(stack);
GunRenderContext params = new GunRenderContext();
if (slots != null) {
for (String slotName : slots.keySet()) {
CompoundNBT slot = slots.getCompound(slotName);
if (!slot.getBoolean("empty")) {
int attachmentId = slot.getInt("attachment_id");
IAttachmentModel model = AttachmentRegistry.getModel(attachmentId);
GunAttachmentSlot slotInGun = gun.getSlot(slotName); | IGenericAttachment attachment = AttachmentRegistry.get(attachmentId); | 3 | 2023-11-14 14:00:55+00:00 | 12k |
zpascual/5419-Arm-Example | src/main/java/com/team5419/frc2023/subsystems/ServoMotorSubsystem.java | [
{
"identifier": "TalonFXFactory",
"path": "src/main/java/com/team254/lib/drivers/TalonFXFactory.java",
"snippet": "public class TalonFXFactory {\n\n private final static int kTimeoutMs = 100;\n\n public static class Configuration {\n public NeutralMode NEUTRAL_MODE = NeutralMode.Coast;\n ... | import com.ctre.phoenix.motorcontrol.*;
import com.ctre.phoenix.motorcontrol.can.TalonFX;
import com.team254.lib.drivers.TalonFXFactory;
import com.team254.lib.drivers.TalonUtil;
import com.team254.lib.motion.MotionProfileConstraints;
import com.team254.lib.motion.MotionState;
import com.team254.lib.motion.SetpointGenerator;
import com.team254.lib.util.ReflectingCSVWriter;
import com.team254.lib.util.Util;
import com.team5419.frc2023.loops.ILooper;
import com.team5419.frc2023.loops.Loop;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Timer; | 8,318 |
TalonUtil.checkError(mMaster.config_IntegralZone(kMotionProfileSlot, mConstants.kIZone, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set i zone: ");
TalonUtil.checkError(
mMaster.configAllowableClosedloopError(kMotionProfileSlot, mConstants.kDeadband, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(mMaster.config_kP(kPositionPIDSlot, mConstants.kPositionKp, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kP: ");
TalonUtil.checkError(mMaster.config_kI(kPositionPIDSlot, mConstants.kPositionKi, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kI: ");
TalonUtil.checkError(mMaster.config_kD(kPositionPIDSlot, mConstants.kPositionKd, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kD: ");
TalonUtil.checkError(mMaster.config_kF(kPositionPIDSlot, mConstants.kPositionKf, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set kF: ");
TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kPositionPIDSlot, mConstants.kPositionMaxIntegralAccumulator,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: ");
TalonUtil.checkError(mMaster.config_IntegralZone(kPositionPIDSlot, mConstants.kPositionIZone, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set i zone: ");
TalonUtil.checkError(
mMaster.configAllowableClosedloopError(kPositionPIDSlot, mConstants.kPositionDeadband, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(
mMaster.configMotionCruiseVelocity(mConstants.kCruiseVelocity, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set cruise velocity: ");
TalonUtil.checkError(mMaster.configMotionAcceleration(mConstants.kAcceleration, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set acceleration: ");
TalonUtil.checkError(mMaster.configOpenloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage ramp rate: ");
TalonUtil.checkError(mMaster.configClosedloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set closed loop ramp rate: ");
TalonUtil.checkError(mMaster.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration(
mConstants.kEnableSupplyCurrentLimit,
mConstants.kSupplyContinuousCurrentLimit,
mConstants.kSupplyPeakCurrentLimit,
mConstants.kSupplyPeakCurrentDuration)),
mConstants.kName + ": Could not set supply current limit.");
TalonUtil.checkError(mMaster.configStatorCurrentLimit(new StatorCurrentLimitConfiguration(
mConstants.kEnableStatorCurrentLimit,
mConstants.kStatorContinuousCurrentLimit,
mConstants.kStatorPeakCurrentLimit,
mConstants.kStatorPeakCurrentDuration)),
mConstants.kName + ": Could not set stator current limit.");
mMaster.configVoltageMeasurementFilter(8);
TalonUtil.checkError(
mMaster.configVoltageCompSaturation(mConstants.kMaxVoltage, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage comp saturation.");
mMaster.enableVoltageCompensation(true);
mMaster.setInverted(mConstants.kMasterConstants.invert_motor);
mMaster.setSensorPhase(mConstants.kMasterConstants.invert_sensor_phase);
mMaster.setNeutralMode(NeutralMode.Brake);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0, 5, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_10_MotionMagic, 1000, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth, mConstants.kStatusFrame8UpdateRate, 20);
// Start with kMotionProfileSlot.
mMaster.selectProfileSlot(kMotionProfileSlot, 0);
for (int i = 0; i < mSlaves.length; ++i) {
mSlaves[i] = TalonFXFactory.createPermanentSlaveTalon(mConstants.kSlaveConstants[i].id, mConstants.kMasterConstants.id);
mSlaves[i].setInverted(mConstants.kSlaveConstants[i].invert_motor);
mSlaves[i].setNeutralMode(NeutralMode.Brake);
mSlaves[i].follow(mMaster);
}
// Send a neutral command.
stop();
}
public static class PeriodicIO {
// INPUTS
public double timestamp;
public double position_ticks;
public double position_units;
public double velocity_ticks_per_100ms;
public double active_trajectory_position; // ticks
public double active_trajectory_velocity; // ticks/100ms
public double active_trajectory_acceleration; // ticks/100ms/s
public double output_percent;
public double output_voltage;
public double master_current;
public double error_ticks;
public int encoder_wraps;
public int absolute_pulse_offset = 0;
// public int absolute_pulse_position;
public int absolute_pulse_position_modded;
public boolean reset_occured;
// OUTPUTS
public double demand;
public double feedforward;
}
protected enum ControlState {
OPEN_LOOP, MOTION_MAGIC, POSITION_PID, MOTION_PROFILING
}
protected PeriodicIO mPeriodicIO = new PeriodicIO();
protected ControlState mControlState = ControlState.OPEN_LOOP;
protected ReflectingCSVWriter<PeriodicIO> mCSVWriter = null;
protected boolean mHasBeenZeroed = false;
protected StickyFaults mFaults = new StickyFaults();
protected SetpointGenerator mSetpointGenerator = new SetpointGenerator(); | package com.team5419.frc2023.subsystems;
/**
* Abstract base class for a subsystem with a single sensor servo-mechanism.
*/
public abstract class ServoMotorSubsystem extends Subsystem {
protected static final int kMotionProfileSlot = 0;
protected static final int kPositionPIDSlot = 1;
// Recommend initializing in a static block!
public static class TalonFXConstants {
public int id = -1;
public boolean invert_motor = false;
public boolean invert_sensor_phase = false;
public int encoder_ppr = 2048;
}
// Recommend initializing in a static block!
public static class ServoMotorSubsystemConstants {
public String kName = "ERROR_ASSIGN_A_NAME";
public double kLooperDt = 0.01;
public int kCANTimeoutMs = 10; // use for important on the fly updates
public int kLongCANTimeoutMs = 100; // use for constructors
public TalonFXConstants kMasterConstants = new TalonFXConstants();
public TalonFXConstants[] kSlaveConstants = new TalonFXConstants[0];
public double kHomePosition = 0.0; // Units
public double kTicksPerUnitDistance = 1.0;
public double kKp = 0; // Raw output / raw error
public double kKi = 0; // Raw output / sum of raw error
public double kKd = 0; // Raw output / (err - prevErr)
public double kKf = 0; // Raw output / velocity in ticks/100ms
public double kKa = 0; // Raw output / accel in (ticks/100ms) / s
public double kMaxIntegralAccumulator = 0;
public int kIZone = 0; // Ticks
public int kDeadband = 0; // Ticks
public double kPositionKp = 0;
public double kPositionKi = 0;
public double kPositionKd = 0;
public double kPositionKf = 0;
public double kPositionMaxIntegralAccumulator = 0;
public int kPositionIZone = 0; // Ticks
public int kPositionDeadband = 0; // Ticks
public int kCruiseVelocity = 0; // Ticks / 100ms
public int kAcceleration = 0; // Ticks / 100ms / s
public double kRampRate = 0.0; // s
public double kMaxVoltage = 12.0;
public int kSupplyContinuousCurrentLimit = 20; // amps
public int kSupplyPeakCurrentLimit = 60; // amps
public double kSupplyPeakCurrentDuration = 0.2; // seconds
public boolean kEnableSupplyCurrentLimit = false;
public int kStatorContinuousCurrentLimit = 20; // amps
public int kStatorPeakCurrentLimit = 60; // amps
public double kStatorPeakCurrentDuration = 0.2; // seconds
public boolean kEnableStatorCurrentLimit = false;
public double kMaxUnitsLimit = Double.POSITIVE_INFINITY;
public double kMinUnitsLimit = Double.NEGATIVE_INFINITY;
public int kStatusFrame8UpdateRate = 1000;
public boolean kRecoverPositionOnReset = false;
}
protected final ServoMotorSubsystemConstants mConstants;
protected final TalonFX mMaster;
protected final TalonFX[] mSlaves;
protected MotionState mMotionStateSetpoint = null;
protected final int mForwardSoftLimitTicks;
protected final int mReverseSoftLimitTicks;
protected ServoMotorSubsystem(final ServoMotorSubsystemConstants constants) {
mConstants = constants;
mMaster = TalonFXFactory.createDefaultTalon(mConstants.kMasterConstants.id);
mSlaves = new TalonFX[mConstants.kSlaveConstants.length];
TalonUtil.checkError(mMaster.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor, 0,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not detect encoder: ");
mForwardSoftLimitTicks = (int) ((mConstants.kMaxUnitsLimit - mConstants.kHomePosition) * mConstants.kTicksPerUnitDistance);
TalonUtil.checkError(
mMaster.configForwardSoftLimitThreshold(mForwardSoftLimitTicks, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set forward soft limit: ");
TalonUtil.checkError(mMaster.configForwardSoftLimitEnable(true, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not enable forward soft limit: ");
mReverseSoftLimitTicks = (int) ((mConstants.kMinUnitsLimit - mConstants.kHomePosition) * mConstants.kTicksPerUnitDistance);
TalonUtil.checkError(
mMaster.configReverseSoftLimitThreshold(mReverseSoftLimitTicks, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set reverse soft limit: ");
TalonUtil.checkError(mMaster.configReverseSoftLimitEnable(true, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not enable reverse soft limit: ");
TalonUtil.checkError(mMaster.configVoltageCompSaturation(12.0, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage compensation saturation: ");
TalonUtil.checkError(mMaster.config_kP(kMotionProfileSlot, mConstants.kKp, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kP: ");
TalonUtil.checkError(mMaster.config_kI(kMotionProfileSlot, mConstants.kKi, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kI: ");
TalonUtil.checkError(mMaster.config_kD(kMotionProfileSlot, mConstants.kKd, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kD: ");
TalonUtil.checkError(mMaster.config_kF(kMotionProfileSlot, mConstants.kKf, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set kF: ");
TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kMotionProfileSlot, mConstants.kMaxIntegralAccumulator,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: ");
TalonUtil.checkError(mMaster.config_IntegralZone(kMotionProfileSlot, mConstants.kIZone, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set i zone: ");
TalonUtil.checkError(
mMaster.configAllowableClosedloopError(kMotionProfileSlot, mConstants.kDeadband, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(mMaster.config_kP(kPositionPIDSlot, mConstants.kPositionKp, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kP: ");
TalonUtil.checkError(mMaster.config_kI(kPositionPIDSlot, mConstants.kPositionKi, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kI: ");
TalonUtil.checkError(mMaster.config_kD(kPositionPIDSlot, mConstants.kPositionKd, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": could not set kD: ");
TalonUtil.checkError(mMaster.config_kF(kPositionPIDSlot, mConstants.kPositionKf, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set kF: ");
TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kPositionPIDSlot, mConstants.kPositionMaxIntegralAccumulator,
mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: ");
TalonUtil.checkError(mMaster.config_IntegralZone(kPositionPIDSlot, mConstants.kPositionIZone, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set i zone: ");
TalonUtil.checkError(
mMaster.configAllowableClosedloopError(kPositionPIDSlot, mConstants.kPositionDeadband, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set deadband: ");
TalonUtil.checkError(
mMaster.configMotionCruiseVelocity(mConstants.kCruiseVelocity, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set cruise velocity: ");
TalonUtil.checkError(mMaster.configMotionAcceleration(mConstants.kAcceleration, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set acceleration: ");
TalonUtil.checkError(mMaster.configOpenloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage ramp rate: ");
TalonUtil.checkError(mMaster.configClosedloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set closed loop ramp rate: ");
TalonUtil.checkError(mMaster.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration(
mConstants.kEnableSupplyCurrentLimit,
mConstants.kSupplyContinuousCurrentLimit,
mConstants.kSupplyPeakCurrentLimit,
mConstants.kSupplyPeakCurrentDuration)),
mConstants.kName + ": Could not set supply current limit.");
TalonUtil.checkError(mMaster.configStatorCurrentLimit(new StatorCurrentLimitConfiguration(
mConstants.kEnableStatorCurrentLimit,
mConstants.kStatorContinuousCurrentLimit,
mConstants.kStatorPeakCurrentLimit,
mConstants.kStatorPeakCurrentDuration)),
mConstants.kName + ": Could not set stator current limit.");
mMaster.configVoltageMeasurementFilter(8);
TalonUtil.checkError(
mMaster.configVoltageCompSaturation(mConstants.kMaxVoltage, mConstants.kLongCANTimeoutMs),
mConstants.kName + ": Could not set voltage comp saturation.");
mMaster.enableVoltageCompensation(true);
mMaster.setInverted(mConstants.kMasterConstants.invert_motor);
mMaster.setSensorPhase(mConstants.kMasterConstants.invert_sensor_phase);
mMaster.setNeutralMode(NeutralMode.Brake);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0, 5, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_10_MotionMagic, 1000, 20);
mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth, mConstants.kStatusFrame8UpdateRate, 20);
// Start with kMotionProfileSlot.
mMaster.selectProfileSlot(kMotionProfileSlot, 0);
for (int i = 0; i < mSlaves.length; ++i) {
mSlaves[i] = TalonFXFactory.createPermanentSlaveTalon(mConstants.kSlaveConstants[i].id, mConstants.kMasterConstants.id);
mSlaves[i].setInverted(mConstants.kSlaveConstants[i].invert_motor);
mSlaves[i].setNeutralMode(NeutralMode.Brake);
mSlaves[i].follow(mMaster);
}
// Send a neutral command.
stop();
}
public static class PeriodicIO {
// INPUTS
public double timestamp;
public double position_ticks;
public double position_units;
public double velocity_ticks_per_100ms;
public double active_trajectory_position; // ticks
public double active_trajectory_velocity; // ticks/100ms
public double active_trajectory_acceleration; // ticks/100ms/s
public double output_percent;
public double output_voltage;
public double master_current;
public double error_ticks;
public int encoder_wraps;
public int absolute_pulse_offset = 0;
// public int absolute_pulse_position;
public int absolute_pulse_position_modded;
public boolean reset_occured;
// OUTPUTS
public double demand;
public double feedforward;
}
protected enum ControlState {
OPEN_LOOP, MOTION_MAGIC, POSITION_PID, MOTION_PROFILING
}
protected PeriodicIO mPeriodicIO = new PeriodicIO();
protected ControlState mControlState = ControlState.OPEN_LOOP;
protected ReflectingCSVWriter<PeriodicIO> mCSVWriter = null;
protected boolean mHasBeenZeroed = false;
protected StickyFaults mFaults = new StickyFaults();
protected SetpointGenerator mSetpointGenerator = new SetpointGenerator(); | protected MotionProfileConstraints mMotionProfileConstraints; | 2 | 2023-11-14 06:44:40+00:00 | 12k |
threethan/QuestAudioPatcher | app/src/main/java/com/threethan/questpatcher/activities/SettingsActivity.java | [
{
"identifier": "SettingsAdapter",
"path": "app/src/main/java/com/threethan/questpatcher/adapters/SettingsAdapter.java",
"snippet": "public class SettingsAdapter extends RecyclerView.Adapter<SettingsAdapter.ViewHolder> {\n\n private static ClickListener clickListener;\n\n private static ArrayList<... | import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.threethan.questpatcher.R;
import com.threethan.questpatcher.adapters.SettingsAdapter;
import com.threethan.questpatcher.utils.APKEditorUtils;
import com.threethan.questpatcher.utils.AppSettings;
import com.threethan.questpatcher.utils.dialogs.ClearAppSettingsDialog;
import com.threethan.questpatcher.utils.tasks.TransferApps;
import java.io.File;
import java.util.ArrayList;
import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils;
import in.sunilpaulmathew.sCommon.CommonUtils.sSerializableItems;
import in.sunilpaulmathew.sCommon.Dialog.sSingleChoiceDialog;
import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
import in.sunilpaulmathew.sCommon.PermissionUtils.sPermissionUtils;
import in.sunilpaulmathew.sCommon.ThemeUtils.sThemeUtils; | 8,254 | if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
sPermissionUtils.requestPermission(
new String[] {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, this);
} else {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
new sSingleChoiceDialog(R.drawable.ic_export, getString(R.string.export_path_resources),
AppSettings.getExportPathMenu(this), AppSettings.getExportPathPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("exportPath", Environment.getExternalStorageDirectory().toString(), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_resources), AppSettings
.getExportPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("exportPath", Environment.getExternalStorageDirectory().toString() + "/AEE", SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_resources), AppSettings
.getExportPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("exportPath", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_resources), AppSettings
.getExportPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
}
}
} else if (APKEditorUtils.isFullVersion(this) && position == 8) {
new sSingleChoiceDialog(R.drawable.ic_android, getString(R.string.export_options),
AppSettings.getExportingAPKMenu(this), AppSettings.getExportingAPKsPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("exportAPKs", getString(R.string.export_storage), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_android, SettingsActivity.this), getString(R.string.export_options), AppSettings
.getAPKs(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("exportAPKs", getString(R.string.export_resign), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_android, SettingsActivity.this), getString(R.string.export_options), AppSettings
.getAPKs(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("exportAPKs", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_android, SettingsActivity.this), getString(R.string.export_options), AppSettings
.getAPKs(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else if (APKEditorUtils.isFullVersion(this) && position == 9) {
new sSingleChoiceDialog(R.drawable.ic_installer, getString(R.string.installer_action),
AppSettings.getInstallerMenu(this), AppSettings.getInstallerMenuPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("installerAction", getString(R.string.install), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_installer, SettingsActivity.this), getString(R.string.installer_action), AppSettings
.getInstallerAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("installerAction", getString(R.string.install_resign), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_installer, SettingsActivity.this), getString(R.string.installer_action), AppSettings
.getInstallerAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("installerAction", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_installer, SettingsActivity.this), getString(R.string.installer_action), AppSettings
.getInstallerAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else if (APKEditorUtils.isFullVersion(this) && position == 10) {
new sSingleChoiceDialog(R.drawable.ic_key, getString(R.string.sign_apk_with),
new String[] {
getString(R.string.sign_apk_default),
getString(R.string.sign_apk_custom)
}, AppSettings.getAPKSignPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
if (AppSettings.isCustomKey(SettingsActivity.this)) {
sCommonUtils.saveString("PrivateKey", null, SettingsActivity.this);
sFileUtils.delete(new File(getFilesDir(), "signing/APKEditor.pk8"));
sCommonUtils.saveString("X509Certificate", null, SettingsActivity.this);
sFileUtils.delete(new File(getFilesDir(), "signing/APKEditorCert"));
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_key, SettingsActivity.this), getString(R.string.sign_apk_with), AppSettings
.getAPKSign(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
} else {
Intent signing = new Intent(SettingsActivity.this, APKSignActivity.class);
startActivity(signing);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_key, SettingsActivity.this), getString(R.string.sign_apk_with), AppSettings
.getAPKSign(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else { | package com.threethan.questpatcher.activities;
/*
* Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 25, 2021
*/
public class SettingsActivity extends AppCompatActivity {
private final ArrayList<sSerializableItems> mData = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
AppCompatImageButton mBack = findViewById(R.id.back_button);
RecyclerView mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
SettingsAdapter mRecycleViewAdapter = new SettingsAdapter(mData);
mRecyclerView.setAdapter(mRecycleViewAdapter);
mData.add(new sSerializableItems(null, getString(R.string.user_interface), null, null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_theme, this), getString(R.string.app_theme), sThemeUtils.getAppTheme(this), null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_translate, this), getString(R.string.language), AppSettings.getLanguage(this), null));
mData.add(new sSerializableItems(null, getString(R.string.settings_general), null, null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_projects, this), getString(R.string.project_exist_action), AppSettings.getProjectExistAction(this), null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_export, this), getString(R.string.export_path_apks), AppSettings.getExportAPKsPath(this), null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_export, this), getString(R.string.export_path_resources), AppSettings.getExportPath(this), null));
if (APKEditorUtils.isFullVersion(this)) {
mData.add(new sSerializableItems(null, getString(R.string.signing_title), null, null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_android, this), getString(R.string.export_options), AppSettings.getAPKs(this), null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_installer, this), getString(R.string.installer_action), AppSettings.getInstallerAction(this), null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_key, this), getString(R.string.sign_apk_with), AppSettings.getAPKSign(this), null));
}
mData.add(new sSerializableItems(null, getString(R.string.settings_misc), null, null));
mData.add(new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_delete, this), getString(R.string.clear_cache), getString(R.string.clear_cache_summary), null));
mRecycleViewAdapter.setOnItemClickListener((position, v) -> {
if (mData.get(position).getTextTwo() != null) {
if (position == 1) {
sThemeUtils.setAppTheme(this);
} else if (position == 2) {
AppSettings.setLanguage(this);
} else if (position == 4) {
new sSingleChoiceDialog(R.drawable.ic_projects, getString(R.string.project_exist_action),
AppSettings.getProjectExitingMenu(this), AppSettings.getProjectExitingMenuPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("projectAction", getString(R.string.save), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_projects, SettingsActivity.this), getString(R.string.project_exist_action), AppSettings.getProjectExistAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("projectAction", getString(R.string.delete), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_projects, SettingsActivity.this), getString(R.string.project_exist_action), AppSettings.getProjectExistAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("projectAction", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(R.drawable.ic_projects, SettingsActivity.this), getString(R.string.project_exist_action), AppSettings.getProjectExistAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else if (position == 5) {
if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
sPermissionUtils.requestPermission(
new String[] {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, this);
} else {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
new sSingleChoiceDialog(R.drawable.ic_export, getString(R.string.export_path_apks),
AppSettings.getAPKExportPathMenu(this), AppSettings.getExportAPKsPathPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("exportAPKsPath", "externalFiles", SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_apks), AppSettings
.getExportAPKsPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
new TransferApps(SettingsActivity.this).execute();
} else if (itemPosition == 1) {
sCommonUtils.saveString("exportAPKsPath", "internalStorage", SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_apks), AppSettings
.getExportAPKsPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
new TransferApps(SettingsActivity.this).execute();
}
}
}.show();
}
}
} else if (position == 6) {
if (Build.VERSION.SDK_INT < 29 && sPermissionUtils.isPermissionDenied(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
sPermissionUtils.requestPermission(
new String[] {
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
}, this);
} else {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
new sSingleChoiceDialog(R.drawable.ic_export, getString(R.string.export_path_resources),
AppSettings.getExportPathMenu(this), AppSettings.getExportPathPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("exportPath", Environment.getExternalStorageDirectory().toString(), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_resources), AppSettings
.getExportPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("exportPath", Environment.getExternalStorageDirectory().toString() + "/AEE", SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_resources), AppSettings
.getExportPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("exportPath", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_export, SettingsActivity.this), getString(R.string.export_path_resources), AppSettings
.getExportPath(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
}
}
} else if (APKEditorUtils.isFullVersion(this) && position == 8) {
new sSingleChoiceDialog(R.drawable.ic_android, getString(R.string.export_options),
AppSettings.getExportingAPKMenu(this), AppSettings.getExportingAPKsPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("exportAPKs", getString(R.string.export_storage), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_android, SettingsActivity.this), getString(R.string.export_options), AppSettings
.getAPKs(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("exportAPKs", getString(R.string.export_resign), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_android, SettingsActivity.this), getString(R.string.export_options), AppSettings
.getAPKs(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("exportAPKs", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_android, SettingsActivity.this), getString(R.string.export_options), AppSettings
.getAPKs(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else if (APKEditorUtils.isFullVersion(this) && position == 9) {
new sSingleChoiceDialog(R.drawable.ic_installer, getString(R.string.installer_action),
AppSettings.getInstallerMenu(this), AppSettings.getInstallerMenuPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
sCommonUtils.saveString("installerAction", getString(R.string.install), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_installer, SettingsActivity.this), getString(R.string.installer_action), AppSettings
.getInstallerAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else if (itemPosition == 1) {
sCommonUtils.saveString("installerAction", getString(R.string.install_resign), SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_installer, SettingsActivity.this), getString(R.string.installer_action), AppSettings
.getInstallerAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
} else {
sCommonUtils.saveString("installerAction", null, SettingsActivity.this);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_installer, SettingsActivity.this), getString(R.string.installer_action), AppSettings
.getInstallerAction(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else if (APKEditorUtils.isFullVersion(this) && position == 10) {
new sSingleChoiceDialog(R.drawable.ic_key, getString(R.string.sign_apk_with),
new String[] {
getString(R.string.sign_apk_default),
getString(R.string.sign_apk_custom)
}, AppSettings.getAPKSignPosition(this), this) {
@Override
public void onItemSelected(int itemPosition) {
if (itemPosition == 0) {
if (AppSettings.isCustomKey(SettingsActivity.this)) {
sCommonUtils.saveString("PrivateKey", null, SettingsActivity.this);
sFileUtils.delete(new File(getFilesDir(), "signing/APKEditor.pk8"));
sCommonUtils.saveString("X509Certificate", null, SettingsActivity.this);
sFileUtils.delete(new File(getFilesDir(), "signing/APKEditorCert"));
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_key, SettingsActivity.this), getString(R.string.sign_apk_with), AppSettings
.getAPKSign(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
} else {
Intent signing = new Intent(SettingsActivity.this, APKSignActivity.class);
startActivity(signing);
mData.set(position, new sSerializableItems(sCommonUtils.getDrawable(
R.drawable.ic_key, SettingsActivity.this), getString(R.string.sign_apk_with), AppSettings
.getAPKSign(SettingsActivity.this), null));
mRecycleViewAdapter.notifyItemChanged(position);
}
}
}.show();
} else { | new ClearAppSettingsDialog(this).show(); | 3 | 2023-11-18 15:13:30+00:00 | 12k |
jenkinsci/harbor-plugin | src/main/java/io/jenkins/plugins/harbor/steps/WaitForHarborWebhookExecution.java | [
{
"identifier": "HarborException",
"path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java",
"snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throw... | import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.util.ArgumentListBuilder;
import io.jenkins.plugins.harbor.HarborException;
import io.jenkins.plugins.harbor.action.HarborBuildBadgeAction;
import io.jenkins.plugins.harbor.action.HarborWebHookAction;
import io.jenkins.plugins.harbor.action.HarborWebhookEvent;
import io.jenkins.plugins.harbor.action.model.EventType;
import io.jenkins.plugins.harbor.action.model.Resource;
import io.jenkins.plugins.harbor.action.model.VulnerabilityScanStatus;
import io.jenkins.plugins.harbor.client.HarborClientImpl;
import io.jenkins.plugins.harbor.client.models.Artifact;
import io.jenkins.plugins.harbor.client.models.NativeReportSummary;
import io.jenkins.plugins.harbor.client.models.Severity;
import io.jenkins.plugins.harbor.configuration.HarborPluginGlobalConfiguration;
import io.jenkins.plugins.harbor.configuration.HarborServer;
import io.jenkins.plugins.harbor.util.HarborConstants;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.steps.StepContext;
import org.jenkinsci.plugins.workflow.steps.StepExecution;
import org.jenkinsci.plugins.workflow.support.actions.PauseAction; | 8,487 | package io.jenkins.plugins.harbor.steps;
public class WaitForHarborWebhookExecution extends StepExecution implements Consumer<HarborWebhookEvent> {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WaitForHarborWebhookExecution.class.getName());
private static final int MAX_LOG_LINES = 1000;
private static final String BUILD_IMAGE_NAME_PATTERN = "#\\d+ naming to (\\S+/\\S+/\\S+:\\S+) .*done";
private static final String BUILD_IMAGE_DIGEST_PATTERN = "(\\d+): digest: (sha256:[a-f0-9]+) size: (\\d+)";
private final WaitForHarborWebhookStep waitForHarborWebhookStep;
private Image image;
public WaitForHarborWebhookExecution(StepContext context, WaitForHarborWebhookStep waitForHarborWebhookStep) {
super(context);
this.waitForHarborWebhookStep = waitForHarborWebhookStep;
}
@Override
public boolean start() throws Exception {
processStepParameters();
if (!checkScanCompleted()) {
HarborWebhookEvent harborWebhookEvent =
HarborWebHookAction.get().getWebhookEventForDigest(image.getImageDigest());
if (harborWebhookEvent != null) {
validateWebhookAndCheckSeverityIfValid(harborWebhookEvent, true);
return true;
} else {
getContextClass(FlowNode.class).addAction(new PauseAction("Harbor Scanner analysis"));
return false;
}
} else {
return true;
}
}
private void processStepParameters() throws IOException {
String foundImageName = waitForHarborWebhookStep.getFullImageName();
String foundImageDigest = null;
if (foundImageName == null) {
List<String> lastConsoleLogLines = getContextClass(Run.class).getLog(MAX_LOG_LINES);
Pattern namePattern = Pattern.compile(BUILD_IMAGE_NAME_PATTERN);
Pattern digestPattern = Pattern.compile(BUILD_IMAGE_DIGEST_PATTERN);
for (String line : lastConsoleLogLines) {
Matcher nameMatcher = namePattern.matcher(line);
Matcher digestMatcher = digestPattern.matcher(line);
if (nameMatcher.find()) {
foundImageName = nameMatcher.group(1);
}
if (digestMatcher.find()) {
foundImageDigest = digestMatcher.group(2);
}
}
} else {
foundImageDigest = getDigestByFullImageName(foundImageName);
}
if (foundImageName == null || foundImageDigest == null) {
throw new ImageInfoExtractionException(String.format(
"Failed to extract image name(%s) or digest(%s). Image not found.",
foundImageName, foundImageDigest));
}
this.image = new Image(foundImageName, foundImageDigest);
getContextClass(Run.class)
.addAction(new HarborBuildBadgeAction(String.format(
"https://%s/harbor/projects/%s/repositories/%s/artifacts-tab/artifacts/%s",
image.getRegistry(), image.getProjects(), image.getRepository(), foundImageDigest)));
}
private String getDigestByFullImageName(String fullImageName) {
ArgumentListBuilder argumentListBuilder = new ArgumentListBuilder();
argumentListBuilder.add("docker", "inspect", "-f", "{{.RepoDigests}}", fullImageName);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream error = new ByteArrayOutputStream();
try {
int status = getContextClass(Launcher.class)
.launch()
.cmds(argumentListBuilder)
.envs(getContextClass(EnvVars.class))
.quiet(true)
.stdout(output)
.stderr(error)
.start()
.join();
if (status == 0) {
String charsetName = Charset.defaultCharset().name();
String repoDigests = output.toString(charsetName).trim();
for (String repoDigest :
repoDigests.substring(1, repoDigests.length() - 1).split(" ")) {
if (repoDigest.startsWith(fullImageName.split(":")[0])) {
return repoDigest.split("@")[1];
}
}
| package io.jenkins.plugins.harbor.steps;
public class WaitForHarborWebhookExecution extends StepExecution implements Consumer<HarborWebhookEvent> {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WaitForHarborWebhookExecution.class.getName());
private static final int MAX_LOG_LINES = 1000;
private static final String BUILD_IMAGE_NAME_PATTERN = "#\\d+ naming to (\\S+/\\S+/\\S+:\\S+) .*done";
private static final String BUILD_IMAGE_DIGEST_PATTERN = "(\\d+): digest: (sha256:[a-f0-9]+) size: (\\d+)";
private final WaitForHarborWebhookStep waitForHarborWebhookStep;
private Image image;
public WaitForHarborWebhookExecution(StepContext context, WaitForHarborWebhookStep waitForHarborWebhookStep) {
super(context);
this.waitForHarborWebhookStep = waitForHarborWebhookStep;
}
@Override
public boolean start() throws Exception {
processStepParameters();
if (!checkScanCompleted()) {
HarborWebhookEvent harborWebhookEvent =
HarborWebHookAction.get().getWebhookEventForDigest(image.getImageDigest());
if (harborWebhookEvent != null) {
validateWebhookAndCheckSeverityIfValid(harborWebhookEvent, true);
return true;
} else {
getContextClass(FlowNode.class).addAction(new PauseAction("Harbor Scanner analysis"));
return false;
}
} else {
return true;
}
}
private void processStepParameters() throws IOException {
String foundImageName = waitForHarborWebhookStep.getFullImageName();
String foundImageDigest = null;
if (foundImageName == null) {
List<String> lastConsoleLogLines = getContextClass(Run.class).getLog(MAX_LOG_LINES);
Pattern namePattern = Pattern.compile(BUILD_IMAGE_NAME_PATTERN);
Pattern digestPattern = Pattern.compile(BUILD_IMAGE_DIGEST_PATTERN);
for (String line : lastConsoleLogLines) {
Matcher nameMatcher = namePattern.matcher(line);
Matcher digestMatcher = digestPattern.matcher(line);
if (nameMatcher.find()) {
foundImageName = nameMatcher.group(1);
}
if (digestMatcher.find()) {
foundImageDigest = digestMatcher.group(2);
}
}
} else {
foundImageDigest = getDigestByFullImageName(foundImageName);
}
if (foundImageName == null || foundImageDigest == null) {
throw new ImageInfoExtractionException(String.format(
"Failed to extract image name(%s) or digest(%s). Image not found.",
foundImageName, foundImageDigest));
}
this.image = new Image(foundImageName, foundImageDigest);
getContextClass(Run.class)
.addAction(new HarborBuildBadgeAction(String.format(
"https://%s/harbor/projects/%s/repositories/%s/artifacts-tab/artifacts/%s",
image.getRegistry(), image.getProjects(), image.getRepository(), foundImageDigest)));
}
private String getDigestByFullImageName(String fullImageName) {
ArgumentListBuilder argumentListBuilder = new ArgumentListBuilder();
argumentListBuilder.add("docker", "inspect", "-f", "{{.RepoDigests}}", fullImageName);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ByteArrayOutputStream error = new ByteArrayOutputStream();
try {
int status = getContextClass(Launcher.class)
.launch()
.cmds(argumentListBuilder)
.envs(getContextClass(EnvVars.class))
.quiet(true)
.stdout(output)
.stderr(error)
.start()
.join();
if (status == 0) {
String charsetName = Charset.defaultCharset().name();
String repoDigests = output.toString(charsetName).trim();
for (String repoDigest :
repoDigests.substring(1, repoDigests.length() - 1).split(" ")) {
if (repoDigest.startsWith(fullImageName.split(":")[0])) {
return repoDigest.split("@")[1];
}
}
| throw new HarborException( | 0 | 2023-11-11 14:54:53+00:00 | 12k |
Mapty231/SpawnFix | src/main/java/me/tye/spawnfix/SpawnFix.java | [
{
"identifier": "Commands",
"path": "src/main/java/me/tye/spawnfix/commands/Commands.java",
"snippet": "public class Commands implements CommandExecutor {\n@Override\npublic boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {... | import me.tye.spawnfix.commands.Commands;
import me.tye.spawnfix.commands.TabComplete;
import me.tye.spawnfix.utils.Config;
import me.tye.spawnfix.utils.Lang;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import static me.tye.spawnfix.utils.Util.*; | 7,311 | package me.tye.spawnfix;
public final class SpawnFix extends JavaPlugin {
@Override
public void onEnable() {
createRequiredFiles();
Config.init();
Lang.init();
Config.load();
Lang.load();
getLogger().log(Level.INFO, Lang.startUp_readMe.getResponse());
getLogger().log(Level.INFO, Lang.startUp_link.getResponse());
//Listeners
getServer().getPluginManager().registerEvents(new PlayerJoin(), this);
getServer().getPluginManager().registerEvents(new PlayerLeave(), this);
getServer().getPluginManager().registerEvents(new PlayerRespawn(), this);
//Commands
Objects.requireNonNull(getCommand("sf")).setExecutor(new Commands()); | package me.tye.spawnfix;
public final class SpawnFix extends JavaPlugin {
@Override
public void onEnable() {
createRequiredFiles();
Config.init();
Lang.init();
Config.load();
Lang.load();
getLogger().log(Level.INFO, Lang.startUp_readMe.getResponse());
getLogger().log(Level.INFO, Lang.startUp_link.getResponse());
//Listeners
getServer().getPluginManager().registerEvents(new PlayerJoin(), this);
getServer().getPluginManager().registerEvents(new PlayerLeave(), this);
getServer().getPluginManager().registerEvents(new PlayerRespawn(), this);
//Commands
Objects.requireNonNull(getCommand("sf")).setExecutor(new Commands()); | Objects.requireNonNull(getCommand("sf")).setTabCompleter(new TabComplete()); | 1 | 2023-11-13 23:53:25+00:00 | 12k |
wangxianhui111/xuechengzaixian | xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/impl/CoursePublishServiceImpl.java | [
{
"identifier": "XueChengPlusException",
"path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java",
"snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private Strin... | import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.feignclient.SearchServiceClient;
import com.xuecheng.content.feignclient.po.CourseIndex;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit; | 8,874 | package com.xuecheng.content.service.impl;
/**
* @author Wuxy
* @version 1.0
* @ClassName CoursePublishServiceImpl
* @since 2023/1/30 15:45
*/
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {
@Resource
private CourseBaseMapper courseBaseMapper;
@Resource
private CourseMarketMapper courseMarketMapper;
@Resource
private CoursePublishMapper coursePublishMapper;
@Resource
private CoursePublishPreMapper coursePublishPreMapper;
@Autowired
private CourseBaseInfoService courseBaseInfoService;
@Autowired
private TeachplanService teachplanService;
@Autowired
private MqMessageService mqMessageService;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private SearchServiceClient searchServiceClient;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedissonClient redissonClient;
@Override
public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
// 查询课程发布信息
CoursePublish coursePublish = getCoursePublishCache(courseId);
// 课程基本信息
CourseBaseInfoDto courseBaseInfo = new CourseBaseInfoDto();
BeanUtils.copyProperties(coursePublish, courseBaseInfo);
// 课程计划信息
List<TeachplanDto> teachplans = JSON.parseArray(coursePublish.getTeachplan(), TeachplanDto.class);
// 创建课程预览信息
CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
coursePreviewDto.setCourseBase(courseBaseInfo);
coursePreviewDto.setTeachplans(teachplans);
return coursePreviewDto;
}
@Override
public CoursePreviewDto getOpenCoursePreviewInfo(Long courseId) {
// 课程基本信息
CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.queryCourseBaseById(courseId);
// 课程计划信息
List<TeachplanDto> teachplans = teachplanService.findTeachplanTree(courseId);
// 创建课程预览信息
CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
coursePreviewDto.setCourseBase(courseBaseInfo);
coursePreviewDto.setTeachplans(teachplans);
return coursePreviewDto;
}
@Override
public void commitAudit(Long companyId, Long courseId) {
// 课程基本信息
CourseBase courseBase = courseBaseMapper.selectById(courseId);
// 课程审核状态
String auditStatus = courseBase.getAuditStatus();
if ("202003".equals(auditStatus)) {
XueChengPlusException.cast("当前为等待审核状态,审核完成可以再次提交。");
}
// 本机构只允许提交本机构的课程
if (!companyId.equals(courseBase.getCompanyId())) {
XueChengPlusException.cast("不允许提交其它机构的课程。");
}
// 课程图片是否填写
if (StringUtils.isEmpty(courseBase.getPic())) {
XueChengPlusException.cast("提交失败,请上传课程图片");
}
// 添加课程预发布记录 | package com.xuecheng.content.service.impl;
/**
* @author Wuxy
* @version 1.0
* @ClassName CoursePublishServiceImpl
* @since 2023/1/30 15:45
*/
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {
@Resource
private CourseBaseMapper courseBaseMapper;
@Resource
private CourseMarketMapper courseMarketMapper;
@Resource
private CoursePublishMapper coursePublishMapper;
@Resource
private CoursePublishPreMapper coursePublishPreMapper;
@Autowired
private CourseBaseInfoService courseBaseInfoService;
@Autowired
private TeachplanService teachplanService;
@Autowired
private MqMessageService mqMessageService;
@Autowired
private MediaServiceClient mediaServiceClient;
@Autowired
private SearchServiceClient searchServiceClient;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedissonClient redissonClient;
@Override
public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
// 查询课程发布信息
CoursePublish coursePublish = getCoursePublishCache(courseId);
// 课程基本信息
CourseBaseInfoDto courseBaseInfo = new CourseBaseInfoDto();
BeanUtils.copyProperties(coursePublish, courseBaseInfo);
// 课程计划信息
List<TeachplanDto> teachplans = JSON.parseArray(coursePublish.getTeachplan(), TeachplanDto.class);
// 创建课程预览信息
CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
coursePreviewDto.setCourseBase(courseBaseInfo);
coursePreviewDto.setTeachplans(teachplans);
return coursePreviewDto;
}
@Override
public CoursePreviewDto getOpenCoursePreviewInfo(Long courseId) {
// 课程基本信息
CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.queryCourseBaseById(courseId);
// 课程计划信息
List<TeachplanDto> teachplans = teachplanService.findTeachplanTree(courseId);
// 创建课程预览信息
CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
coursePreviewDto.setCourseBase(courseBaseInfo);
coursePreviewDto.setTeachplans(teachplans);
return coursePreviewDto;
}
@Override
public void commitAudit(Long companyId, Long courseId) {
// 课程基本信息
CourseBase courseBase = courseBaseMapper.selectById(courseId);
// 课程审核状态
String auditStatus = courseBase.getAuditStatus();
if ("202003".equals(auditStatus)) {
XueChengPlusException.cast("当前为等待审核状态,审核完成可以再次提交。");
}
// 本机构只允许提交本机构的课程
if (!companyId.equals(courseBase.getCompanyId())) {
XueChengPlusException.cast("不允许提交其它机构的课程。");
}
// 课程图片是否填写
if (StringUtils.isEmpty(courseBase.getPic())) {
XueChengPlusException.cast("提交失败,请上传课程图片");
}
// 添加课程预发布记录 | CoursePublishPre coursePublishPre = new CoursePublishPre(); | 15 | 2023-11-13 11:39:35+00:00 | 12k |
jensjeflensje/minecraft_typewriter | src/main/java/dev/jensderuiter/minecrafttypewriter/command/SpawnCommand.java | [
{
"identifier": "TypewriterPlugin",
"path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java",
"snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin... | import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin;
import dev.jensderuiter.minecrafttypewriter.typewriter.TypeWriter;
import dev.jensderuiter.minecrafttypewriter.typewriter.type.WoodenTypeWriter;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; | 7,543 | package dev.jensderuiter.minecrafttypewriter.command;
public class SpawnCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) return true;
Player player = (Player) sender;
if (TypewriterPlugin.playerWriters.get(player) != null) return true;
| package dev.jensderuiter.minecrafttypewriter.command;
public class SpawnCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) return true;
Player player = (Player) sender;
if (TypewriterPlugin.playerWriters.get(player) != null) return true;
| TypeWriter typeWriter = new WoodenTypeWriter(player); | 2 | 2023-11-18 20:44:30+00:00 | 12k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.