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
ZhiQinIsZhen/dubbo-springboot3
dubbo-service/dubbo-service-user/user-biz/src/main/java/com/liyz/boot3/service/user/provider/auth/RemoteAuthServiceImpl.java
[ { "identifier": "BeanUtil", "path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/util/BeanUtil.java", "snippet": "@UtilityClass\npublic final class BeanUtil {\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @return ...
import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.common.util.DateUtil; import com.liyz.boot3.common.util.PatternUtil; import com.liyz.boot3.service.auth.bo.AuthUserBO; import com.liyz.boot3.service.auth.bo.AuthUserLoginBO; import com.liyz.boot3.service.auth.bo.AuthUserLogoutBO; import com.liyz.boot3.service.auth.bo.AuthUserRegisterBO; import com.liyz.boot3.service.auth.enums.Device; import com.liyz.boot3.service.auth.enums.LoginType; import com.liyz.boot3.service.auth.exception.AuthExceptionCodeEnum; import com.liyz.boot3.service.auth.exception.RemoteAuthServiceException; import com.liyz.boot3.service.auth.remote.RemoteAuthService; import com.liyz.boot3.service.user.model.*; import com.liyz.boot3.service.user.model.base.UserAuthBaseDO; import com.liyz.boot3.service.user.service.*; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.DubboService; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; import java.util.List; import java.util.Objects;
9,402
package com.liyz.boot3.service.user.provider.auth; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/3/10 11:10 */ @Slf4j @DubboService(tag = "user") public class RemoteAuthServiceImpl implements RemoteAuthService { @Resource private UserInfoService userInfoService; @Resource private UserAuthMobileService userAuthMobileService; @Resource private UserAuthEmailService userAuthEmailService; @Resource private UserLoginLogService userLoginLogService; @Resource private UserLogoutLogService userLogoutLogService; /** * 用户注册 * * @param authUserRegister 注册参数 * @return True:注册成功;false:注册失败 */ @Override @Transactional(rollbackFor = Exception.class) public Boolean registry(AuthUserRegisterBO authUserRegister) { String username = authUserRegister.getUsername(); boolean isEmail = PatternUtil.matchEmail(username); //判断该用户名是否存在 boolean userNameExist = isEmail ? Objects.nonNull(userAuthEmailService.getByUsername(username)) : Objects.nonNull(userAuthMobileService.getByUsername(username)); if (userNameExist) { throw new RemoteAuthServiceException(isEmail ? AuthExceptionCodeEnum.EMAIL_EXIST : AuthExceptionCodeEnum.MOBILE_EXIST); } UserInfoDO userInfoDO = BeanUtil.copyProperties(authUserRegister, UserInfoDO::new, (s, t) -> { if (isEmail) { t.setEmail(authUserRegister.getUsername()); } else { t.setMobile(authUserRegister.getUsername()); } t.setRegistryTime(DateUtil.currentDate()); }); userInfoService.save(userInfoDO); if (StringUtils.isNotBlank(userInfoDO.getMobile())) { UserAuthMobileDO mobileDO = UserAuthMobileDO.builder().mobile(userInfoDO.getMobile()).build(); mobileDO.setUserId(userInfoDO.getUserId()); mobileDO.setPassword(authUserRegister.getPassword()); userAuthMobileService.save(mobileDO); } if (StringUtils.isNotBlank(userInfoDO.getEmail())) { UserAuthEmailDO emailDO = UserAuthEmailDO.builder().email(userInfoDO.getEmail()).build(); emailDO.setUserId(userInfoDO.getUserId()); emailDO.setPassword(authUserRegister.getPassword()); userAuthEmailService.save(emailDO); } return Boolean.TRUE; } /** * 根据用户名查询用户信息 * * @param username 用户名 * @param device 登录设备 * @return 登录用户信息 */ @Override
package com.liyz.boot3.service.user.provider.auth; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/3/10 11:10 */ @Slf4j @DubboService(tag = "user") public class RemoteAuthServiceImpl implements RemoteAuthService { @Resource private UserInfoService userInfoService; @Resource private UserAuthMobileService userAuthMobileService; @Resource private UserAuthEmailService userAuthEmailService; @Resource private UserLoginLogService userLoginLogService; @Resource private UserLogoutLogService userLogoutLogService; /** * 用户注册 * * @param authUserRegister 注册参数 * @return True:注册成功;false:注册失败 */ @Override @Transactional(rollbackFor = Exception.class) public Boolean registry(AuthUserRegisterBO authUserRegister) { String username = authUserRegister.getUsername(); boolean isEmail = PatternUtil.matchEmail(username); //判断该用户名是否存在 boolean userNameExist = isEmail ? Objects.nonNull(userAuthEmailService.getByUsername(username)) : Objects.nonNull(userAuthMobileService.getByUsername(username)); if (userNameExist) { throw new RemoteAuthServiceException(isEmail ? AuthExceptionCodeEnum.EMAIL_EXIST : AuthExceptionCodeEnum.MOBILE_EXIST); } UserInfoDO userInfoDO = BeanUtil.copyProperties(authUserRegister, UserInfoDO::new, (s, t) -> { if (isEmail) { t.setEmail(authUserRegister.getUsername()); } else { t.setMobile(authUserRegister.getUsername()); } t.setRegistryTime(DateUtil.currentDate()); }); userInfoService.save(userInfoDO); if (StringUtils.isNotBlank(userInfoDO.getMobile())) { UserAuthMobileDO mobileDO = UserAuthMobileDO.builder().mobile(userInfoDO.getMobile()).build(); mobileDO.setUserId(userInfoDO.getUserId()); mobileDO.setPassword(authUserRegister.getPassword()); userAuthMobileService.save(mobileDO); } if (StringUtils.isNotBlank(userInfoDO.getEmail())) { UserAuthEmailDO emailDO = UserAuthEmailDO.builder().email(userInfoDO.getEmail()).build(); emailDO.setUserId(userInfoDO.getUserId()); emailDO.setPassword(authUserRegister.getPassword()); userAuthEmailService.save(emailDO); } return Boolean.TRUE; } /** * 根据用户名查询用户信息 * * @param username 用户名 * @param device 登录设备 * @return 登录用户信息 */ @Override
public AuthUserBO loadByUsername(String username, Device device) {
3
2023-11-13 01:28:21+00:00
12k
martin-bian/DimpleBlog
dimple-tools/src/main/java/com/dimple/service/impl/QiNiuServiceImpl.java
[ { "identifier": "QiniuConfig", "path": "dimple-tools/src/main/java/com/dimple/domain/QiniuConfig.java", "snippet": "@Data\n@Entity\n@Table(name = \"tool_qiniu_config\")\npublic class QiniuConfig implements Serializable {\n\n @Id\n @Column(name = \"config_id\")\n @ApiModelProperty(value = \"ID\"...
import com.alibaba.fastjson.JSON; import com.dimple.domain.QiniuConfig; import com.dimple.domain.QiniuContent; import com.dimple.exception.BadRequestException; import com.dimple.repository.QiNiuConfigRepository; import com.dimple.repository.QiniuContentRepository; import com.dimple.service.QiNiuService; import com.dimple.service.dto.QiniuQueryCriteria; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QiNiuUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.ValidationUtil; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.BucketManager; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.storage.model.FileInfo; import com.qiniu.util.Auth; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional;
7,214
package com.dimple.service.impl; /** * @className: QiNiuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "qiNiu") public class QiNiuServiceImpl implements QiNiuService { private final QiNiuConfigRepository qiNiuConfigRepository; private final QiniuContentRepository qiniuContentRepository; @Value("${qiniu.max-size}") private Long maxSize; @Override @Cacheable(key = "'id:1'") public QiniuConfig find() { Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L); return qiniuConfig.orElseGet(QiniuConfig::new); } @Override @CachePut(key = "'id:1'") @Transactional(rollbackFor = Exception.class) public QiniuConfig config(QiniuConfig qiniuConfig) { qiniuConfig.setId(1L); String http = "http://", https = "https://"; if (!(qiniuConfig.getHost().toLowerCase().startsWith(http) || qiniuConfig.getHost().toLowerCase().startsWith(https))) { throw new BadRequestException("外链域名必须以http://或者https://开头"); } return qiNiuConfigRepository.save(qiniuConfig); } @Override public Object queryAll(QiniuQueryCriteria criteria, Pageable pageable) { return PageUtil.toPage(qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); } @Override public List<QiniuContent> queryAll(QiniuQueryCriteria criteria) { return qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); } @Override @Transactional(rollbackFor = Exception.class) public QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig) {
package com.dimple.service.impl; /** * @className: QiNiuServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "qiNiu") public class QiNiuServiceImpl implements QiNiuService { private final QiNiuConfigRepository qiNiuConfigRepository; private final QiniuContentRepository qiniuContentRepository; @Value("${qiniu.max-size}") private Long maxSize; @Override @Cacheable(key = "'id:1'") public QiniuConfig find() { Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L); return qiniuConfig.orElseGet(QiniuConfig::new); } @Override @CachePut(key = "'id:1'") @Transactional(rollbackFor = Exception.class) public QiniuConfig config(QiniuConfig qiniuConfig) { qiniuConfig.setId(1L); String http = "http://", https = "https://"; if (!(qiniuConfig.getHost().toLowerCase().startsWith(http) || qiniuConfig.getHost().toLowerCase().startsWith(https))) { throw new BadRequestException("外链域名必须以http://或者https://开头"); } return qiNiuConfigRepository.save(qiniuConfig); } @Override public Object queryAll(QiniuQueryCriteria criteria, Pageable pageable) { return PageUtil.toPage(qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); } @Override public List<QiniuContent> queryAll(QiniuQueryCriteria criteria) { return qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); } @Override @Transactional(rollbackFor = Exception.class) public QiniuContent upload(MultipartFile file, QiniuConfig qiniuConfig) {
FileUtil.checkSize(maxSize, file.getSize());
7
2023-11-10 03:30:36+00:00
12k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/inputmeta/editcontainer/codecabinet/ModuleSetCodeCabinet.java
[ { "identifier": "ModuleSetCodeModel", "path": "database/src/main/java/com/lazycoder/database/model/command/ModuleSetCodeModel.java", "snippet": "@NoArgsConstructor\n@Data\npublic class ModuleSetCodeModel extends GeneralCommandPathCodeModel {\n\n /**\n * 类型名称\n */\n private String typeName ...
import com.lazycoder.database.model.command.ModuleSetCodeModel; import com.lazycoder.service.vo.datasourceedit.command.ContainerModel; import com.lazycoder.uidatasourceedit.DataSourceEditHolder; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.command.CommandCodeControl; import com.lazycoder.uidatasourceedit.inputmeta.editcontainer.codecabinet.tier.ModuleSetCodeTier; import com.lazycoder.uiutils.utils.SysUtil; import java.util.ArrayList;
8,761
package com.lazycoder.uidatasourceedit.inputmeta.editcontainer.codecabinet; public class ModuleSetCodeCabinet extends AbstractCodeCabinet { /** * */ private static final long serialVersionUID = 7306877878749024048L; private int typeSerialNumber; /** * @param theModel * @param operatingOrdinal * @param expanded * @param proportion */ public ModuleSetCodeCabinet(ContainerModel theModel, int typeSerialNumber, int operatingOrdinal, boolean expanded, double proportion) { super(expanded, proportion); this.operatingOrdinalNumber = operatingOrdinal; this.typeSerialNumber = typeSerialNumber; } /** * 获取代码模型列表 * * @return */ public ArrayList<ModuleSetCodeModel> getCodeModelList() { ArrayList<ModuleSetCodeModel> list = new ArrayList<>();
package com.lazycoder.uidatasourceedit.inputmeta.editcontainer.codecabinet; public class ModuleSetCodeCabinet extends AbstractCodeCabinet { /** * */ private static final long serialVersionUID = 7306877878749024048L; private int typeSerialNumber; /** * @param theModel * @param operatingOrdinal * @param expanded * @param proportion */ public ModuleSetCodeCabinet(ContainerModel theModel, int typeSerialNumber, int operatingOrdinal, boolean expanded, double proportion) { super(expanded, proportion); this.operatingOrdinalNumber = operatingOrdinal; this.typeSerialNumber = typeSerialNumber; } /** * 获取代码模型列表 * * @return */ public ArrayList<ModuleSetCodeModel> getCodeModelList() { ArrayList<ModuleSetCodeModel> list = new ArrayList<>();
ModuleSetCodeTier tempPane;
4
2023-11-16 11:55:06+00:00
12k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/MainFragment.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.Checkable; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.test.DeviceTestCallback; import kr.or.kashi.hde.util.DebugLog; import kr.or.kashi.hde.util.LocalPreferences; import kr.or.kashi.hde.util.LocalPreferences.Pref; import kr.or.kashi.hde.util.Utils; import kr.or.kashi.hde.widget.CheckableListAdapter; import kr.or.kashi.hde.widget.CustomLayoutManager; import kr.or.kashi.hde.widget.DebugLogView; import kr.or.kashi.hde.widget.DeviceInfoView; import kr.or.kashi.hde.widget.DeviceListAdapter; import kr.or.kashi.hde.widget.DeviceTestPartView; import kr.or.kashi.hde.widget.HomeDeviceView; import kr.or.kashi.hde.widget.NullRecyclerViewAdapter;
9,843
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien 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 kr.or.kashi.hde; public class MainFragment extends Fragment { private static final String TAG = "HomeTestFragment"; private static final String SAVED_DEVICES_FILENAME = "saved_devices"; private final Context mContext; private final HomeNetwork mNetwork; private HomeDevice mSelectedDevice; private CheckBox mEventLogCheck; private CheckBox mTxRxLogCheck; private ToggleButton mAutoScrollToggle; private DebugLogView mDebugLogView; private ToggleButton mDiscoveryToggle; private ListView mDeviceTypeListView; private CheckBox mGroupIdCheckBox; private SeekBar mGroupIdSeekBar; private TextView mGroupIdTextView; private ToggleButton mGroupFullToggle; private CheckBox mSingleIdCheckBox; private SeekBar mSingleIdSeekBar; private TextView mSingleIdTextView; private ToggleButton mSingleFullToggle; private TextView mRangeTextView; private Spinner mPollingIntervalsSpinner; private ToggleButton mAutoTestToggle; private TextView mDeviceCountText; private RecyclerView mDeviceListView; private ProgressBar mDiscoveryProgress; private ViewGroup mDeviceDetailPart; private DeviceInfoView mDeviceInfoView; private ViewGroup mDeviceControlArea; private DeviceTestPartView mDeviceTestPart; private Map<String, Integer> mDeviceToKsIdMap = new TreeMap<>(); private Set<String> mSelectedDeviceTypes = new HashSet<>(); private DeviceDiscovery.Callback mDiscoveryCallback = new DeviceDiscovery.Callback() { List<HomeDevice> mStagedDevices = new ArrayList<>(); @Override public void onDiscoveryStarted() { debug("onDiscoveryStarted "); mDiscoveryProgress.setVisibility(View.VISIBLE); mStagedDevices.clear(); } @Override public void onDiscoveryFinished() { debug("onDiscoveryFinished "); if (mStagedDevices.size() > 0) { for (HomeDevice device: mStagedDevices) { mNetwork.addDevice(device); } mStagedDevices.clear(); } // Wait for a while until new devices are up to date by polling its state new Handler().postDelayed(() -> { updateDeviceList(); mDiscoveryProgress.setVisibility(View.GONE); mDiscoveryToggle.setChecked(false); }, 1000); } @Override public void onDeviceDiscovered(HomeDevice device) { final String clsName = device.getClass().getSimpleName(); debug("onDeviceDiscovered " + clsName + " " + device.getAddress()); mStagedDevices.add(device); } }; private HomeDevice.Callback mDeviceCallback = new HomeDevice.Callback() { public void onPropertyChanged(HomeDevice device, PropertyMap props) { for (String name : props.toMap().keySet()) { debug("onPropertyChanged - " + name + " : " + device.dc().getProperty(name).getValue()); } } public void onErrorOccurred(HomeDevice device, int error) { debug("onErrorOccurred:" + error); } }; public MainFragment(Context context, HomeNetwork network) { mContext = context; mNetwork = network; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNetwork.getDeviceDiscovery().addCallback(mDiscoveryCallback); mDeviceToKsIdMap.put("AirConditioner", 0x02); mDeviceToKsIdMap.put("BatchSwitch", 0x33); mDeviceToKsIdMap.put("Curtain", 0x13); mDeviceToKsIdMap.put("DoorLock", 0x31); mDeviceToKsIdMap.put("GasValve", 0x12); mDeviceToKsIdMap.put("HouseMeter", 0x30); mDeviceToKsIdMap.put("Light", 0x0E); mDeviceToKsIdMap.put("PowerSaver", 0x39); mDeviceToKsIdMap.put("Thermostat", 0x36); mDeviceToKsIdMap.put("Ventilation", 0x32); mSelectedDeviceTypes = LocalPreferences.getSelectedDeviceTypes(); } @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) { final View v = inflater.inflate(R.layout.main, container, false); v.findViewById(R.id.clear_log_button).setOnClickListener(view -> { mDebugLogView.clear(); mAutoScrollToggle.setChecked(true); mDebugLogView.setAutoScroll(true); }); mEventLogCheck = (CheckBox) v.findViewById(R.id.event_log_check); mEventLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_EVENT_ENABLED, true)); mEventLogCheck.setOnClickListener(view -> updateLogFilter()); mTxRxLogCheck = (CheckBox) v.findViewById(R.id.txrx_log_check); mTxRxLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_TXRX_ENABLED, true)); mTxRxLogCheck.setOnClickListener(view -> updateLogFilter()); mAutoScrollToggle = (ToggleButton) v.findViewById(R.id.auto_scroll_toggle);; mAutoScrollToggle.setOnClickListener(view -> mDebugLogView.setAutoScroll(((Checkable)view).isChecked())); mDebugLogView = (DebugLogView) v.findViewById(R.id.debug_log_view);
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien 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 kr.or.kashi.hde; public class MainFragment extends Fragment { private static final String TAG = "HomeTestFragment"; private static final String SAVED_DEVICES_FILENAME = "saved_devices"; private final Context mContext; private final HomeNetwork mNetwork; private HomeDevice mSelectedDevice; private CheckBox mEventLogCheck; private CheckBox mTxRxLogCheck; private ToggleButton mAutoScrollToggle; private DebugLogView mDebugLogView; private ToggleButton mDiscoveryToggle; private ListView mDeviceTypeListView; private CheckBox mGroupIdCheckBox; private SeekBar mGroupIdSeekBar; private TextView mGroupIdTextView; private ToggleButton mGroupFullToggle; private CheckBox mSingleIdCheckBox; private SeekBar mSingleIdSeekBar; private TextView mSingleIdTextView; private ToggleButton mSingleFullToggle; private TextView mRangeTextView; private Spinner mPollingIntervalsSpinner; private ToggleButton mAutoTestToggle; private TextView mDeviceCountText; private RecyclerView mDeviceListView; private ProgressBar mDiscoveryProgress; private ViewGroup mDeviceDetailPart; private DeviceInfoView mDeviceInfoView; private ViewGroup mDeviceControlArea; private DeviceTestPartView mDeviceTestPart; private Map<String, Integer> mDeviceToKsIdMap = new TreeMap<>(); private Set<String> mSelectedDeviceTypes = new HashSet<>(); private DeviceDiscovery.Callback mDiscoveryCallback = new DeviceDiscovery.Callback() { List<HomeDevice> mStagedDevices = new ArrayList<>(); @Override public void onDiscoveryStarted() { debug("onDiscoveryStarted "); mDiscoveryProgress.setVisibility(View.VISIBLE); mStagedDevices.clear(); } @Override public void onDiscoveryFinished() { debug("onDiscoveryFinished "); if (mStagedDevices.size() > 0) { for (HomeDevice device: mStagedDevices) { mNetwork.addDevice(device); } mStagedDevices.clear(); } // Wait for a while until new devices are up to date by polling its state new Handler().postDelayed(() -> { updateDeviceList(); mDiscoveryProgress.setVisibility(View.GONE); mDiscoveryToggle.setChecked(false); }, 1000); } @Override public void onDeviceDiscovered(HomeDevice device) { final String clsName = device.getClass().getSimpleName(); debug("onDeviceDiscovered " + clsName + " " + device.getAddress()); mStagedDevices.add(device); } }; private HomeDevice.Callback mDeviceCallback = new HomeDevice.Callback() { public void onPropertyChanged(HomeDevice device, PropertyMap props) { for (String name : props.toMap().keySet()) { debug("onPropertyChanged - " + name + " : " + device.dc().getProperty(name).getValue()); } } public void onErrorOccurred(HomeDevice device, int error) { debug("onErrorOccurred:" + error); } }; public MainFragment(Context context, HomeNetwork network) { mContext = context; mNetwork = network; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNetwork.getDeviceDiscovery().addCallback(mDiscoveryCallback); mDeviceToKsIdMap.put("AirConditioner", 0x02); mDeviceToKsIdMap.put("BatchSwitch", 0x33); mDeviceToKsIdMap.put("Curtain", 0x13); mDeviceToKsIdMap.put("DoorLock", 0x31); mDeviceToKsIdMap.put("GasValve", 0x12); mDeviceToKsIdMap.put("HouseMeter", 0x30); mDeviceToKsIdMap.put("Light", 0x0E); mDeviceToKsIdMap.put("PowerSaver", 0x39); mDeviceToKsIdMap.put("Thermostat", 0x36); mDeviceToKsIdMap.put("Ventilation", 0x32); mSelectedDeviceTypes = LocalPreferences.getSelectedDeviceTypes(); } @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) { final View v = inflater.inflate(R.layout.main, container, false); v.findViewById(R.id.clear_log_button).setOnClickListener(view -> { mDebugLogView.clear(); mAutoScrollToggle.setChecked(true); mDebugLogView.setAutoScroll(true); }); mEventLogCheck = (CheckBox) v.findViewById(R.id.event_log_check); mEventLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_EVENT_ENABLED, true)); mEventLogCheck.setOnClickListener(view -> updateLogFilter()); mTxRxLogCheck = (CheckBox) v.findViewById(R.id.txrx_log_check); mTxRxLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_TXRX_ENABLED, true)); mTxRxLogCheck.setOnClickListener(view -> updateLogFilter()); mAutoScrollToggle = (ToggleButton) v.findViewById(R.id.auto_scroll_toggle);; mAutoScrollToggle.setOnClickListener(view -> mDebugLogView.setAutoScroll(((Checkable)view).isChecked())); mDebugLogView = (DebugLogView) v.findViewById(R.id.debug_log_view);
DebugLog.setLogger(mDebugLogView);
2
2023-11-10 01:19:44+00:00
12k
erhenjt/twoyi2
app/src/main/java/io/twoyi/ui/SelectAppActivity.java
[ { "identifier": "AppKV", "path": "app/src/main/java/io/twoyi/utils/AppKV.java", "snippet": "public class AppKV {\n\n\n private static final String PREF_NAME = \"app_kv\";\n\n public static final String ADD_APP_NOT_SHOW_SYSTEM= \"add_app_not_show_system\";\n public static final String ADD_APP_NO...
import android.app.Activity; import android.app.ProgressDialog; import android.content.ClipData; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.net.Uri; import android.os.Bundle; import android.os.SystemClock; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.core.view.MenuItemCompat; import androidx.core.widget.CompoundButtonCompat; import com.afollestad.materialdialogs.MaterialDialog; import com.github.clans.fab.FloatingActionButton; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import io.twoyi.R; import io.twoyi.utils.AppKV; import io.twoyi.utils.CacheManager; import io.twoyi.utils.IOUtils; import io.twoyi.utils.Installer; import io.twoyi.utils.UIHelper; import io.twoyi.utils.image.GlideModule;
7,884
} private List<File> copyFilesFromUri(List<Uri> fileUris) { List<File> files = new ArrayList<>(); ContentResolver contentResolver = getContentResolver(); for (Uri uri : fileUris) { long now = System.currentTimeMillis(); File tmpFile = new File(getCacheDir(), now + ".apk"); Log.i(TAG, "copyFilesFromUri temp file: " + tmpFile); try (InputStream inputStream = contentResolver.openInputStream(uri); OutputStream os = new FileOutputStream(tmpFile)) { byte[] buffer = new byte[1024]; int count; while ((count = inputStream.read(buffer)) > 0) { os.write(buffer, 0, count); } } catch (IOException e) { continue; } files.add(tmpFile); } return files; } private void startInstall(List<File> result, ProgressDialog dialog, boolean cleanFile) { Installer.installAsync(getApplicationContext(), result, new Installer.InstallResult() { @Override public void onSuccess(List<File> files) { if (cleanFile) { IOUtils.deleteAll(files); } runOnUiThread(() -> { Toast.makeText(getApplicationContext(), R.string.install_success, Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); }); } @Override public void onFail(List<File> files, String msg) { if (cleanFile) { IOUtils.deleteAll(files); } runOnUiThread(() -> { Toast.makeText(getApplicationContext(), getResources().getString(R.string.install_failed_reason, msg), Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); }); } }); } private void loadAsync() { mEmptyView.setText(null); mDisplayItems.clear(); MaterialDialog progressDialog = UIHelper.getNumberProgressDialog(this); UIHelper.show(progressDialog); // 是否从别的地方过来的,这种情况下不做任何过滤。 boolean specified = specifiedPackages.size() > 0; AtomicBoolean specifiedFound = new AtomicBoolean(false); long start = SystemClock.elapsedRealtime(); UIHelper.defer().when(() -> { PackageManager packageManager = getPackageManager(); if (packageManager == null) { return Collections.<AppItem>emptyList(); } List<ApplicationInfo> apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA); runOnUiThread(() -> progressDialog.setMaxProgress(apps.size())); List<AppItem> appItems = new ArrayList<>(); int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; PackageInfo sys = packageManager.getPackageInfo( "android", PackageManager.GET_SIGNATURES); boolean directlyAdd = true; boolean noSystemApps = AppKV.getBooleanConfig(getApplicationContext(), AppKV.ADD_APP_NOT_SHOW_SYSTEM, true); boolean no32BitApps = AppKV.getBooleanConfig(getApplicationContext(), AppKV.ADD_APP_NOT_SHOW_32BIT, true); for (ApplicationInfo app : apps) { // 自己忽略 runOnUiThread(() -> progressDialog.incrementProgress(1)); if (TextUtils.equals(getPackageName(), app.packageName)) { continue; } // 检查系统应用 boolean isSystemApp = (app.flags & mask) != 0 || isSystemApp(packageManager, app.packageName, sys); if (isSystemApp) { // 如果是系统应用 if (!directlyAdd) { // 非 magisk 模式直接跳过,因为不可能支持 continue; } if (noSystemApps && !specified) { // magisk 模式如果设置了 "不显示系统" 也忽略 // 如果是从别的地方跳转过来的,那么忽略 continue; } } if (no32BitApps) { if (!UIHelper.isAppSupport64bit(app)) { continue; } } AppItem appItem = new AppItem(); appItem.applicationInfo = app;
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package io.twoyi.ui; /** * @author weishu * @date 2018/7/21. */ public class SelectAppActivity extends AppCompatActivity { private static final String TAG = "SelectAppActivity"; private static final int REQUEST_GET_FILE = 1; private static int TAG_KEY = R.id.create_app_list; private ListAppAdapter mAdapter; private final List<AppItem> mDisplayItems = new ArrayList<>(); private final List<AppItem> mAllApps = new ArrayList<>(); private AppItem mSelectItem; private TextView mEmptyView; private final Set<String> specifiedPackages = new HashSet<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_createapp); ListView mListView = findViewById(R.id.create_app_list); mAdapter = new ListAppAdapter(); mListView.setAdapter(mAdapter); mEmptyView = findViewById(R.id.empty_view); mListView.setEmptyView(mEmptyView); FloatingActionButton mFloatButton = findViewById(R.id.create_app_from_external); mFloatButton.setColorNormalResId(R.color.colorPrimary); mFloatButton.setColorPressedResId(R.color.colorPrimaryOpacity); mFloatButton.setOnClickListener((v) -> { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.setType("application/vnd.android.package-archive"); // apk file intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult(intent, REQUEST_GET_FILE); } catch (Throwable ignored) { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); } }); TextView createApp = findViewById(R.id.create_app_btn); createApp.setBackgroundResource(R.color.colorPrimary); createApp.setText(R.string.select_app_button); createApp.setOnClickListener((v) -> { Set<AppItem> selectedApps = new HashSet<>(); for (AppItem displayItem : mDisplayItems) { if (displayItem.selected) { selectedApps.add(displayItem); } } if (selectedApps.isEmpty()) { Toast.makeText(this, R.string.select_app_tips, Toast.LENGTH_SHORT).show(); return; } selectComplete(selectedApps); }); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary)); actionBar.setTitle(R.string.create_app_activity); } Intent intent = getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null && TextUtils.equals(data.getScheme(), "package")) { String schemeSpecificPart = data.getSchemeSpecificPart(); if (schemeSpecificPart != null) { String[] split = schemeSpecificPart.split("\\|"); specifiedPackages.clear(); specifiedPackages.addAll(Arrays.asList(split)); } } } if (true) { int size = specifiedPackages.size(); if (size > 1) { specifiedPackages.clear(); } } loadAsync(); } private void selectComplete(Set<AppItem> pkgs) { if (pkgs.size() != 1) { // TODO: support install mutilpe apps together Toast.makeText(getApplicationContext(), R.string.please_install_one_by_one, Toast.LENGTH_SHORT).show(); return; } ProgressDialog progressDialog = UIHelper.getProgressDialog(this); progressDialog.setCancelable(false); progressDialog.show(); for (AppItem pkg : pkgs) { List<File> apks = new ArrayList<>(); ApplicationInfo applicationInfo = pkg.applicationInfo; // main apk String sourceDir = applicationInfo.sourceDir; apks.add(new File(sourceDir)); String[] splitSourceDirs = applicationInfo.splitSourceDirs; if (splitSourceDirs != null) { for (String splitSourceDir : splitSourceDirs) { apks.add(new File(splitSourceDir)); } } startInstall(apks, progressDialog, false); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_menu, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); // 当SearchView获得焦点时弹出软键盘的类型,就是设置输入类型 searchView.setIconified(false); searchView.onActionViewExpanded(); searchView.setInputType(EditorInfo.TYPE_CLASS_TEXT); // 设置回车键表示查询操作 searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH); // 为searchView添加事件 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { // 输入后点击回车改变文本 @Override public boolean onQueryTextSubmit(String query) { return false; } // 随着输入改变文本 @Override public boolean onQueryTextChange(String newText) { filterListByText(newText); return false; } }); searchView.setOnCloseListener(() -> { mDisplayItems.clear(); mDisplayItems.addAll(mAllApps); notifyDataSetChangedWithSort(); return false; }); setFilterMenuItem(menu, R.id.menu_not_show_system, AppKV.ADD_APP_NOT_SHOW_SYSTEM, true); setFilterMenuItem(menu, R.id.menu_not_show_32bit, AppKV.ADD_APP_NOT_SHOW_32BIT, true); return super.onCreateOptionsMenu(menu); } private MenuItem setFilterMenuItem(Menu menu, int id, String key, boolean defalutValue) { MenuItem menuItem = menu.findItem(id); menuItem.setChecked(AppKV.getBooleanConfig(getApplicationContext(), key, defalutValue)); menuItem.setOnMenuItemClickListener(item -> { boolean checked = !item.isChecked(); item.setChecked(checked); AppKV.setBooleanConfig(getApplicationContext(), key, checked); // 重新加载所有配置 // loadAsync 的时候会检查这个标记 loadAsync(); return true; }); return menuItem; } private void filterListByText(String query) { if (TextUtils.isEmpty(query)) { mDisplayItems.clear(); mDisplayItems.addAll(mAllApps); notifyDataSetChangedWithSort(); return; } List<AppItem> newApps = new ArrayList<>(); Set<CharSequence> pkgs = new HashSet<>(); for (AppItem mAllApp : mAllApps) { pkgs.add(mAllApp.pkg); } for (AppItem appItem : mAllApps) { String name = appItem.name.toString().toLowerCase(Locale.ROOT); String pkg = appItem.pkg.toString().toLowerCase(Locale.ROOT); String queryLower = query.toLowerCase(Locale.ROOT); if (name.contains(queryLower) || pkg.contains(queryLower)) { newApps.add(appItem); } if (appItem.selected && !pkgs.contains(appItem.pkg)) { newApps.add(appItem); } } mDisplayItems.clear(); mDisplayItems.addAll(newApps); notifyDataSetChangedWithSort(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (!(requestCode == REQUEST_GET_FILE && resultCode == Activity.RESULT_OK)) { return; } if (data == null) { return; } ClipData clipData = data.getClipData(); List<Uri> fileUris = new ArrayList<>(); if (clipData == null) { // single file fileUris.add(data.getData()); } else { // multiple file int itemCount = clipData.getItemCount(); for (int i = 0; i < itemCount; i++) { ClipData.Item item = clipData.getItemAt(i); Uri uri = item.getUri(); fileUris.add(uri); } } if (fileUris.isEmpty()) { Toast.makeText(getApplicationContext(), R.string.select_app_app_not_found, Toast.LENGTH_SHORT).show(); return; } ProgressDialog dialog = UIHelper.getProgressDialog(this); dialog.setCancelable(false); dialog.show(); // start copy and install UIHelper.defer().when(() -> { List<File> files = copyFilesFromUri(fileUris); Log.i(TAG, "files copied: " + files); boolean allValid = Installer.checkFile(getApplicationContext(), files); if (!allValid) { IOUtils.deleteAll(files); throw new RuntimeException("invalid apk file!"); } return files; }).done(result -> startInstall(result, dialog, false)) .fail(result -> runOnUiThread(() -> { Toast.makeText(getApplicationContext(), getResources().getString(R.string.install_failed_reason, result.getMessage()), Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); })); } private List<File> copyFilesFromUri(List<Uri> fileUris) { List<File> files = new ArrayList<>(); ContentResolver contentResolver = getContentResolver(); for (Uri uri : fileUris) { long now = System.currentTimeMillis(); File tmpFile = new File(getCacheDir(), now + ".apk"); Log.i(TAG, "copyFilesFromUri temp file: " + tmpFile); try (InputStream inputStream = contentResolver.openInputStream(uri); OutputStream os = new FileOutputStream(tmpFile)) { byte[] buffer = new byte[1024]; int count; while ((count = inputStream.read(buffer)) > 0) { os.write(buffer, 0, count); } } catch (IOException e) { continue; } files.add(tmpFile); } return files; } private void startInstall(List<File> result, ProgressDialog dialog, boolean cleanFile) { Installer.installAsync(getApplicationContext(), result, new Installer.InstallResult() { @Override public void onSuccess(List<File> files) { if (cleanFile) { IOUtils.deleteAll(files); } runOnUiThread(() -> { Toast.makeText(getApplicationContext(), R.string.install_success, Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); }); } @Override public void onFail(List<File> files, String msg) { if (cleanFile) { IOUtils.deleteAll(files); } runOnUiThread(() -> { Toast.makeText(getApplicationContext(), getResources().getString(R.string.install_failed_reason, msg), Toast.LENGTH_SHORT).show(); dialog.dismiss(); finish(); }); } }); } private void loadAsync() { mEmptyView.setText(null); mDisplayItems.clear(); MaterialDialog progressDialog = UIHelper.getNumberProgressDialog(this); UIHelper.show(progressDialog); // 是否从别的地方过来的,这种情况下不做任何过滤。 boolean specified = specifiedPackages.size() > 0; AtomicBoolean specifiedFound = new AtomicBoolean(false); long start = SystemClock.elapsedRealtime(); UIHelper.defer().when(() -> { PackageManager packageManager = getPackageManager(); if (packageManager == null) { return Collections.<AppItem>emptyList(); } List<ApplicationInfo> apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA); runOnUiThread(() -> progressDialog.setMaxProgress(apps.size())); List<AppItem> appItems = new ArrayList<>(); int mask = ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; PackageInfo sys = packageManager.getPackageInfo( "android", PackageManager.GET_SIGNATURES); boolean directlyAdd = true; boolean noSystemApps = AppKV.getBooleanConfig(getApplicationContext(), AppKV.ADD_APP_NOT_SHOW_SYSTEM, true); boolean no32BitApps = AppKV.getBooleanConfig(getApplicationContext(), AppKV.ADD_APP_NOT_SHOW_32BIT, true); for (ApplicationInfo app : apps) { // 自己忽略 runOnUiThread(() -> progressDialog.incrementProgress(1)); if (TextUtils.equals(getPackageName(), app.packageName)) { continue; } // 检查系统应用 boolean isSystemApp = (app.flags & mask) != 0 || isSystemApp(packageManager, app.packageName, sys); if (isSystemApp) { // 如果是系统应用 if (!directlyAdd) { // 非 magisk 模式直接跳过,因为不可能支持 continue; } if (noSystemApps && !specified) { // magisk 模式如果设置了 "不显示系统" 也忽略 // 如果是从别的地方跳转过来的,那么忽略 continue; } } if (no32BitApps) { if (!UIHelper.isAppSupport64bit(app)) { continue; } } AppItem appItem = new AppItem(); appItem.applicationInfo = app;
appItem.name = CacheManager.getLabel(getApplicationContext(), app, packageManager);
1
2023-11-11 22:08:20+00:00
12k
EmonerRobotics/2023Robot
src/main/java/frc/robot/commands/autonomous/AutoCommand.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n\n public static class LimelightConstants{\n public static double goalHeightInches = 30.31496; //30.31496\n }\n\n public final class LiftMeasurements{\n public static final...
import java.util.List; import java.util.Map; import com.pathplanner.lib.PathConstraints; import com.pathplanner.lib.PathPlanner; import com.pathplanner.lib.PathPlannerTrajectory; import com.pathplanner.lib.auto.PIDConstants; import com.pathplanner.lib.auto.SwerveAutoBuilder; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import frc.robot.Constants; import frc.robot.RobotContainer; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils;
7,935
package frc.robot.commands.autonomous; public class AutoCommand { //LiftSubsystem liftSubsystem = new LiftSubsystem(); SmartDashboard smartDashboard; //static HashMap<String, Command> eventMap = new HashMap<>(); static Map<String, Command> eventMap = Map.of( "event1", new InstantCommand(() -> System.out.println("event triggered"))); public static Command makeAutoCommand(Drivetrain drivetrain, PoseEstimation poseEstimation, String name) { name = name.concat(AllianceUtils.isBlue()? ".blue" : ".red"); List<PathPlannerTrajectory> pathGroup = PathPlanner.loadPathGroup(name, new PathConstraints(Constants.AutoConstants.MAX_SPEED_METERS_PER_SECOND, Constants.AutoConstants.MAX_ACCELERATION_METERS_PER_SECOND_SQUARED));
package frc.robot.commands.autonomous; public class AutoCommand { //LiftSubsystem liftSubsystem = new LiftSubsystem(); SmartDashboard smartDashboard; //static HashMap<String, Command> eventMap = new HashMap<>(); static Map<String, Command> eventMap = Map.of( "event1", new InstantCommand(() -> System.out.println("event triggered"))); public static Command makeAutoCommand(Drivetrain drivetrain, PoseEstimation poseEstimation, String name) { name = name.concat(AllianceUtils.isBlue()? ".blue" : ".red"); List<PathPlannerTrajectory> pathGroup = PathPlanner.loadPathGroup(name, new PathConstraints(Constants.AutoConstants.MAX_SPEED_METERS_PER_SECOND, Constants.AutoConstants.MAX_ACCELERATION_METERS_PER_SECOND_SQUARED));
RobotContainer.field.getObject("Auto Path").setTrajectory(pathGroup.get(0));
1
2023-11-18 14:02:20+00:00
12k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/SkyBlock.java
[ { "identifier": "CommandRegistry", "path": "src/main/java/com/sweattypalms/skyblock/commands/CommandRegistry.java", "snippet": "public class CommandRegistry {\n private static CommandRegistry instance;\n private final Map<String, MethodContainer> commands = new HashMap<>();\n\n public CommandRe...
import com.sweattypalms.skyblock.commands.CommandRegistry; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.items.ItemManager; import com.sweattypalms.skyblock.core.items.builder.reforges.ReforgeManager; import com.sweattypalms.skyblock.core.mobs.builder.MobManager; import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonManager; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.world.WorldManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import org.reflections.Reflections; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.Set;
8,247
package com.sweattypalms.skyblock; // TODO: Work on skills + loot. public final class SkyBlock extends JavaPlugin { private static SkyBlock instance; public static SkyBlock getInstance() { return instance; } public boolean debug = true; @Override public void onEnable() { instance = this; long start = System.currentTimeMillis(); this.registerServer(); // Init the plugin asynchronously to speed up Bukkit.getScheduler().runTaskAsynchronously(this, () -> { registerCommands(); registerListeners(); registerCraft(); configs(); long end = System.currentTimeMillis() - start; System.out.println(ChatColor.GREEN + "Skyblock has been enabled! This took " + ChatColor.YELLOW + end + "ms"); }); drawAscii(); Bukkit.getOnlinePlayers().forEach(SkyblockPlayer::newPlayer); } private void registerServer() {
package com.sweattypalms.skyblock; // TODO: Work on skills + loot. public final class SkyBlock extends JavaPlugin { private static SkyBlock instance; public static SkyBlock getInstance() { return instance; } public boolean debug = true; @Override public void onEnable() { instance = this; long start = System.currentTimeMillis(); this.registerServer(); // Init the plugin asynchronously to speed up Bukkit.getScheduler().runTaskAsynchronously(this, () -> { registerCommands(); registerListeners(); registerCraft(); configs(); long end = System.currentTimeMillis() - start; System.out.println(ChatColor.GREEN + "Skyblock has been enabled! This took " + ChatColor.YELLOW + end + "ms"); }); drawAscii(); Bukkit.getOnlinePlayers().forEach(SkyblockPlayer::newPlayer); } private void registerServer() {
WorldManager.init();
7
2023-11-15 15:05:58+00:00
12k
cometcake575/Origins-Reborn
src/main/java/com/starshootercity/abilities/AbilityRegister.java
[ { "identifier": "Origin", "path": "src/main/java/com/starshootercity/Origin.java", "snippet": "public class Origin {\n private final ItemStack icon;\n private final int position;\n private final char impact;\n private final String name;\n private final List<Key> abilities;\n private fi...
import com.starshootercity.Origin; import com.starshootercity.OriginSwapper; import com.starshootercity.OriginsReborn; import net.kyori.adventure.key.Key; import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.craftbukkit.v1_20_R3.entity.CraftEntity; import org.bukkit.craftbukkit.v1_20_R3.entity.CraftPlayer; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.potion.PotionEffectType; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
7,910
package com.starshootercity.abilities; public class AbilityRegister { public static Map<Key, Ability> abilityMap = new HashMap<>(); public static Map<Key, DependencyAbility> dependencyAbilityMap = new HashMap<>(); public static void registerAbility(Ability ability) { abilityMap.put(ability.getKey(), ability); if (ability instanceof DependencyAbility dependencyAbility) { dependencyAbilityMap.put(ability.getKey(), dependencyAbility); } if (ability instanceof Listener listener) { Bukkit.getPluginManager().registerEvents(listener, OriginsReborn.getInstance()); } } public static void runForAbility(Entity entity, Key key, Runnable runnable) { runForAbility(entity, key, runnable, () -> {}); } public static boolean hasAbility(Player player, Key key) {
package com.starshootercity.abilities; public class AbilityRegister { public static Map<Key, Ability> abilityMap = new HashMap<>(); public static Map<Key, DependencyAbility> dependencyAbilityMap = new HashMap<>(); public static void registerAbility(Ability ability) { abilityMap.put(ability.getKey(), ability); if (ability instanceof DependencyAbility dependencyAbility) { dependencyAbilityMap.put(ability.getKey(), dependencyAbility); } if (ability instanceof Listener listener) { Bukkit.getPluginManager().registerEvents(listener, OriginsReborn.getInstance()); } } public static void runForAbility(Entity entity, Key key, Runnable runnable) { runForAbility(entity, key, runnable, () -> {}); } public static boolean hasAbility(Player player, Key key) {
Origin origin = OriginSwapper.getOrigin(player);
0
2023-11-10 21:39:16+00:00
12k
Hikaito/Fox-Engine
src/system/layerTree/data/LayerManager.java
[ { "identifier": "LayerTreeGui", "path": "src/system/gui/editorPane/LayerTreeGui.java", "snippet": "public class LayerTreeGui {\n\n // generate base unit used by both folder and layer bar\n public static JPanel makeFiletreeBar(int level){\n JPanel panel = new JPanel(); // generate panel\n...
import system.gui.editorPane.LayerTreeGui; import system.gui.editorPane.LayerEditorPane; import system.backbone.Copy; import system.layerTree.interfaces.LayerTreeFolder; import system.layerTree.interfaces.Renderable; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.util.*; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import system.Program; import system.backbone.VersionNumber; import system.gui.WarningWindow;
9,019
if(layer instanceof Folder){ //transfer children from layer to parent (in reverse order to the parent's old index) //Note: this can be improved by shifting all items at once LinkedList<TreeUnit> list = ((Folder)layer).getChildren(); ListIterator<TreeUnit> iterator = list.listIterator(list.size()); //iterate over children while(iterator.hasPrevious()){ children.add(index, iterator.previous()); } // reset parents of deleted elements for(TreeUnit child : children){ child.setParent(parent); } } } //redraw layer GUI and canvas GUI Program.redrawAllRegions(); } //endregion //region image rendering and helper functions----------------------------------- // resets all renderable children's parents [helper] public void generateTreeParents(){ ((TreeUnit)root).setParent(null); // reset root to orphan generateTreeParents(root); // recurse on root } // recursive function private void generateTreeParents(LayerTreeFolder parent){ LinkedList<TreeUnit> children = parent.getChildren(); // for each offspring, reset parent for(TreeUnit child : children){ child.setParent( parent); // set parent // if also filetreefolder, recurse if (child instanceof LayerTreeFolder){ generateTreeParents((LayerTreeFolder) child); } } } // pings children image in need of regeneration up the tree to the root public void markImageForRender(TreeUnit obj){ // mark current layer as re-render if (obj instanceof Renderable) ((Renderable) obj).requireRender(); // mark all applicable parents: starting with the current image, pass the render mark up the tree LayerTreeFolder parent = obj.getParent(); while(parent != null){ if (parent instanceof Renderable) ((Renderable) parent).requireRender(); parent = ((TreeUnit) parent).getParent(); } } // markImageForRerender but skips the first layer public void markParentForRender(TreeUnit obj){ // mark current layer as re-render if (obj.getParent() != null) markImageForRender((TreeUnit) obj.getParent()); } //public interface to get layer stack public BufferedImage stackImage(){ return ((Renderable)root).getImage(); } //endregion //region GUI layer layout render------------------------------- //internal state variables private JPanel layerTreePanel = new JPanel(); //panel for holding layer gui private JPanel layerEditPanel = new JPanel(); //panel for holding editor information //global accessors public JPanel getLayerTreePanel(){return layerTreePanel;} public JPanel getLayerEditorPanel(){return layerEditPanel;} // initializations private void initializeGUI(){ // layerTreePanel intializations layerTreePanel.setLayout(new BoxLayout(layerTreePanel, BoxLayout.Y_AXIS)); //create box layout in vertical: stack children elements //layerTreePanel.setBackground(Color.lightGray); // layerEditPanel initializations layerEditPanel.setMinimumSize(new Dimension(100, 300)); layerEditPanel.setMaximumSize(new Dimension(9000, 300)); //layerEditPanel.setBorder(BorderFactory.createLineBorder(Color.darkGray)); //draw element borders layerEditPanel.setLayout(new BoxLayout(layerEditPanel, BoxLayout.Y_AXIS)); //set layout to vertical box, so items stack vertically //layerEditPanel.setBackground(Color.BLACK); // spacing requirement (keeps it from being cropped with resize) layerEditPanel.setPreferredSize(new Dimension(300, 100)); } // regenerate tree gui public void rebuildLayerTree(){ //clear gui layerTreePanel.removeAll(); //recursively build gui LayerTreeGui.buildPanel(layerTreePanel, 1, ((Folder)root)); //refresh gui layerEditPanel.revalidate(); //redraws components layerEditPanel.repaint(); //repaints base rectangle when elements are removed } // regenerate editor gui public void rebuildEditorPanel(){ // remove elements in panel layerEditPanel.removeAll(); //Selection type: single object if(Program.getSelectionStatus() == SelectionManager.selectionPriority.PRIMARY){ TreeUnit top = Program.peekSelectionTop(); // get selected element // object type: Layer if(top instanceof Layer){ //LayermapLayerEditPane.add(layerEditPanel, (LayerCORE) top);
package system.layerTree.data; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class LayerManager { //region internal state variables ------------------------------------ // enum to describe whether to insert at the top or the bottom public enum position{TOP, BOTTOM}; public enum direction {UP, DOWN, IN, OUT}; public position defaultLocation = position.TOP; // default location fixme control object // project root @Expose @SerializedName(value = "root") private Folder root = new Folder(); //root level layer: sentinel object that doesn't hold information // project ID: should not change @Expose @SerializedName(value = "project_ID") private String projectID = Program.getProjectID(); public void setProjectID(String id){ projectID = id; } // project name //fixme can be used for default file save name //fixme currently no way to change this @Expose @SerializedName(value = "project_name") private String projectTitle = "[no title]"; public void setProjectTitle(String title){ projectTitle = title; } // version number @Expose @SerializedName(value="program_version") protected VersionNumber programVersion = Program.getProgramVersion(); // default to program version public VersionNumber getProgramVersion(){return programVersion;} // reject if program number is lower than project public static boolean evaluateProgramNumber(VersionNumber program, VersionNumber project){ if(program.compareTo(project) < 0) return false; return true; } //constructor public LayerManager(){ initializeGUI(); } //endregion //region filemanager management--------------------------------- //copy existing file into manager (add) public void addManager(LayerManager obj){ // test for project number if(!projectID.equals(obj.projectID)){ WarningWindow.warningWindow("Project ID's don't match. \nMerge could not occur."); return; } // test for valid program number. Otherwise warn user if(!evaluateProgramNumber(Program.getProgramVersion(), obj.getProgramVersion())){ WarningWindow.warningWindow("File version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + obj.getProgramVersion()); return; } // merge obj.root.setTitle("Imported Project"); // give folder a name addChild(root, obj.root); // import folder generateTreeParents(); } //gut existing manager and replace with new information (replace) public void replaceManager(LayerManager obj){ // test for project number if(!projectID.equals(obj.projectID)){ WarningWindow.warningWindow("Project ID's don't match. \nLoad could not occur."); return; } // test for valid program number. Otherwise warn user if(!evaluateProgramNumber(Program.getProgramVersion(), obj.getProgramVersion())){ WarningWindow.warningWindow("File version invalid. Program version: " + Program.getProgramVersion() + "; Project version: " + obj.getProgramVersion()); return; } // replace all relevant variables clear(); //prepare layer for new information root = obj.root; projectID = obj.projectID; projectTitle = obj.projectTitle; generateTreeParents(); } //endregion //region selection (message passing)------------------------------------ private final SelectionManager selectionManager = new SelectionManager(); // initialize // message passing public void addSelection(TreeUnit obj){selectionManager.addSelection(obj);} public void removeSelection(TreeUnit obj){selectionManager.removeSelection(obj);} public void clearSelection(){selectionManager.clearSelection();} public TreeUnit peekSelectionTop(){return selectionManager.peekTop();} public SelectionManager.selectionPriority getSelectionStatus(){return selectionManager.getSelectionStatus();} public SelectionManager.selectionPriority checkSelection(TreeUnit obj){return selectionManager.checkSelection(obj);} public Color selectionColor(TreeUnit unit){return selectionManager.selectColor(unit);} //endregion //region layer manipulation----------------------------------- // fixme add undoredo to most of these functions //clear the entire file public void clear(){ Program.clearSelection(); // clear selection; this is technically a deletion root.clearChildren(); // remove all elements from root setProjectID(Program.getProjectID()); // reset UUID, for file clearing for new projects markImageForRender(root); //remark image for rendering Program.redrawAllRegions(); // redraw canvas and gui } //traverse layer - move down: moves layer down in parent's child hierarchy, if there is space to move //traverse layer - move up: moves layer up in parent's child hierarchy, if there is space to move //traverse layer - move in: moves layer to children list of closest sibling; ignores if there is no suitable sibling //traverse layer - move down: moves layer to be a sibling of the current parent; ignores if parent is root //note: does not ensure layer is a part of the system; also re-renders unnecessarily even in the case of impossible moves public void moveLayer(TreeUnit layer, direction dir){ // reject if layer has no parent [not seeded into tree] (also catches root condition) if (layer.getParent() == null) return; //mark image for regeneration if applicable if (layer instanceof Renderable) markImageForRender(layer); // get layer index LinkedList<TreeUnit> children = (layer.getParent()).getChildren(); int index = children.indexOf(layer); // if place below if (dir == direction.DOWN){ //if there is only one child layer or the layer is at the bottom, ignore request if(index + 1 == children.size() || children.size() == 1) return; //remove the layer and reinsert at one index down children.remove(layer); children.add(index + 1, layer); } // if place above else if (dir == direction.UP){ //If there is only one child or the layer is already at the top, ignore request if(index == 0 || children.size() == 1) return; //remove layer from heirarchy and reinsert at one index higher children.remove(layer); children.add(index - 1, layer); } // if move in else if (dir == direction.IN){ //if there are no older siblings, ignore request if(index == 0){return;} // if there is a valid sibling, move the layer to the bottom of the sibling TreeUnit sibling = children.get(index-1); if(sibling instanceof LayerTreeFolder){ children.remove(layer); addChild((LayerTreeFolder) sibling, layer, position.BOTTOM); } } // else if move out else if (dir == direction.OUT){ TreeUnit parent = (TreeUnit) layer.getParent(); LayerTreeFolder grandparent = parent.getParent(); // null parents already excluded //if layer is at max level, ignore request if(grandparent == null){ return; } //otherwise move layer out one and redraw GUI children.remove(layer); //remove layer from parent addChildAtSibling(parent, layer, position.BOTTOM); // shove layer behind parent } //mark image for regeneration in new location if applicable if (layer instanceof Renderable) markImageForRender(layer); //redraw layer editor gui Program.redrawAllRegions(); } //add folder: adds new folder type layer public void addFolder(){ // add folder to root addChild(root, new Folder()); } //add layer: adds new layer at the end of the root layer child list public void addLayer(){ // add layer to root addChild(root, new Layer()); } //fixme is this used? //add layer with image: adds new layer at the front of the root layer child list and initializes metadata public void addLayer(long code, boolean useColor, Color color){ Layer layer = new Layer(); //create layer layer.setImage(code); //set image //add color and useColor states layer.setColor(color); layer.setUseColor(useColor); addChild(root, layer, position.TOP); //add to list; adds at front } // add renderable to parent [helper function and main function that specifies insertion location] public void addChild(LayerTreeFolder parent, TreeUnit child){ addChild(parent, child, defaultLocation); } public void addChild(LayerTreeFolder parent, TreeUnit child, position place){ child.setParent(parent); // set parent object for child // toggle response based on default settings if (place == position.BOTTOM){ parent.getChildren().addLast(child); } else{ // top parent.getChildren().addFirst(child); } // rebuild gui markImageForRender(child); Program.redrawAllRegions(); } // add renderable to sibling public void addChildAtSibling(TreeUnit sibling, TreeUnit child, position place){ // set parent LinkedList<TreeUnit> children = (sibling.getParent()).getChildren(); child.setParent(sibling.getParent()); // toggle location if (place == position.TOP){ children.add(children.indexOf(sibling), child); } else{ //below children.add(children.indexOf(sibling) + 1, child); } // rebuild gui markImageForRender(child); Program.redrawAllRegions(); } //clone layer // automatically deep deletes, since there's not really a reason to shallow delete public void duplicate(TreeUnit layer){ // remove selection Program.clearSelection(); //clone element if (layer instanceof Copy){ TreeUnit clone = (TreeUnit) ((Copy<?>) layer).copy(); addChildAtSibling(layer, (TreeUnit) clone, position.BOTTOM); markImageForRender(clone); } //redraw layer GUI and canvas GUI Program.redrawLayerEditor(); Program.redrawCanvas(); } //remove layer: removes selected layer from layer hierarchy; parent inherits children //note: does not ensure layer is a part of the system // deep = true: delete all nested elements // deep = false: do not delete nested elements public void delete(TreeUnit layer, boolean deep){ // remove selection Program.clearSelection(); // mark for rerender markImageForRender(layer); //get layer parent children list LinkedList<TreeUnit> children = layer.getParent().getChildren(); // deep deletion if(deep){ //remove layer from parent children.remove(layer); } // shallow deletion else{ //get index of layer int index = children.indexOf(layer); //remove layer from parent LayerTreeFolder parent = layer.getParent(); children.remove(layer); // transfer children if there are children if(layer instanceof Folder){ //transfer children from layer to parent (in reverse order to the parent's old index) //Note: this can be improved by shifting all items at once LinkedList<TreeUnit> list = ((Folder)layer).getChildren(); ListIterator<TreeUnit> iterator = list.listIterator(list.size()); //iterate over children while(iterator.hasPrevious()){ children.add(index, iterator.previous()); } // reset parents of deleted elements for(TreeUnit child : children){ child.setParent(parent); } } } //redraw layer GUI and canvas GUI Program.redrawAllRegions(); } //endregion //region image rendering and helper functions----------------------------------- // resets all renderable children's parents [helper] public void generateTreeParents(){ ((TreeUnit)root).setParent(null); // reset root to orphan generateTreeParents(root); // recurse on root } // recursive function private void generateTreeParents(LayerTreeFolder parent){ LinkedList<TreeUnit> children = parent.getChildren(); // for each offspring, reset parent for(TreeUnit child : children){ child.setParent( parent); // set parent // if also filetreefolder, recurse if (child instanceof LayerTreeFolder){ generateTreeParents((LayerTreeFolder) child); } } } // pings children image in need of regeneration up the tree to the root public void markImageForRender(TreeUnit obj){ // mark current layer as re-render if (obj instanceof Renderable) ((Renderable) obj).requireRender(); // mark all applicable parents: starting with the current image, pass the render mark up the tree LayerTreeFolder parent = obj.getParent(); while(parent != null){ if (parent instanceof Renderable) ((Renderable) parent).requireRender(); parent = ((TreeUnit) parent).getParent(); } } // markImageForRerender but skips the first layer public void markParentForRender(TreeUnit obj){ // mark current layer as re-render if (obj.getParent() != null) markImageForRender((TreeUnit) obj.getParent()); } //public interface to get layer stack public BufferedImage stackImage(){ return ((Renderable)root).getImage(); } //endregion //region GUI layer layout render------------------------------- //internal state variables private JPanel layerTreePanel = new JPanel(); //panel for holding layer gui private JPanel layerEditPanel = new JPanel(); //panel for holding editor information //global accessors public JPanel getLayerTreePanel(){return layerTreePanel;} public JPanel getLayerEditorPanel(){return layerEditPanel;} // initializations private void initializeGUI(){ // layerTreePanel intializations layerTreePanel.setLayout(new BoxLayout(layerTreePanel, BoxLayout.Y_AXIS)); //create box layout in vertical: stack children elements //layerTreePanel.setBackground(Color.lightGray); // layerEditPanel initializations layerEditPanel.setMinimumSize(new Dimension(100, 300)); layerEditPanel.setMaximumSize(new Dimension(9000, 300)); //layerEditPanel.setBorder(BorderFactory.createLineBorder(Color.darkGray)); //draw element borders layerEditPanel.setLayout(new BoxLayout(layerEditPanel, BoxLayout.Y_AXIS)); //set layout to vertical box, so items stack vertically //layerEditPanel.setBackground(Color.BLACK); // spacing requirement (keeps it from being cropped with resize) layerEditPanel.setPreferredSize(new Dimension(300, 100)); } // regenerate tree gui public void rebuildLayerTree(){ //clear gui layerTreePanel.removeAll(); //recursively build gui LayerTreeGui.buildPanel(layerTreePanel, 1, ((Folder)root)); //refresh gui layerEditPanel.revalidate(); //redraws components layerEditPanel.repaint(); //repaints base rectangle when elements are removed } // regenerate editor gui public void rebuildEditorPanel(){ // remove elements in panel layerEditPanel.removeAll(); //Selection type: single object if(Program.getSelectionStatus() == SelectionManager.selectionPriority.PRIMARY){ TreeUnit top = Program.peekSelectionTop(); // get selected element // object type: Layer if(top instanceof Layer){ //LayermapLayerEditPane.add(layerEditPanel, (LayerCORE) top);
layerEditPanel.add(LayerEditorPane.layerEditorPane((Layer) top));
1
2023-11-12 21:12:21+00:00
12k
ebandal/jDwgParser
src/structure/Dwg.java
[ { "identifier": "DecodeCallback", "path": "src/decode/DecodeCallback.java", "snippet": "public interface DecodeCallback {\n public void onDecoded(String name, Object value, int retBitOffset);\n}" }, { "identifier": "DecoderR14", "path": "src/decode/DecoderR14.java", "snippet": "public...
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.time.temporal.JulianFields; import java.util.concurrent.atomic.AtomicInteger; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import decode.DecodeCallback; import decode.DecoderR14; import decode.DecoderR2004; import decode.DwgParseException; import structure.header.FileHeader; import structure.sectionpage.DataSectionPage; import structure.sectionpage.HeaderVariables; import structure.sectionpage.SystemSectionPage;
8,665
package structure; public class Dwg { private static final Logger log = Logger.getLogger(Dwg.class.getName());
package structure; public class Dwg { private static final Logger log = Logger.getLogger(Dwg.class.getName());
public FileHeader header;
4
2023-11-11 13:57:18+00:00
12k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/checks/impl/velocity/KnockbackHandler.java
[ { "identifier": "GrimAPI", "path": "src/main/java/ac/grim/grimac/GrimAPI.java", "snippet": "@Getter\npublic enum GrimAPI {\n INSTANCE;\n\n private final PlayerDataManager playerDataManager = new PlayerDataManager();\n private final InitManager initManager = new InitManager();\n private final...
import ac.grim.grimac.GrimAPI; import ac.grim.grimac.checks.CheckData; import ac.grim.grimac.checks.type.PacketCheck; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.data.VelocityData; import ac.grim.grimac.utils.math.GrimMath; import io.github.retrooper.packetevents.event.impl.PacketPlaySendEvent; import io.github.retrooper.packetevents.packettype.PacketType; import io.github.retrooper.packetevents.packetwrappers.play.out.entityvelocity.WrappedPacketOutEntityVelocity; import io.github.retrooper.packetevents.utils.vector.Vector3d; import org.bukkit.entity.Entity; import org.bukkit.util.Vector; import java.util.concurrent.ConcurrentLinkedQueue;
7,376
package ac.grim.grimac.checks.impl.velocity; // We are making a velocity sandwich between two pieces of transaction packets (bread) @CheckData(name = "AntiKB", configName = "Knockback") public class KnockbackHandler extends PacketCheck { ConcurrentLinkedQueue<VelocityData> firstBreadMap = new ConcurrentLinkedQueue<>(); ConcurrentLinkedQueue<VelocityData> lastKnockbackKnownTaken = new ConcurrentLinkedQueue<>(); VelocityData firstBreadOnlyKnockback = null; boolean wasExplosionZeroPointZeroThree = false; double offsetToFlag; double setbackVL; double decay; public KnockbackHandler(GrimPlayer player) { super(player); } @Override public void onPacketSend(final PacketPlaySendEvent event) { byte packetID = event.getPacketId(); if (packetID == PacketType.Play.Server.ENTITY_VELOCITY) { WrappedPacketOutEntityVelocity velocity = new WrappedPacketOutEntityVelocity(event.getNMSPacket()); int entityId = velocity.getEntityId(); GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getPlayer()); if (player == null) return; // Detect whether this knockback packet affects the player or if it is useless Entity playerVehicle = player.bukkitPlayer.getVehicle(); if ((playerVehicle == null && entityId != player.entityID) || (playerVehicle != null && entityId != playerVehicle.getEntityId())) { return; } // If the player isn't in a vehicle and the ID is for the player, the player will take kb // If the player is in a vehicle and the ID is for the player's vehicle, the player will take kb Vector3d playerVelocity = velocity.getVelocity(); // Wrap velocity between two transactions player.sendTransaction(); addPlayerKnockback(entityId, player.lastTransactionSent.get(), new Vector(playerVelocity.getX(), playerVelocity.getY(), playerVelocity.getZ())); event.setPostTask(player::sendTransaction); } } private void addPlayerKnockback(int entityID, int breadOne, Vector knockback) { firstBreadMap.add(new VelocityData(entityID, breadOne, knockback)); } public VelocityData getRequiredKB(int entityID, int transaction) { tickKnockback(transaction); VelocityData returnLastKB = null; for (VelocityData data : lastKnockbackKnownTaken) { if (data.entityID == entityID) returnLastKB = data; } lastKnockbackKnownTaken.clear(); return returnLastKB; } private void tickKnockback(int transactionID) { VelocityData data = firstBreadMap.peek(); while (data != null) { if (data.transaction == transactionID) { // First bread knockback firstBreadOnlyKnockback = new VelocityData(data.entityID, data.transaction, data.vector); firstBreadMap.poll(); break; // All knockback after this will have not been applied } else if (data.transaction < transactionID) { // This kb has 100% arrived to the player if (firstBreadOnlyKnockback != null) // Don't require kb twice lastKnockbackKnownTaken.add(new VelocityData(data.entityID, data.transaction, data.vector, data.offset)); else lastKnockbackKnownTaken.add(new VelocityData(data.entityID, data.transaction, data.vector)); firstBreadOnlyKnockback = null; firstBreadMap.poll(); data = firstBreadMap.peek(); } else { // We are too far ahead in the future break; } } } public void forceExempt() { // Unsure knockback was taken if (player.firstBreadKB != null) { player.firstBreadKB.offset = 0; } if (player.likelyKB != null) { player.likelyKB.offset = 0; } } public void setPointThree(boolean isPointThree) { wasExplosionZeroPointZeroThree = wasExplosionZeroPointZeroThree || isPointThree; } public void handlePredictionAnalysis(double offset) { if (player.firstBreadKB != null) { player.firstBreadKB.offset = Math.min(player.firstBreadKB.offset, offset); } if (player.likelyKB != null) { player.likelyKB.offset = Math.min(player.likelyKB.offset, offset); } } public void handlePlayerKb(double offset) { boolean wasZero = wasExplosionZeroPointZeroThree; wasExplosionZeroPointZeroThree = false; if (player.likelyKB == null && player.firstBreadKB == null) { return; } if (!wasZero && player.predictedVelocity.isKnockback() && player.likelyKB == null && player.firstBreadKB != null) { // The player took this knockback, this tick, 100% // Fixes exploit that would allow players to take knockback an infinite number of times if (player.firstBreadKB.offset < offsetToFlag) { firstBreadOnlyKnockback = null; } } if (wasZero || player.predictedVelocity.isKnockback()) { // Unsure knockback was taken if (player.firstBreadKB != null) { player.firstBreadKB.offset = Math.min(player.firstBreadKB.offset, offset); } // 100% known kb was taken if (player.likelyKB != null) { player.likelyKB.offset = Math.min(player.likelyKB.offset, offset); } } if (player.likelyKB != null) { if (player.likelyKB.offset > offsetToFlag) { increaseViolations(); String formatOffset = "o: " + formatOffset(player.likelyKB.offset); if (player.likelyKB.offset == Integer.MAX_VALUE) { formatOffset = "ignored knockback"; }
package ac.grim.grimac.checks.impl.velocity; // We are making a velocity sandwich between two pieces of transaction packets (bread) @CheckData(name = "AntiKB", configName = "Knockback") public class KnockbackHandler extends PacketCheck { ConcurrentLinkedQueue<VelocityData> firstBreadMap = new ConcurrentLinkedQueue<>(); ConcurrentLinkedQueue<VelocityData> lastKnockbackKnownTaken = new ConcurrentLinkedQueue<>(); VelocityData firstBreadOnlyKnockback = null; boolean wasExplosionZeroPointZeroThree = false; double offsetToFlag; double setbackVL; double decay; public KnockbackHandler(GrimPlayer player) { super(player); } @Override public void onPacketSend(final PacketPlaySendEvent event) { byte packetID = event.getPacketId(); if (packetID == PacketType.Play.Server.ENTITY_VELOCITY) { WrappedPacketOutEntityVelocity velocity = new WrappedPacketOutEntityVelocity(event.getNMSPacket()); int entityId = velocity.getEntityId(); GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getPlayer()); if (player == null) return; // Detect whether this knockback packet affects the player or if it is useless Entity playerVehicle = player.bukkitPlayer.getVehicle(); if ((playerVehicle == null && entityId != player.entityID) || (playerVehicle != null && entityId != playerVehicle.getEntityId())) { return; } // If the player isn't in a vehicle and the ID is for the player, the player will take kb // If the player is in a vehicle and the ID is for the player's vehicle, the player will take kb Vector3d playerVelocity = velocity.getVelocity(); // Wrap velocity between two transactions player.sendTransaction(); addPlayerKnockback(entityId, player.lastTransactionSent.get(), new Vector(playerVelocity.getX(), playerVelocity.getY(), playerVelocity.getZ())); event.setPostTask(player::sendTransaction); } } private void addPlayerKnockback(int entityID, int breadOne, Vector knockback) { firstBreadMap.add(new VelocityData(entityID, breadOne, knockback)); } public VelocityData getRequiredKB(int entityID, int transaction) { tickKnockback(transaction); VelocityData returnLastKB = null; for (VelocityData data : lastKnockbackKnownTaken) { if (data.entityID == entityID) returnLastKB = data; } lastKnockbackKnownTaken.clear(); return returnLastKB; } private void tickKnockback(int transactionID) { VelocityData data = firstBreadMap.peek(); while (data != null) { if (data.transaction == transactionID) { // First bread knockback firstBreadOnlyKnockback = new VelocityData(data.entityID, data.transaction, data.vector); firstBreadMap.poll(); break; // All knockback after this will have not been applied } else if (data.transaction < transactionID) { // This kb has 100% arrived to the player if (firstBreadOnlyKnockback != null) // Don't require kb twice lastKnockbackKnownTaken.add(new VelocityData(data.entityID, data.transaction, data.vector, data.offset)); else lastKnockbackKnownTaken.add(new VelocityData(data.entityID, data.transaction, data.vector)); firstBreadOnlyKnockback = null; firstBreadMap.poll(); data = firstBreadMap.peek(); } else { // We are too far ahead in the future break; } } } public void forceExempt() { // Unsure knockback was taken if (player.firstBreadKB != null) { player.firstBreadKB.offset = 0; } if (player.likelyKB != null) { player.likelyKB.offset = 0; } } public void setPointThree(boolean isPointThree) { wasExplosionZeroPointZeroThree = wasExplosionZeroPointZeroThree || isPointThree; } public void handlePredictionAnalysis(double offset) { if (player.firstBreadKB != null) { player.firstBreadKB.offset = Math.min(player.firstBreadKB.offset, offset); } if (player.likelyKB != null) { player.likelyKB.offset = Math.min(player.likelyKB.offset, offset); } } public void handlePlayerKb(double offset) { boolean wasZero = wasExplosionZeroPointZeroThree; wasExplosionZeroPointZeroThree = false; if (player.likelyKB == null && player.firstBreadKB == null) { return; } if (!wasZero && player.predictedVelocity.isKnockback() && player.likelyKB == null && player.firstBreadKB != null) { // The player took this knockback, this tick, 100% // Fixes exploit that would allow players to take knockback an infinite number of times if (player.firstBreadKB.offset < offsetToFlag) { firstBreadOnlyKnockback = null; } } if (wasZero || player.predictedVelocity.isKnockback()) { // Unsure knockback was taken if (player.firstBreadKB != null) { player.firstBreadKB.offset = Math.min(player.firstBreadKB.offset, offset); } // 100% known kb was taken if (player.likelyKB != null) { player.likelyKB.offset = Math.min(player.likelyKB.offset, offset); } } if (player.likelyKB != null) { if (player.likelyKB.offset > offsetToFlag) { increaseViolations(); String formatOffset = "o: " + formatOffset(player.likelyKB.offset); if (player.likelyKB.offset == Integer.MAX_VALUE) { formatOffset = "ignored knockback"; }
alert(formatOffset, "AntiKB", GrimMath.floor(violations) + "");
4
2023-11-11 05:14:12+00:00
12k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/command/MainCommand.java
[ { "identifier": "Client", "path": "src/main/java/com/github/codecnomad/codecclient/Client.java", "snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft...
import cc.polyfrost.oneconfig.utils.commands.annotations.Command; import cc.polyfrost.oneconfig.utils.commands.annotations.Main; import cc.polyfrost.oneconfig.utils.commands.annotations.SubCommand; import com.github.codecnomad.codecclient.Client; import com.github.codecnomad.codecclient.ui.Config; import com.github.codecnomad.codecclient.utils.Chat; import com.github.codecnomad.codecclient.utils.Pathfinding; import com.github.codecnomad.codecclient.utils.Render; import com.github.codecnomad.codecclient.utils.Walker; import net.minecraft.util.BlockPos; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List;
9,215
package com.github.codecnomad.codecclient.command; @SuppressWarnings("unused") @Command(value = "codecclient", aliases = {"codec"}) public class MainCommand { List<BlockPos> waypoints = new ArrayList<>(); @Main public void mainCommand() { Client.guiConfig.openGui(); } Collection<BlockPos> path = new ArrayList<>();
package com.github.codecnomad.codecclient.command; @SuppressWarnings("unused") @Command(value = "codecclient", aliases = {"codec"}) public class MainCommand { List<BlockPos> waypoints = new ArrayList<>(); @Main public void mainCommand() { Client.guiConfig.openGui(); } Collection<BlockPos> path = new ArrayList<>();
public static Pathfinding pathfinding = new Pathfinding();
3
2023-11-16 10:12:20+00:00
12k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/modules/OreSim.java
[ { "identifier": "MeteorRejectsAddon", "path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java", "snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(...
import anticope.rejects.MeteorRejectsAddon; import anticope.rejects.events.PlayerRespawnEvent; import anticope.rejects.events.SeedChangedEvent; import anticope.rejects.utils.Ore; import anticope.rejects.utils.seeds.Seed; import anticope.rejects.utils.seeds.Seeds; import baritone.api.BaritoneAPI; import com.seedfinding.mccore.version.MCVersion; import meteordevelopment.meteorclient.events.render.Render3DEvent; import meteordevelopment.meteorclient.events.world.ChunkDataEvent; import meteordevelopment.meteorclient.events.world.TickEvent; import meteordevelopment.meteorclient.settings.*; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.orbit.EventHandler; import net.minecraft.client.world.ClientWorld; import net.minecraft.registry.RegistryKeys; import net.minecraft.util.Identifier; import net.minecraft.util.math.*; import net.minecraft.util.math.random.ChunkRandom; import net.minecraft.world.Heightmap; import net.minecraft.world.chunk.ChunkStatus; import java.util.*;
7,851
package anticope.rejects.modules; public class OreSim extends Module { private final HashMap<Long, HashMap<Ore, HashSet<Vec3d>>> chunkRenderers = new HashMap<>(); private Seed worldSeed = null; private List<Ore> oreConfig; public ArrayList<BlockPos> oreGoals = new ArrayList<>(); private ChunkPos prevOffset = new ChunkPos(0, 0); public enum AirCheck { ON_LOAD, RECHECK, OFF } private final SettingGroup sgGeneral = settings.getDefaultGroup(); private final SettingGroup sgOres = settings.createGroup("Ores"); private final Setting<Integer> horizontalRadius = sgGeneral.add(new IntSetting.Builder() .name("chunk-range") .description("Taxi cap distance of chunks being shown.") .defaultValue(5) .min(1) .sliderMax(10) .build() ); private final Setting<AirCheck> airCheck = sgGeneral.add(new EnumSetting.Builder<AirCheck>() .name("air-check-mode") .description("Checks if there is air at a calculated ore pos.") .defaultValue(AirCheck.RECHECK) .build() ); private final Setting<Boolean> baritone = sgGeneral.add(new BoolSetting.Builder() .name("baritone") .description("Set baritone ore positions to the simulated ones.") .defaultValue(false) .build() ); public OreSim() { super(MeteorRejectsAddon.CATEGORY, "ore-sim", "Xray on crack."); Ore.oreSettings.forEach(sgOres::add); } public boolean baritone() { return isActive() && baritone.get(); } @EventHandler private void onRender(Render3DEvent event) { if (mc.player == null || oreConfig == null) { return; }
package anticope.rejects.modules; public class OreSim extends Module { private final HashMap<Long, HashMap<Ore, HashSet<Vec3d>>> chunkRenderers = new HashMap<>(); private Seed worldSeed = null; private List<Ore> oreConfig; public ArrayList<BlockPos> oreGoals = new ArrayList<>(); private ChunkPos prevOffset = new ChunkPos(0, 0); public enum AirCheck { ON_LOAD, RECHECK, OFF } private final SettingGroup sgGeneral = settings.getDefaultGroup(); private final SettingGroup sgOres = settings.createGroup("Ores"); private final Setting<Integer> horizontalRadius = sgGeneral.add(new IntSetting.Builder() .name("chunk-range") .description("Taxi cap distance of chunks being shown.") .defaultValue(5) .min(1) .sliderMax(10) .build() ); private final Setting<AirCheck> airCheck = sgGeneral.add(new EnumSetting.Builder<AirCheck>() .name("air-check-mode") .description("Checks if there is air at a calculated ore pos.") .defaultValue(AirCheck.RECHECK) .build() ); private final Setting<Boolean> baritone = sgGeneral.add(new BoolSetting.Builder() .name("baritone") .description("Set baritone ore positions to the simulated ones.") .defaultValue(false) .build() ); public OreSim() { super(MeteorRejectsAddon.CATEGORY, "ore-sim", "Xray on crack."); Ore.oreSettings.forEach(sgOres::add); } public boolean baritone() { return isActive() && baritone.get(); } @EventHandler private void onRender(Render3DEvent event) { if (mc.player == null || oreConfig == null) { return; }
if (Seeds.get().getSeed() != null) {
5
2023-11-13 08:11:28+00:00
12k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/VideoSelectActivity.java
[ { "identifier": "BaseActivity", "path": "library/base/src/main/java/com/hjq/base/BaseActivity.java", "snippet": "public abstract class BaseActivity extends AppCompatActivity\n implements ActivityAction, ClickAction,\n HandlerAction, BundleAction, KeyboardAction {\n\n /** 错误结果码 */\n p...
import android.content.ContentResolver; import android.content.Intent; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore; import android.text.TextUtils; import android.view.View; import android.view.animation.AnimationUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.hjq.base.BaseActivity; import com.hjq.base.BaseAdapter; import com.buaa.food.R; import com.buaa.food.action.StatusAction; import com.buaa.food.aop.Log; import com.buaa.food.aop.Permissions; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppActivity; import com.buaa.food.manager.ThreadPoolManager; import com.buaa.food.other.GridSpaceDecoration; import com.buaa.food.ui.adapter.VideoSelectAdapter; import com.buaa.food.ui.dialog.AlbumDialog; import com.buaa.food.widget.StatusLayout; import com.hjq.permissions.Permission; import com.hjq.permissions.XXPermissions; import com.hjq.widget.view.FloatActionButton; import com.tencent.bugly.crashreport.CrashReport; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set;
10,551
package com.buaa.food.ui.activity; public final class VideoSelectActivity extends AppActivity implements StatusAction, Runnable, BaseAdapter.OnItemClickListener, BaseAdapter.OnItemLongClickListener, BaseAdapter.OnChildClickListener { private static final String INTENT_KEY_IN_MAX_SELECT = "maxSelect"; private static final String INTENT_KEY_OUT_VIDEO_LIST = "videoList"; public static void start(BaseActivity activity, OnVideoSelectListener listener) { start(activity, 1, listener); } @Log @Permissions({Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE}) public static void start(BaseActivity activity, int maxSelect, OnVideoSelectListener listener) { if (maxSelect < 1) { // 最少要选择一个视频 throw new IllegalArgumentException("are you ok?"); } Intent intent = new Intent(activity, VideoSelectActivity.class); intent.putExtra(INTENT_KEY_IN_MAX_SELECT, maxSelect); activity.startActivityForResult(intent, (resultCode, data) -> { if (listener == null) { return; } if (data == null) { listener.onCancel(); return; } ArrayList<VideoBean> list = data.getParcelableArrayListExtra(INTENT_KEY_OUT_VIDEO_LIST); if (list == null || list.isEmpty()) { listener.onCancel(); return; } Iterator<VideoBean> iterator = list.iterator(); while (iterator.hasNext()) { if (!new File(iterator.next().getVideoPath()).isFile()) { iterator.remove(); } } if (resultCode == RESULT_OK && !list.isEmpty()) { listener.onSelected(list); return; } listener.onCancel(); }); } private StatusLayout mStatusLayout; private RecyclerView mRecyclerView; private FloatActionButton mFloatingView; private VideoSelectAdapter mAdapter; /** 最大选中 */ private int mMaxSelect = 1; /** 选中列表 */ private final ArrayList<VideoBean> mSelectVideo = new ArrayList<>(); /** 全部视频 */ private final ArrayList<VideoBean> mAllVideo = new ArrayList<>(); /** 视频专辑 */ private final HashMap<String, List<VideoBean>> mAllAlbum = new HashMap<>(); /** 专辑选择对话框 */ private AlbumDialog.Builder mAlbumDialog; @Override protected int getLayoutId() { return R.layout.video_select_activity; } @Override protected void initView() { mStatusLayout = findViewById(R.id.hl_video_select_hint); mRecyclerView = findViewById(R.id.rv_video_select_list); mFloatingView = findViewById(R.id.fab_video_select_floating); setOnClickListener(mFloatingView); mAdapter = new VideoSelectAdapter(this, mSelectVideo); mAdapter.setOnChildClickListener(R.id.fl_video_select_check, this); mAdapter.setOnItemClickListener(this); mAdapter.setOnItemLongClickListener(this); mRecyclerView.setAdapter(mAdapter); // 禁用动画效果 mRecyclerView.setItemAnimator(null); // 添加分割线 mRecyclerView.addItemDecoration(new GridSpaceDecoration((int) getResources().getDimension(R.dimen.dp_5))); // 设置滚动监听 mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { switch (newState) { case RecyclerView.SCROLL_STATE_DRAGGING: mFloatingView.hide(); break; case RecyclerView.SCROLL_STATE_IDLE: mFloatingView.show(); break; default: break; } } }); } @Override protected void initData() { // 获取最大的选择数 mMaxSelect = getInt(INTENT_KEY_IN_MAX_SELECT, mMaxSelect); // 显示加载进度条 showLoading(); // 加载视频列表
package com.buaa.food.ui.activity; public final class VideoSelectActivity extends AppActivity implements StatusAction, Runnable, BaseAdapter.OnItemClickListener, BaseAdapter.OnItemLongClickListener, BaseAdapter.OnChildClickListener { private static final String INTENT_KEY_IN_MAX_SELECT = "maxSelect"; private static final String INTENT_KEY_OUT_VIDEO_LIST = "videoList"; public static void start(BaseActivity activity, OnVideoSelectListener listener) { start(activity, 1, listener); } @Log @Permissions({Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE}) public static void start(BaseActivity activity, int maxSelect, OnVideoSelectListener listener) { if (maxSelect < 1) { // 最少要选择一个视频 throw new IllegalArgumentException("are you ok?"); } Intent intent = new Intent(activity, VideoSelectActivity.class); intent.putExtra(INTENT_KEY_IN_MAX_SELECT, maxSelect); activity.startActivityForResult(intent, (resultCode, data) -> { if (listener == null) { return; } if (data == null) { listener.onCancel(); return; } ArrayList<VideoBean> list = data.getParcelableArrayListExtra(INTENT_KEY_OUT_VIDEO_LIST); if (list == null || list.isEmpty()) { listener.onCancel(); return; } Iterator<VideoBean> iterator = list.iterator(); while (iterator.hasNext()) { if (!new File(iterator.next().getVideoPath()).isFile()) { iterator.remove(); } } if (resultCode == RESULT_OK && !list.isEmpty()) { listener.onSelected(list); return; } listener.onCancel(); }); } private StatusLayout mStatusLayout; private RecyclerView mRecyclerView; private FloatActionButton mFloatingView; private VideoSelectAdapter mAdapter; /** 最大选中 */ private int mMaxSelect = 1; /** 选中列表 */ private final ArrayList<VideoBean> mSelectVideo = new ArrayList<>(); /** 全部视频 */ private final ArrayList<VideoBean> mAllVideo = new ArrayList<>(); /** 视频专辑 */ private final HashMap<String, List<VideoBean>> mAllAlbum = new HashMap<>(); /** 专辑选择对话框 */ private AlbumDialog.Builder mAlbumDialog; @Override protected int getLayoutId() { return R.layout.video_select_activity; } @Override protected void initView() { mStatusLayout = findViewById(R.id.hl_video_select_hint); mRecyclerView = findViewById(R.id.rv_video_select_list); mFloatingView = findViewById(R.id.fab_video_select_floating); setOnClickListener(mFloatingView); mAdapter = new VideoSelectAdapter(this, mSelectVideo); mAdapter.setOnChildClickListener(R.id.fl_video_select_check, this); mAdapter.setOnItemClickListener(this); mAdapter.setOnItemLongClickListener(this); mRecyclerView.setAdapter(mAdapter); // 禁用动画效果 mRecyclerView.setItemAnimator(null); // 添加分割线 mRecyclerView.addItemDecoration(new GridSpaceDecoration((int) getResources().getDimension(R.dimen.dp_5))); // 设置滚动监听 mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { switch (newState) { case RecyclerView.SCROLL_STATE_DRAGGING: mFloatingView.hide(); break; case RecyclerView.SCROLL_STATE_IDLE: mFloatingView.show(); break; default: break; } } }); } @Override protected void initData() { // 获取最大的选择数 mMaxSelect = getInt(INTENT_KEY_IN_MAX_SELECT, mMaxSelect); // 显示加载进度条 showLoading(); // 加载视频列表
ThreadPoolManager.getInstance().execute(this);
4
2023-11-14 10:04:26+00:00
12k
WallasAR/GUITest
src/main/java/com/session/employee/PurchaseController.java
[ { "identifier": "Banco", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public class Banco {\n Scanner scanner1 = new Scanner(System.in);\n public static Connection connection = conexao();\n Statement executar;\n {\n try {\n executar = connection.createStateme...
import com.db.bank.Banco; import com.example.guitest.LoginController; import com.example.guitest.Main; import com.table.view.CarrinhoTable; import com.table.view.ClienteTable; import com.table.view.FuncionarioTable; import com.table.view.MedicamentoTable; import com.warning.alert.AlertMsg; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Date; import java.text.SimpleDateFormat; import static com.db.bank.Banco.connection;
8,674
tfNome.setDisable(true); tfTipo.setDisable(true); tfValor.setDisable(true); try { tabelamedi(); } catch (SQLException e) { throw new RuntimeException(e); } } public void ViewBox()throws SQLException{ String consultaSQLcliente = "SELECT usuario FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { String valorDaColuna4 = resultado.getString("usuario"); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } } public void colocarRegistro(javafx.event.ActionEvent event) throws SQLException { Banco banco = new Banco(); String user = Box.getSelectionModel().getSelectedItem().toString(); String nome = tfNome.getText(); int quantidade = Integer.parseInt(tfQuantidade.getText()); float valor = Float.parseFloat(tfValor.getText()); String tipo = tfTipo.getText(); String consultatipo = "SELECT nome, quantidade, tipo FROM medicamentos WHERE nome = ?"; PreparedStatement preparedStatement = connection.prepareStatement(consultatipo); preparedStatement.setString(1, nome); ResultSet resultado = preparedStatement.executeQuery(); String consultafone = "SELECT telefone FROM cliente WHERE usuario = ?"; preparedStatement = connection.prepareStatement(consultafone); preparedStatement.setString(1, user); ResultSet resultadofone = preparedStatement.executeQuery(); String nomemedicamento = null; while(resultado.next() && resultadofone.next()) { String tipomedi = resultado.getString("tipo"); nomemedicamento = resultado.getString("nome"); int quantidadebanco = resultado.getInt("quantidade"); String fone = resultadofone.getString("telefone"); if (tipomedi.equalsIgnoreCase("TarjaPreta") && quantidadebanco > 0) { AlertMsg alert = new AlertMsg(); if (alert.msgConfirm("Alerta de tarja preta! O medicamento " + nomemedicamento + " necessita de receita", "Solicite-a ao cliente.")) { float novoValor = valor * quantidade; // Date system to table registro int novaquanti = quantidadebanco - quantidade; banco.inserircarrinho(user, nome, quantidade, novoValor); String updateselect1 = "UPDATE medicamentos SET quantidade = ? WHERE nome = ?"; try (PreparedStatement preparedStatementselect = connection.prepareStatement(updateselect1)) { preparedStatementselect.setInt(1, novaquanti); preparedStatementselect.setString(2, nomemedicamento); preparedStatementselect.executeUpdate(); tabelamedi(); Carrinho(); } break; } else { } } else if (tipomedi.equalsIgnoreCase("TarjaVermelha") && quantidadebanco > 0) { AlertMsg alert = new AlertMsg(); if (alert.msgConfirm("Alerta de tarja vermelha! O medicamento " + nomemedicamento + " necessita de receita dupla", "Solicite-a ao cliente.")) { float novoValor = valor * quantidade; // Date system to table registro int novaquanti = quantidadebanco - quantidade; banco.inserircarrinho(user, nome, quantidade, novoValor); String updateselect1 = "UPDATE medicamentos SET quantidade = ? WHERE nome = ?"; try (PreparedStatement preparedStatementselect = connection.prepareStatement(updateselect1)) { preparedStatementselect.setInt(1, novaquanti); preparedStatementselect.setString(2, nomemedicamento); preparedStatementselect.executeUpdate(); tabelamedi(); Carrinho(); } break; } else { } } else if (tipo.equalsIgnoreCase("SemTarja") && quantidadebanco > 0) { float novoValor = valor * quantidade; // Date system to table registro int novaquanti = quantidadebanco - quantidade; banco.inserircarrinho(user, nome, quantidade, novoValor); String updateselect1 = "UPDATE medicamentos SET quantidade = ? WHERE nome = ?"; try (PreparedStatement preparedStatementselect = connection.prepareStatement(updateselect1)) { preparedStatementselect.setInt(1, novaquanti); preparedStatementselect.setString(2, nomemedicamento); preparedStatementselect.executeUpdate(); tabelamedi(); Carrinho(); } break; }else if(quantidadebanco == 0){ AlertMsg alert = new AlertMsg(); if(alert.msgConfirm("A quantidade do medicamento selecionado é: " + quantidadebanco, "Faça um agendamento.")){ float novoValor = valor * quantidade; Date dataHoraAtual = new Date(); String date = new SimpleDateFormat("dd/MM/yyyy | HH:mm:ss").format(dataHoraAtual); String status = "Pedido Efetuado"; banco.inserirencomendas(user, nome, quantidade, novoValor, date, fone, status); } } } } public void Carrinho() throws SQLException { int index = tvCarrinho.getSelectionModel().getSelectedIndex(); if (index <= -1) {
package com.session.employee; public class PurchaseController implements Initializable { @FXML private TableView tvCarrinho; @FXML private TableView tvCompra; @FXML private TableColumn tcIdmedi; @FXML private TableColumn tcNomemedi; @FXML private TableColumn tcQuantimedi; @FXML private TableColumn tcTipomedi; @FXML private TableColumn tcPreçomedi; @FXML private TableColumn tcUser; @FXML private TableColumn tfUser; @FXML private TableColumn tfIdmedi; @FXML private TableColumn tfNomemedi; @FXML private TableColumn tfQuantimedi; @FXML private TableColumn tfPreçomedi; @FXML private TextField tfSearch; @FXML private TextField tfIdCarrinho; @FXML private TextField tfNome; @FXML private TextField tfQuantidade; @FXML private TextField tfTipo; @FXML private TextField tfValor; @FXML private TextField tfId; @FXML private ComboBox Box; @FXML private Label labelShowTotal; @FXML protected void MainAction(MouseEvent e) { if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) { Main.changedScene("main"); } } @FXML protected void MedOrderAction(MouseEvent e) { Main.changedScene("medOrder"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("ClientAdmFunc"); } public void tabelamedi() throws SQLException { List<MedicamentoTable> medicamentos = new ArrayList<>(); String consultaSQL = "SELECT * FROM medicamentos"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQL); while (resultado.next()) { int valorDaColuna1 = resultado.getInt("id"); String valorDaColuna2 = resultado.getString("nome"); int valorDaColuna3 = resultado.getInt("quantidade"); String valorDaColina4 = resultado.getString("tipo"); Float valorDaColuna5 = resultado.getFloat("valor"); MedicamentoTable medicamento = new MedicamentoTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColina4, valorDaColuna5); medicamentos.add(medicamento); } ObservableList<MedicamentoTable> datamedi = FXCollections.observableList(medicamentos); tcIdmedi.setCellValueFactory(new PropertyValueFactory<>("id")); tcNomemedi.setCellValueFactory(new PropertyValueFactory<>("nomemedi")); tcQuantimedi.setCellValueFactory(new PropertyValueFactory<>("quantidade")); tcTipomedi.setCellValueFactory(new PropertyValueFactory<>("tipo")); tcPreçomedi.setCellValueFactory(new PropertyValueFactory<>("valor")); tvCompra.setItems(datamedi); FilteredList<MedicamentoTable> filteredLis = new FilteredList<>(datamedi, b -> true); tfSearch.textProperty().addListener((observable, oldValue, newValue) ->{ filteredLis.setPredicate(funcionarioTable -> { if (newValue.isEmpty() || newValue.isBlank() || newValue == null){ return true; } String searchKeyowrds = newValue.toLowerCase(); if (funcionarioTable.getNomemedi().toLowerCase().indexOf(searchKeyowrds) > -1) { return true; } else if(funcionarioTable.getTipo().toLowerCase().indexOf(searchKeyowrds) > -1){ return true; } else { return false; } }); }); SortedList<MedicamentoTable> sortedList = new SortedList<>(filteredLis); sortedList.comparatorProperty().bind(tvCompra.comparatorProperty()); tvCompra.setItems(sortedList); } // TableView Medicamentos GetItems public void getItemsActionCompra(MouseEvent event)throws SQLException { int index; index = tvCompra.getSelectionModel().getSelectedIndex(); if (index <= -1){ return; } List<ClienteTable> clientes = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { int valorDaColuna1 = resultado.getInt("id"); String valorDaColuna2 = resultado.getString("nome"); String valorDaColuna3 = resultado.getString("sobrenome"); String valorDaColuna4 = resultado.getString("usuario"); String valorDaColuna5 = resultado.getString("telefone"); ClienteTable cliente = new ClienteTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColuna4, valorDaColuna5); clientes.add(cliente); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } // fill the TextFields tfId.setText(String.valueOf(tcIdmedi.getCellData(index))); tfNome.setText((String) tcNomemedi.getCellData(index)); tfTipo.setText((String) tcTipomedi.getCellData(index)); tfValor.setText(String.valueOf((float) tcPreçomedi.getCellData(index))); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { tfId.setDisable(true); tfNome.setDisable(true); tfTipo.setDisable(true); tfValor.setDisable(true); try { tabelamedi(); } catch (SQLException e) { throw new RuntimeException(e); } } public void ViewBox()throws SQLException{ String consultaSQLcliente = "SELECT usuario FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { String valorDaColuna4 = resultado.getString("usuario"); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } } public void colocarRegistro(javafx.event.ActionEvent event) throws SQLException { Banco banco = new Banco(); String user = Box.getSelectionModel().getSelectedItem().toString(); String nome = tfNome.getText(); int quantidade = Integer.parseInt(tfQuantidade.getText()); float valor = Float.parseFloat(tfValor.getText()); String tipo = tfTipo.getText(); String consultatipo = "SELECT nome, quantidade, tipo FROM medicamentos WHERE nome = ?"; PreparedStatement preparedStatement = connection.prepareStatement(consultatipo); preparedStatement.setString(1, nome); ResultSet resultado = preparedStatement.executeQuery(); String consultafone = "SELECT telefone FROM cliente WHERE usuario = ?"; preparedStatement = connection.prepareStatement(consultafone); preparedStatement.setString(1, user); ResultSet resultadofone = preparedStatement.executeQuery(); String nomemedicamento = null; while(resultado.next() && resultadofone.next()) { String tipomedi = resultado.getString("tipo"); nomemedicamento = resultado.getString("nome"); int quantidadebanco = resultado.getInt("quantidade"); String fone = resultadofone.getString("telefone"); if (tipomedi.equalsIgnoreCase("TarjaPreta") && quantidadebanco > 0) { AlertMsg alert = new AlertMsg(); if (alert.msgConfirm("Alerta de tarja preta! O medicamento " + nomemedicamento + " necessita de receita", "Solicite-a ao cliente.")) { float novoValor = valor * quantidade; // Date system to table registro int novaquanti = quantidadebanco - quantidade; banco.inserircarrinho(user, nome, quantidade, novoValor); String updateselect1 = "UPDATE medicamentos SET quantidade = ? WHERE nome = ?"; try (PreparedStatement preparedStatementselect = connection.prepareStatement(updateselect1)) { preparedStatementselect.setInt(1, novaquanti); preparedStatementselect.setString(2, nomemedicamento); preparedStatementselect.executeUpdate(); tabelamedi(); Carrinho(); } break; } else { } } else if (tipomedi.equalsIgnoreCase("TarjaVermelha") && quantidadebanco > 0) { AlertMsg alert = new AlertMsg(); if (alert.msgConfirm("Alerta de tarja vermelha! O medicamento " + nomemedicamento + " necessita de receita dupla", "Solicite-a ao cliente.")) { float novoValor = valor * quantidade; // Date system to table registro int novaquanti = quantidadebanco - quantidade; banco.inserircarrinho(user, nome, quantidade, novoValor); String updateselect1 = "UPDATE medicamentos SET quantidade = ? WHERE nome = ?"; try (PreparedStatement preparedStatementselect = connection.prepareStatement(updateselect1)) { preparedStatementselect.setInt(1, novaquanti); preparedStatementselect.setString(2, nomemedicamento); preparedStatementselect.executeUpdate(); tabelamedi(); Carrinho(); } break; } else { } } else if (tipo.equalsIgnoreCase("SemTarja") && quantidadebanco > 0) { float novoValor = valor * quantidade; // Date system to table registro int novaquanti = quantidadebanco - quantidade; banco.inserircarrinho(user, nome, quantidade, novoValor); String updateselect1 = "UPDATE medicamentos SET quantidade = ? WHERE nome = ?"; try (PreparedStatement preparedStatementselect = connection.prepareStatement(updateselect1)) { preparedStatementselect.setInt(1, novaquanti); preparedStatementselect.setString(2, nomemedicamento); preparedStatementselect.executeUpdate(); tabelamedi(); Carrinho(); } break; }else if(quantidadebanco == 0){ AlertMsg alert = new AlertMsg(); if(alert.msgConfirm("A quantidade do medicamento selecionado é: " + quantidadebanco, "Faça um agendamento.")){ float novoValor = valor * quantidade; Date dataHoraAtual = new Date(); String date = new SimpleDateFormat("dd/MM/yyyy | HH:mm:ss").format(dataHoraAtual); String status = "Pedido Efetuado"; banco.inserirencomendas(user, nome, quantidade, novoValor, date, fone, status); } } } } public void Carrinho() throws SQLException { int index = tvCarrinho.getSelectionModel().getSelectedIndex(); if (index <= -1) {
List<CarrinhoTable> carrinho = new ArrayList<>();
3
2023-11-16 14:55:08+00:00
12k
PoluteClient/PoluteClientV1
1.19.4/src/main/java/net/Poluteclient/phosphor/mixin/MouseMixin.java
[ { "identifier": "AsteriaMenu", "path": "1.19.4/src/main/java/net/Poluteclient/phosphor/gui/PoluteMenu.java", "snippet": "public class AsteriaMenu implements Renderable {\n private static AsteriaMenu instance;\n\n private static final AtomicBoolean clientEnabled = new AtomicBoolean(true);\n publ...
import net.Poluteclient.phosphor.api.event.events.MouseMoveEvent; import net.Poluteclient.phosphor.api.event.events.MousePressEvent; import net.Poluteclient.phosphor.api.event.events.MouseUpdateEvent; import net.Poluteclient.phosphor.common.Phosphor; import net.Poluteclient.phosphor.gui.AsteriaMenu; import net.Poluteclient.phosphor.gui.AsteriaNewMenu; import net.Poluteclient.phosphor.gui.CategoryTab; import net.Poluteclient.phosphor.gui.ImguiLoader; import net.Poluteclient.phosphor.module.modules.client.AsteriaSettingsModule; import net.minecraft.client.MinecraftClient; import net.minecraft.client.Mouse; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
10,081
package net.Poluteclient.phosphor.mixin; @Mixin(Mouse.class) public class MouseMixin { @Shadow @Final private MinecraftClient client; @Inject(method = "onCursorPos", at = @At("HEAD")) private void onMouseMove(long window, double mouseX, double mouseY, CallbackInfo ci) { if (window == this.client.getWindow().getHandle()) Phosphor.EVENTBUS.post(MouseMoveEvent.get(mouseX, mouseY)); } @Inject(method = "updateMouse", at = @At("HEAD")) private void onMouseUpdate(CallbackInfo ci) { Phosphor.EVENTBUS.post(MouseUpdateEvent.get()); } @Inject(method = "onMouseButton", at = @At("HEAD"), cancellable = true) private void onMouseButton(long window, int button, int action, int mods, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { ci.cancel(); } Phosphor.EVENTBUS.post(MousePressEvent.get(button, action)); } @Inject(method = "onMouseScroll", at = @At("HEAD"), cancellable = true) private void onMouseScroll(long window, double horizontal, double vertical, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { double scrollY = vertical * 30; if (ImguiLoader.isRendered(AsteriaNewMenu.getInstance())) { AsteriaNewMenu.getInstance().scrollY -= scrollY;
package net.Poluteclient.phosphor.mixin; @Mixin(Mouse.class) public class MouseMixin { @Shadow @Final private MinecraftClient client; @Inject(method = "onCursorPos", at = @At("HEAD")) private void onMouseMove(long window, double mouseX, double mouseY, CallbackInfo ci) { if (window == this.client.getWindow().getHandle()) Phosphor.EVENTBUS.post(MouseMoveEvent.get(mouseX, mouseY)); } @Inject(method = "updateMouse", at = @At("HEAD")) private void onMouseUpdate(CallbackInfo ci) { Phosphor.EVENTBUS.post(MouseUpdateEvent.get()); } @Inject(method = "onMouseButton", at = @At("HEAD"), cancellable = true) private void onMouseButton(long window, int button, int action, int mods, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { ci.cancel(); } Phosphor.EVENTBUS.post(MousePressEvent.get(button, action)); } @Inject(method = "onMouseScroll", at = @At("HEAD"), cancellable = true) private void onMouseScroll(long window, double horizontal, double vertical, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { double scrollY = vertical * 30; if (ImguiLoader.isRendered(AsteriaNewMenu.getInstance())) { AsteriaNewMenu.getInstance().scrollY -= scrollY;
} else if (ImguiLoader.isRendered(AsteriaMenu.getInstance())) {
0
2023-11-11 17:14:20+00:00
12k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/debug/DebugEntities.java
[ { "identifier": "DragonModel", "path": "src/main/java/useless/dragonfly/debug/testentity/Dragon/DragonModel.java", "snippet": "public class DragonModel extends BenchEntityModel {\n}" }, { "identifier": "DragonRenderer", "path": "src/main/java/useless/dragonfly/debug/testentity/Dragon/DragonR...
import net.minecraft.client.gui.guidebook.mobs.MobInfoRegistry; import net.minecraft.core.Global; import turniplabs.halplibe.helper.EntityHelper; import useless.dragonfly.debug.testentity.Dragon.DragonModel; import useless.dragonfly.debug.testentity.Dragon.DragonRenderer; import useless.dragonfly.debug.testentity.Dragon.EntityDragon; import useless.dragonfly.debug.testentity.HTest.EntityHTest; import useless.dragonfly.debug.testentity.HTest.HModelTest; import useless.dragonfly.debug.testentity.HTest.RenderHTest; import useless.dragonfly.debug.testentity.Warden.EntityWarden; import useless.dragonfly.debug.testentity.Warden.WardenModel; import useless.dragonfly.debug.testentity.Warden.WardenRenderer; import useless.dragonfly.debug.testentity.Zombie.EntityZombieTest; import useless.dragonfly.debug.testentity.Zombie.RenderZombieTest; import useless.dragonfly.debug.testentity.Zombie.ZombieModelTest; import useless.dragonfly.helper.AnimationHelper; import useless.dragonfly.helper.ModelHelper; import static useless.dragonfly.DragonFly.MOD_ID;
8,300
package useless.dragonfly.debug; public class DebugEntities { public static void init(){ EntityHelper.Core.createEntity(EntityHTest.class, 1000, "ht"); EntityHelper.Core.createEntity(EntityZombieTest.class, 1000, "zt"); AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "zombie_test.animation"); EntityHelper.Core.createEntity(EntityDragon.class, 1001, "dragon"); EntityHelper.Core.createEntity(EntityWarden.class, 1002, "warden"); MobInfoRegistry.register(EntityWarden.class, "df.warden.name", "df.warden.desc", 20, 0, null); if (!Global.isServer){
package useless.dragonfly.debug; public class DebugEntities { public static void init(){ EntityHelper.Core.createEntity(EntityHTest.class, 1000, "ht"); EntityHelper.Core.createEntity(EntityZombieTest.class, 1000, "zt"); AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "zombie_test.animation"); EntityHelper.Core.createEntity(EntityDragon.class, 1001, "dragon"); EntityHelper.Core.createEntity(EntityWarden.class, 1002, "warden"); MobInfoRegistry.register(EntityWarden.class, "df.warden.name", "df.warden.desc", 20, 0, null); if (!Global.isServer){
EntityHelper.Client.assignEntityRenderer(EntityHTest.class, new RenderHTest(ModelHelper.getOrCreateEntityModel(MOD_ID, "hierachytest.json", HModelTest.class), 0.5f));
13
2023-11-16 01:10:52+00:00
12k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/utils/rabbitmq/RabbitMqUtils.java
[ { "identifier": "SpringContextHolder", "path": "src/main/java/top/sharehome/springbootinittemplate/config/bean/SpringContextHolder.java", "snippet": "@Component\n@Slf4j\npublic class SpringContextHolder implements ApplicationContextAware {\n\n /**\n * 以静态变量保存ApplicationContext,可在任意代码中取出Applicaito...
import com.alibaba.fastjson2.JSON; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.config.rabbitmq.BaseCustomizeMq; import top.sharehome.springbootinittemplate.config.rabbitmq.BaseCustomizeMqWithDelay; import top.sharehome.springbootinittemplate.config.rabbitmq.BaseCustomizeMqWithDlx; import top.sharehome.springbootinittemplate.config.rabbitmq.condition.RabbitMqCondition; import top.sharehome.springbootinittemplate.config.rabbitmq.defaultMq.DefaultRabbitMq; import top.sharehome.springbootinittemplate.config.rabbitmq.defaultMq.DefaultRabbitMqWithDelay; import top.sharehome.springbootinittemplate.config.rabbitmq.defaultMq.DefaultRabbitMqWithDlx; import top.sharehome.springbootinittemplate.config.rabbitmq.properties.RabbitMqProperties; import top.sharehome.springbootinittemplate.utils.rabbitmq.model.RabbitMessage; import javax.annotation.PostConstruct; import java.lang.reflect.Field; import java.util.Objects; import java.util.UUID;
7,612
*/ public static void sendMsgWithDlx(Object message, Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { String exchangeWithDlxName; String bindingWithDlxRoutingKey; try { Field exchangeWithDlxNameField = rabbitmqClass.getField("EXCHANGE_WITH_DLX_NAME"); exchangeWithDlxName = (String) exchangeWithDlxNameField.get(null); Field bindingWithDlxRoutingKeyField = rabbitmqClass.getField("BINDING_WITH_DLX_ROUTING_KEY"); bindingWithDlxRoutingKey = (String) bindingWithDlxRoutingKeyField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return; } String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(UUID.randomUUID().toString()); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(exchangeWithDlxName, bindingWithDlxRoutingKey, sendRes); } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); } } /** * 向带有死信队列的消息队列发送消息 * * @param msgId 消息ID * @param message 消息体 * @param rabbitmqClass 消息队列类 */ public static void sendMsgWithDlx(String msgId, Object message, Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { String exchangeWithDlxName; String bindingWithDlxRoutingKey; try { Field exchangeWithDlxNameField = rabbitmqClass.getField("EXCHANGE_WITH_DLX_NAME"); exchangeWithDlxName = (String) exchangeWithDlxNameField.get(null); Field bindingWithDlxRoutingKeyField = rabbitmqClass.getField("BINDING_WITH_DLX_ROUTING_KEY"); bindingWithDlxRoutingKey = (String) bindingWithDlxRoutingKeyField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return; } String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(msgId); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(exchangeWithDlxName, bindingWithDlxRoutingKey, sendRes); } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); } } /** * 从带有死信队列的消息队列获取消息 * * @param rabbitmqClass 消息队列类 * @return 返回消息体 */ public static RabbitMessage receiveMsgWithDlx(Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); String queueWithDlxName; if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { try { Field queueWithDlxNameField = rabbitmqClass.getField("QUEUE_WITH_DLX_NAME"); queueWithDlxName = (String) queueWithDlxNameField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } Object res = RABBITMQ_TEMPLATE.receiveAndConvert(queueWithDlxName, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(res.toString(), RabbitMessage.class); } /** * 从消息队列的死信队列中获取消息 * * @param rabbitmqClass 消息队列类 * @return 返回消息体 */ public static RabbitMessage receiveMsgWithDlxInDlx(Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); String dlxQueueName; if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { try { Field dlxQueueNameField = rabbitmqClass.getField("DLX_QUEUE_NAME"); dlxQueueName = (String) dlxQueueNameField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } Object res = RABBITMQ_TEMPLATE.receiveAndConvert(dlxQueueName, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(Objects.requireNonNull(res).toString(), RabbitMessage.class); } /** * 向延迟队列发送消息 * * @param message 消息体 * @param rabbitmqClass 消息队列类 */
package top.sharehome.springbootinittemplate.utils.rabbitmq; /** * RabbitMq工具类 * * @author AntonyCheng */ @AllArgsConstructor @Slf4j public class RabbitMqUtils { /** * 被封装的RabbitMq客户端 */ private static final RabbitTemplate RABBITMQ_TEMPLATE = SpringContextHolder.getBean("rabbitTemplateBean", RabbitTemplate.class); private final RabbitMqProperties rabbitMqProperties; private static long maxAwaitTimeout; @PostConstruct private void setMaxAwaitTimeout() { maxAwaitTimeout = rabbitMqProperties.getMaxAwaitTimeout(); } /** * 向默认的不带有死信队列的消息队列发送消息 * * @param message 消息体 */ public static void defaultSendMsg(Object message) { String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(UUID.randomUUID().toString()); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(DefaultRabbitMq.EXCHANGE_NAME, DefaultRabbitMq.BINDING_ROUTING_KEY, sendRes); } /** * 向默认的不带有死信队列的消息队列发送消息 * * @param msgId 消息ID * @param message 消息体 */ public static void defaultSendMsg(String msgId, Object message) { String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(msgId); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(DefaultRabbitMq.EXCHANGE_NAME, DefaultRabbitMq.BINDING_ROUTING_KEY, sendRes); } /** * 从默认的不带有死信队列的消息队列获取消息 * * @return 返回消息体 */ public static RabbitMessage defaultReceiveMsg() { Object res = RABBITMQ_TEMPLATE.receiveAndConvert(DefaultRabbitMq.QUEUE_NAME, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(res.toString(), RabbitMessage.class); } /** * 向默认的带有死信队列的消息队列发送消息 * * @param message 消息体 */ public static void defaultSendMsgWithDlx(Object message) { String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(UUID.randomUUID().toString()); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(DefaultRabbitMqWithDlx.EXCHANGE_WITH_DLX_NAME, DefaultRabbitMqWithDlx.BINDING_WITH_DLX_ROUTING_KEY, sendRes); } /** * 向默认的带有死信队列的消息队列发送消息 * * @param msgId 消息ID * @param message 消息体 */ public static void defaultSendMsgWithDlx(String msgId, Object message) { String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(msgId); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(DefaultRabbitMqWithDlx.EXCHANGE_WITH_DLX_NAME, DefaultRabbitMqWithDlx.BINDING_WITH_DLX_ROUTING_KEY, sendRes); } /** * 从默认的带有死信队列的消息队列获取消息 * * @return 返回消息体 */ public static RabbitMessage defaultReceiveMsgWithDlx() { Object res = RABBITMQ_TEMPLATE.receiveAndConvert(DefaultRabbitMqWithDlx.QUEUE_WITH_DLX_NAME, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(res.toString(), RabbitMessage.class); } /** * 从默认的消息队列的死信队列中获取消息 * * @return 返回消息体 */ public static RabbitMessage defaultReceiveMsgWithDlxInDlx() { Object res = RABBITMQ_TEMPLATE.receiveAndConvert(DefaultRabbitMqWithDlx.DLX_QUEUE_WITH_DLX_NAME, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(Objects.requireNonNull(res).toString(), RabbitMessage.class); } /** * 向默认的延迟队列发送消息 * * @param message 消息体 */ public static void defaultSendMsgWithDelay(Object message) { String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(UUID.randomUUID().toString()); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(DefaultRabbitMqWithDelay.EXCHANGE_WITH_DELAY_NAME, DefaultRabbitMqWithDelay.BINDING_WITH_DELAY_ROUTING_KEY, sendRes); } /** * 向默认的延迟队列发送消息 * * @param msgId 消息ID * @param message 消息体 */ public static void defaultSendMsgWithDelay(String msgId, Object message) { String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(msgId); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(DefaultRabbitMqWithDelay.EXCHANGE_WITH_DELAY_NAME, DefaultRabbitMqWithDelay.BINDING_WITH_DELAY_ROUTING_KEY, sendRes); } /** * 从默认的延迟队列获取消息 * * @return 返回消息体 */ public static RabbitMessage defaultReceiveMsgWithDelay() { Object res = RABBITMQ_TEMPLATE.receiveAndConvert(DefaultRabbitMqWithDelay.DLX_QUEUE_WITH_DELAY_NAME, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(res.toString(), RabbitMessage.class); } /** * 向不带有死信队列的消息队列发送消息 * * @param message 消息体 * @param rabbitmqClass 消息队列类 */ public static void sendMsg(Object message, Class<? extends BaseCustomizeMq> rabbitmqClass) { String className = rabbitmqClass.getName(); if (!StringUtils.equals("BaseCustomizeMq", className.split(rabbitmqClass.getPackage().getName())[1])) { String exchangeName; String bindingRouteKey; try { Field exchangeNameField = rabbitmqClass.getField("EXCHANGE_NAME"); exchangeName = (String) exchangeNameField.get(null); Field bindingRouteKeyField = rabbitmqClass.getField("BINDING_ROUTING_KEY"); bindingRouteKey = (String) bindingRouteKeyField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq [{}] is incorrect", className); return; } String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(UUID.randomUUID().toString()); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(exchangeName, bindingRouteKey, sendRes); } else { log.error(">>>>>>>>>> the custom rabbitmq [{}] is incorrect", className); } } /** * 向不带有死信队列的消息队列发送消息 * * @param msgId 消息ID * @param message 消息体 * @param rabbitmqClass 消息队列类 */ public static void sendMsg(String msgId, Object message, Class<? extends BaseCustomizeMq> rabbitmqClass) { String className = rabbitmqClass.getName(); if (!StringUtils.equals("BaseCustomizeMq", className.split(rabbitmqClass.getPackage().getName())[1])) { String exchangeName; String bindingRouteKey; try { Field exchangeNameField = rabbitmqClass.getField("EXCHANGE_NAME"); exchangeName = (String) exchangeNameField.get(null); Field bindingRouteKeyField = rabbitmqClass.getField("BINDING_ROUTING_KEY"); bindingRouteKey = (String) bindingRouteKeyField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq [{}] is incorrect", className); return; } String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(msgId); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(exchangeName, bindingRouteKey, sendRes); } else { log.error(">>>>>>>>>> the custom rabbitmq [{}] is incorrect", className); } } /** * 从不带有死信队列的消息队列获取消息 * * @param rabbitmqClass 消息队列类 * @return 返回消息体 */ public static RabbitMessage receiveMsg(Class<? extends BaseCustomizeMq> rabbitmqClass) { String className = rabbitmqClass.getName(); String queueName; if (!StringUtils.equals("BaseCustomizeMq", className.split(rabbitmqClass.getPackage().getName())[1])) { try { Field queueNameField = rabbitmqClass.getField("QUEUE_NAME"); queueName = (String) queueNameField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq [{}] is incorrect", className); return null; } } else { log.error(">>>>>>>>>> the custom rabbitmq [{}] is incorrect", className); return null; } Object res = RABBITMQ_TEMPLATE.receiveAndConvert(queueName, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(res.toString(), RabbitMessage.class); } /** * 向带有死信队列的消息队列发送消息 * * @param message 消息体 * @param rabbitmqClass 消息队列类 */ public static void sendMsgWithDlx(Object message, Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { String exchangeWithDlxName; String bindingWithDlxRoutingKey; try { Field exchangeWithDlxNameField = rabbitmqClass.getField("EXCHANGE_WITH_DLX_NAME"); exchangeWithDlxName = (String) exchangeWithDlxNameField.get(null); Field bindingWithDlxRoutingKeyField = rabbitmqClass.getField("BINDING_WITH_DLX_ROUTING_KEY"); bindingWithDlxRoutingKey = (String) bindingWithDlxRoutingKeyField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return; } String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(UUID.randomUUID().toString()); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(exchangeWithDlxName, bindingWithDlxRoutingKey, sendRes); } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); } } /** * 向带有死信队列的消息队列发送消息 * * @param msgId 消息ID * @param message 消息体 * @param rabbitmqClass 消息队列类 */ public static void sendMsgWithDlx(String msgId, Object message, Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { String exchangeWithDlxName; String bindingWithDlxRoutingKey; try { Field exchangeWithDlxNameField = rabbitmqClass.getField("EXCHANGE_WITH_DLX_NAME"); exchangeWithDlxName = (String) exchangeWithDlxNameField.get(null); Field bindingWithDlxRoutingKeyField = rabbitmqClass.getField("BINDING_WITH_DLX_ROUTING_KEY"); bindingWithDlxRoutingKey = (String) bindingWithDlxRoutingKeyField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return; } String msgText = JSON.toJSONString(message); RabbitMessage rabbitMessage = new RabbitMessage(); rabbitMessage.setMsgId(msgId); rabbitMessage.setMsgText(msgText); String sendRes = JSON.toJSONString(rabbitMessage); RABBITMQ_TEMPLATE.convertAndSend(exchangeWithDlxName, bindingWithDlxRoutingKey, sendRes); } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); } } /** * 从带有死信队列的消息队列获取消息 * * @param rabbitmqClass 消息队列类 * @return 返回消息体 */ public static RabbitMessage receiveMsgWithDlx(Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); String queueWithDlxName; if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { try { Field queueWithDlxNameField = rabbitmqClass.getField("QUEUE_WITH_DLX_NAME"); queueWithDlxName = (String) queueWithDlxNameField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } Object res = RABBITMQ_TEMPLATE.receiveAndConvert(queueWithDlxName, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(res.toString(), RabbitMessage.class); } /** * 从消息队列的死信队列中获取消息 * * @param rabbitmqClass 消息队列类 * @return 返回消息体 */ public static RabbitMessage receiveMsgWithDlxInDlx(Class<? extends BaseCustomizeMqWithDlx> rabbitmqClass) { String className = rabbitmqClass.getName(); String dlxQueueName; if (!StringUtils.equals("BaseCustomizeMqWithDlx", className.split(rabbitmqClass.getPackage().getName())[1])) { try { Field dlxQueueNameField = rabbitmqClass.getField("DLX_QUEUE_NAME"); dlxQueueName = (String) dlxQueueNameField.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } } else { log.error(">>>>>>>>>> the custom rabbitmq with dlx [{}] is incorrect", className); return null; } Object res = RABBITMQ_TEMPLATE.receiveAndConvert(dlxQueueName, maxAwaitTimeout); if (ObjectUtils.isEmpty(res)) { return null; } return JSON.parseObject(Objects.requireNonNull(res).toString(), RabbitMessage.class); } /** * 向延迟队列发送消息 * * @param message 消息体 * @param rabbitmqClass 消息队列类 */
public static void sendMsgWithDelay(Object message, Class<? extends BaseCustomizeMqWithDelay> rabbitmqClass) {
2
2023-11-12 07:49:59+00:00
12k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/Renderer2D.java
[ { "identifier": "ResourceUtil", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/io/ResourceUtil.java", "snippet": "public final class ResourceUtil {\n /**\n * Reads a resource as an {@code InputStream}.\n *\n * @param path resource path to read\n * @return stream to read ...
import com.github.rmheuer.azalea.io.ResourceUtil; import com.github.rmheuer.azalea.render.ColorRGBA; import com.github.rmheuer.azalea.render.Renderer; import com.github.rmheuer.azalea.render.mesh.Mesh; import com.github.rmheuer.azalea.render.mesh.MeshData; import com.github.rmheuer.azalea.render.pipeline.ActivePipeline; import com.github.rmheuer.azalea.render.pipeline.PipelineInfo; import com.github.rmheuer.azalea.render.shader.ShaderProgram; import com.github.rmheuer.azalea.render.texture.Bitmap; import com.github.rmheuer.azalea.render.texture.Texture2D; import com.github.rmheuer.azalea.utils.SafeCloseable; import org.joml.Matrix4f; import java.io.IOException; import java.util.List;
9,069
package com.github.rmheuer.azalea.render2d; /** * Renderer to render {@code DrawList2D}s. */ public final class Renderer2D implements SafeCloseable { public static final int MAX_TEXTURE_SLOTS = 16; private static final String VERTEX_SHADER_PATH = "azalea/shaders/render2d/vertex.glsl"; private static final String FRAGMENT_SHADER_PATH = "azalea/shaders/render2d/fragment.glsl"; private final Renderer renderer; private final Mesh mesh; private final ShaderProgram shader; private final Texture2D whiteTex; /** * @param renderer renderer to use for rendering */ public Renderer2D(Renderer renderer) { this.renderer = renderer; mesh = renderer.createMesh(); try { shader = renderer.createShaderProgram( ResourceUtil.readAsStream(VERTEX_SHADER_PATH), ResourceUtil.readAsStream(FRAGMENT_SHADER_PATH)); } catch (IOException e) { throw new RuntimeException("Failed to load built-in shaders", e); } Bitmap whiteData = new Bitmap(1, 1, ColorRGBA.white()); whiteTex = renderer.createTexture2D(); whiteTex.setData(whiteData); try (ActivePipeline pipe = renderer.bindPipeline(new PipelineInfo(shader))) { for (int i = 0; i < MAX_TEXTURE_SLOTS; i++) { pipe.getUniform("u_Textures[" + i + "]").setInt(i); } } } private void drawBatch(ActivePipeline pipeline, VertexBatch batch) { Texture2D[] textures = batch.getTextures(); for (int i = 0; i < MAX_TEXTURE_SLOTS; i++) { Texture2D tex = textures[i]; if (tex != null) { pipeline.bindTexture(i, tex); } }
package com.github.rmheuer.azalea.render2d; /** * Renderer to render {@code DrawList2D}s. */ public final class Renderer2D implements SafeCloseable { public static final int MAX_TEXTURE_SLOTS = 16; private static final String VERTEX_SHADER_PATH = "azalea/shaders/render2d/vertex.glsl"; private static final String FRAGMENT_SHADER_PATH = "azalea/shaders/render2d/fragment.glsl"; private final Renderer renderer; private final Mesh mesh; private final ShaderProgram shader; private final Texture2D whiteTex; /** * @param renderer renderer to use for rendering */ public Renderer2D(Renderer renderer) { this.renderer = renderer; mesh = renderer.createMesh(); try { shader = renderer.createShaderProgram( ResourceUtil.readAsStream(VERTEX_SHADER_PATH), ResourceUtil.readAsStream(FRAGMENT_SHADER_PATH)); } catch (IOException e) { throw new RuntimeException("Failed to load built-in shaders", e); } Bitmap whiteData = new Bitmap(1, 1, ColorRGBA.white()); whiteTex = renderer.createTexture2D(); whiteTex.setData(whiteData); try (ActivePipeline pipe = renderer.bindPipeline(new PipelineInfo(shader))) { for (int i = 0; i < MAX_TEXTURE_SLOTS; i++) { pipe.getUniform("u_Textures[" + i + "]").setInt(i); } } } private void drawBatch(ActivePipeline pipeline, VertexBatch batch) { Texture2D[] textures = batch.getTextures(); for (int i = 0; i < MAX_TEXTURE_SLOTS; i++) { Texture2D tex = textures[i]; if (tex != null) { pipeline.bindTexture(i, tex); } }
try (MeshData data = batch.getData()) {
4
2023-11-16 04:46:53+00:00
12k
Shushandr/offroad
src/net/osmand/data/Amenity.java
[ { "identifier": "Location", "path": "src/net/osmand/Location.java", "snippet": "public class Location {\n \n private String mProvider;\n private long mTime = 0;\n private double mLatitude = 0.0;\n private double mLongitude = 0.0;\n private boolean mHasAltitude = false;\n private dou...
import net.osmand.Location; import net.osmand.osm.PoiCategory; import net.osmand.util.Algorithms; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream;
9,928
package net.osmand.data; public class Amenity extends MapObject { public static final String WEBSITE = "website"; public static final String PHONE = "phone"; public static final String DESCRIPTION = "description"; public static final String OPENING_HOURS = "opening_hours"; public static final String CONTENT = "content"; private String subType;
package net.osmand.data; public class Amenity extends MapObject { public static final String WEBSITE = "website"; public static final String PHONE = "phone"; public static final String DESCRIPTION = "description"; public static final String OPENING_HOURS = "opening_hours"; public static final String CONTENT = "content"; private String subType;
private PoiCategory type;
1
2023-11-15 05:04:55+00:00
12k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmAppraisalPlanController.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu...
import cn.hutool.core.collection.ListUtil; import com.alibaba.fastjson.JSONObject; import com.kakarote.common.log.annotation.OperateLog; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.entity.OperationResult; import com.kakarote.common.log.enums.ApplyEnum; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.common.log.enums.OperateObjectEnum; import com.kakarote.core.common.Result; import com.kakarote.core.entity.BasePage; import com.kakarote.hrm.entity.BO.*; import com.kakarote.hrm.entity.VO.*; import com.kakarote.hrm.service.IHrmAppraisalPlanService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
9,924
package com.kakarote.hrm.controller; /** * <p> * 考核计划基础信息表 前端控制器 * </p> * * @author zyl * @since 2022-05-21 */ @Api(tags = "考核计划相关接口") @RestController @RequestMapping("/hrmAppraisalPlan") public class HrmAppraisalPlanController { @Autowired IHrmAppraisalPlanService hrmAppraisalPlanService; @ApiOperation("查看考核计划列表") @PostMapping("/queryPageList") public Result<BasePage<AppraisalPlanVO>> queryPageList(@RequestBody QueryAppraisalPlanBO queryAppraisalPlanBO) { BasePage<AppraisalPlanVO> planList = hrmAppraisalPlanService.queryPageList(queryAppraisalPlanBO); return Result.ok(planList); } @PostMapping("/queryField") @ApiOperation("查询场景搜索字段") public Result<List<HrmModelFiledVO>> queryField(@RequestParam("appraisalPlanId") Long appraisalPlanId) { List<HrmModelFiledVO> filedVOS = hrmAppraisalPlanService.queryField(appraisalPlanId); return Result.ok(filedVOS); } @ApiOperation("查询员工考核绩效列表") @PostMapping("/queryEmployeeAppraisalList") public Result<BasePage<AppraisalPlanOfEmployeeVO>> queryEmployeeAppraisalList(@RequestBody QueryEmployeeQuotaBO queryEmployeeQuotaBO) { BasePage<AppraisalPlanOfEmployeeVO> appraisalPlanList = hrmAppraisalPlanService.queryEmployeeAppraisalList(queryEmployeeQuotaBO); return Result.ok(appraisalPlanList); } @PostMapping("/queryAppraisalResultPageList") @ApiOperation("考核结果列表接口") public Result<BasePage<Map<String, Object>>> queryAppraisalResultPageList(@RequestBody HrmSearchBO search) { search.setPageType(1); BasePage<Map<String, Object>> mapBasePage = hrmAppraisalPlanService.queryAppraisalResultPageList(search); return Result.ok(mapBasePage); } @ApiOperation("保存考核计划") @PostMapping("/addAppraisalPlan") @OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_KPI) public Result<Long> addAppraisalPlan(@RequestBody AppraisalPlanBO appraisalPlanBO) { OperationLog operationLog = hrmAppraisalPlanService.addOrUpdate(appraisalPlanBO); JSONObject operationObject = (JSONObject) operationLog.getOperationObject(); return OperationResult.ok(operationObject.getLong("typeId"), ListUtil.toList(operationLog)); } @ApiOperation("查看考核设置") @PostMapping("/querySetting") public Result<AppraisalPlanSettingInfoVO> querySetting(@RequestBody AppraisalPlanReq appraisalPlanReq) { AppraisalPlanSettingInfoVO planSettingInfo = hrmAppraisalPlanService.querySetting(appraisalPlanReq.getAppraisalPlanId()); return Result.ok(planSettingInfo); } @ApiOperation("删除考核计划") @PostMapping("/delAppraisalPlan")
package com.kakarote.hrm.controller; /** * <p> * 考核计划基础信息表 前端控制器 * </p> * * @author zyl * @since 2022-05-21 */ @Api(tags = "考核计划相关接口") @RestController @RequestMapping("/hrmAppraisalPlan") public class HrmAppraisalPlanController { @Autowired IHrmAppraisalPlanService hrmAppraisalPlanService; @ApiOperation("查看考核计划列表") @PostMapping("/queryPageList") public Result<BasePage<AppraisalPlanVO>> queryPageList(@RequestBody QueryAppraisalPlanBO queryAppraisalPlanBO) { BasePage<AppraisalPlanVO> planList = hrmAppraisalPlanService.queryPageList(queryAppraisalPlanBO); return Result.ok(planList); } @PostMapping("/queryField") @ApiOperation("查询场景搜索字段") public Result<List<HrmModelFiledVO>> queryField(@RequestParam("appraisalPlanId") Long appraisalPlanId) { List<HrmModelFiledVO> filedVOS = hrmAppraisalPlanService.queryField(appraisalPlanId); return Result.ok(filedVOS); } @ApiOperation("查询员工考核绩效列表") @PostMapping("/queryEmployeeAppraisalList") public Result<BasePage<AppraisalPlanOfEmployeeVO>> queryEmployeeAppraisalList(@RequestBody QueryEmployeeQuotaBO queryEmployeeQuotaBO) { BasePage<AppraisalPlanOfEmployeeVO> appraisalPlanList = hrmAppraisalPlanService.queryEmployeeAppraisalList(queryEmployeeQuotaBO); return Result.ok(appraisalPlanList); } @PostMapping("/queryAppraisalResultPageList") @ApiOperation("考核结果列表接口") public Result<BasePage<Map<String, Object>>> queryAppraisalResultPageList(@RequestBody HrmSearchBO search) { search.setPageType(1); BasePage<Map<String, Object>> mapBasePage = hrmAppraisalPlanService.queryAppraisalResultPageList(search); return Result.ok(mapBasePage); } @ApiOperation("保存考核计划") @PostMapping("/addAppraisalPlan") @OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_KPI) public Result<Long> addAppraisalPlan(@RequestBody AppraisalPlanBO appraisalPlanBO) { OperationLog operationLog = hrmAppraisalPlanService.addOrUpdate(appraisalPlanBO); JSONObject operationObject = (JSONObject) operationLog.getOperationObject(); return OperationResult.ok(operationObject.getLong("typeId"), ListUtil.toList(operationLog)); } @ApiOperation("查看考核设置") @PostMapping("/querySetting") public Result<AppraisalPlanSettingInfoVO> querySetting(@RequestBody AppraisalPlanReq appraisalPlanReq) { AppraisalPlanSettingInfoVO planSettingInfo = hrmAppraisalPlanService.querySetting(appraisalPlanReq.getAppraisalPlanId()); return Result.ok(planSettingInfo); } @ApiOperation("删除考核计划") @PostMapping("/delAppraisalPlan")
@OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_KPI, behavior = BehaviorEnum.DELETE)
3
2023-10-17 05:49:52+00:00
12k
WisdomShell/codeshell-intellij
src/main/java/com/codeshell/intellij/widget/CodeShellWidget.java
[ { "identifier": "CodeShellStatus", "path": "src/main/java/com/codeshell/intellij/enums/CodeShellStatus.java", "snippet": "public enum CodeShellStatus {\n UNKNOWN(0, \"Unknown\"),\n OK(200, \"OK\"),\n BAD_REQUEST(400, \"Bad request/token\"),\n NOT_FOUND(404, \"404 Not found\"),\n TOO_MANY_...
import com.codeshell.intellij.enums.CodeShellStatus; import com.codeshell.intellij.services.CodeShellCompleteService; import com.codeshell.intellij.settings.CodeShellSettings; import com.codeshell.intellij.utils.CodeGenHintRenderer; import com.codeshell.intellij.utils.CodeShellIcons; import com.codeshell.intellij.utils.CodeShellUtils; import com.codeshell.intellij.utils.EditorUtils; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.impl.EditorComponentImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.openapi.wm.impl.status.EditorBasedWidget; import com.intellij.util.Consumer; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.CompletableFuture;
7,605
} }; } @Override public void install(@NotNull StatusBar statusBar) { super.install(statusBar); EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster(); multicaster.addCaretListener(this, this); multicaster.addSelectionListener(this, this); multicaster.addDocumentListener(this, this); KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this); Disposer.register(this, () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", this) ); } private Editor getFocusOwnerEditor() { Component component = getFocusOwnerComponent(); Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor(); return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null; } private Component getFocusOwnerComponent() { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (Objects.isNull(focusOwner)) { IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject()); Window frame = focusManager.getLastFocusedIdeWindow(); if (Objects.nonNull(frame)) { focusOwner = focusManager.getLastFocusedFor(frame); } } return focusOwner; } private boolean isFocusedEditor(Editor editor) { Component focusOwner = getFocusOwnerComponent(); return focusOwner == editor.getContentComponent(); } @Override public void propertyChange(PropertyChangeEvent evt) { updateInlayHints(getFocusOwnerEditor()); } @Override public void selectionChanged(SelectionEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretPositionChanged(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretAdded(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretRemoved(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void afterDocumentChange(@NotNull Document document) { enableSuggestion = true; if (ApplicationManager.getApplication().isDispatchThread()) { EditorFactory.getInstance().editors(document) .filter(this::isFocusedEditor) .findFirst() .ifPresent(this::updateInlayHints); } } private void updateInlayHints(Editor focusedEditor) { if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) { return; } VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument()); if (Objects.isNull(file)) { return; } String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText(); if (Objects.nonNull(selection) && !selection.isEmpty()) { String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION); if (Objects.nonNull(existingHints) && existingHints.length > 0) { file.putUserData(SHELL_CODER_CODE_SUGGESTION, null); file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset()); InlayModel inlayModel = focusedEditor.getInlayModel(); inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints); inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints); } return; } Integer codeShellPos = file.getUserData(SHELL_CODER_POSITION); int lastPosition = (Objects.isNull(codeShellPos)) ? 0 : codeShellPos; int currentPosition = focusedEditor.getCaretModel().getOffset(); if (lastPosition == currentPosition) return; InlayModel inlayModel = focusedEditor.getInlayModel(); if (currentPosition > lastPosition) { String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION); if (Objects.nonNull(existingHints) && existingHints.length > 0) { String inlineHint = existingHints[0]; String modifiedText = focusedEditor.getDocument().getCharsSequence().subSequence(lastPosition, currentPosition).toString(); if (modifiedText.startsWith("\n")) { modifiedText = modifiedText.replace(" ", ""); } if (inlineHint.startsWith(modifiedText)) { inlineHint = inlineHint.substring(modifiedText.length()); enableSuggestion = false; if (inlineHint.length() > 0) { inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
package com.codeshell.intellij.widget; public class CodeShellWidget extends EditorBasedWidget implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation, CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener { public static final String ID = "CodeShellWidget"; public static final Key<String[]> SHELL_CODER_CODE_SUGGESTION = new Key<>("CodeShell Code Suggestion"); public static final Key<Integer> SHELL_CODER_POSITION = new Key<>("CodeShell Position"); public static boolean enableSuggestion = false; protected CodeShellWidget(@NotNull Project project) { super(project); } @Override public @NonNls @NotNull String ID() { return ID; } @Override public StatusBarWidget copy() { return new CodeShellWidget(getProject()); } @Override public @Nullable Icon getIcon() { CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class); CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus()); if (status == CodeShellStatus.OK) { return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled; } else { return CodeShellIcons.WidgetError; } } @Override public WidgetPresentation getPresentation() { return this; } @Override public @Nullable @NlsContexts.Tooltip String getTooltipText() { StringBuilder toolTipText = new StringBuilder("CodeShell"); if (CodeShellSettings.getInstance().isSaytEnabled()) { toolTipText.append(" enabled"); } else { toolTipText.append(" disabled"); } CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class); int statusCode = codeShell.getStatus(); CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode); switch (status) { case OK: if (CodeShellSettings.getInstance().isSaytEnabled()) { toolTipText.append(" (Click to disable)"); } else { toolTipText.append(" (Click to enable)"); } break; case UNKNOWN: toolTipText.append(" (http error "); toolTipText.append(statusCode); toolTipText.append(")"); break; default: toolTipText.append(" ("); toolTipText.append(status.getDisplayValue()); toolTipText.append(")"); } return toolTipText.toString(); } @Override public @Nullable Consumer<MouseEvent> getClickConsumer() { return mouseEvent -> { CodeShellSettings.getInstance().toggleSaytEnabled(); if (Objects.nonNull(myStatusBar)) { myStatusBar.updateWidget(ID); } }; } @Override public void install(@NotNull StatusBar statusBar) { super.install(statusBar); EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster(); multicaster.addCaretListener(this, this); multicaster.addSelectionListener(this, this); multicaster.addDocumentListener(this, this); KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this); Disposer.register(this, () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", this) ); } private Editor getFocusOwnerEditor() { Component component = getFocusOwnerComponent(); Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor(); return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null; } private Component getFocusOwnerComponent() { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (Objects.isNull(focusOwner)) { IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject()); Window frame = focusManager.getLastFocusedIdeWindow(); if (Objects.nonNull(frame)) { focusOwner = focusManager.getLastFocusedFor(frame); } } return focusOwner; } private boolean isFocusedEditor(Editor editor) { Component focusOwner = getFocusOwnerComponent(); return focusOwner == editor.getContentComponent(); } @Override public void propertyChange(PropertyChangeEvent evt) { updateInlayHints(getFocusOwnerEditor()); } @Override public void selectionChanged(SelectionEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretPositionChanged(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretAdded(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretRemoved(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void afterDocumentChange(@NotNull Document document) { enableSuggestion = true; if (ApplicationManager.getApplication().isDispatchThread()) { EditorFactory.getInstance().editors(document) .filter(this::isFocusedEditor) .findFirst() .ifPresent(this::updateInlayHints); } } private void updateInlayHints(Editor focusedEditor) { if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) { return; } VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument()); if (Objects.isNull(file)) { return; } String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText(); if (Objects.nonNull(selection) && !selection.isEmpty()) { String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION); if (Objects.nonNull(existingHints) && existingHints.length > 0) { file.putUserData(SHELL_CODER_CODE_SUGGESTION, null); file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset()); InlayModel inlayModel = focusedEditor.getInlayModel(); inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints); inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints); } return; } Integer codeShellPos = file.getUserData(SHELL_CODER_POSITION); int lastPosition = (Objects.isNull(codeShellPos)) ? 0 : codeShellPos; int currentPosition = focusedEditor.getCaretModel().getOffset(); if (lastPosition == currentPosition) return; InlayModel inlayModel = focusedEditor.getInlayModel(); if (currentPosition > lastPosition) { String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION); if (Objects.nonNull(existingHints) && existingHints.length > 0) { String inlineHint = existingHints[0]; String modifiedText = focusedEditor.getDocument().getCharsSequence().subSequence(lastPosition, currentPosition).toString(); if (modifiedText.startsWith("\n")) { modifiedText = modifiedText.replace(" ", ""); } if (inlineHint.startsWith(modifiedText)) { inlineHint = inlineHint.substring(modifiedText.length()); enableSuggestion = false; if (inlineHint.length() > 0) { inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
inlayModel.addInlineElement(currentPosition, true, new CodeGenHintRenderer(inlineHint));
3
2023-10-18 06:29:13+00:00
12k
zhaoeryu/eu-backend
eu-generate/src/main/java/cn/eu/generate/service/impl/GenTableServiceImpl.java
[ { "identifier": "EuServiceImpl", "path": "eu-common-core/src/main/java/cn/eu/common/base/service/impl/EuServiceImpl.java", "snippet": "public abstract class EuServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IEuService<T> {\n\n /**\n * 分页参数从1开始\n */\n protected ...
import cn.eu.common.base.service.impl.EuServiceImpl; import cn.eu.common.model.PageResult; import cn.eu.generate.constants.GenConstant; import cn.eu.generate.domain.GenTable; import cn.eu.generate.domain.GenTableColumn; import cn.eu.generate.enums.GenMode; import cn.eu.generate.mapper.GenTableMapper; import cn.eu.generate.model.dto.GenerateTemplateDto; import cn.eu.generate.model.vo.TableInfoVo; import cn.eu.generate.service.IGenTableColumnService; import cn.eu.generate.service.IGenTableService; import cn.eu.generate.model.query.GenTableQueryCriteria; import cn.eu.generate.utils.FieldTypeMappingUtil; import cn.eu.generate.utils.GenUtil; import cn.eu.generate.utils.VelocityHelper; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.velocity.VelocityContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
7,238
package cn.eu.generate.service.impl; /** * @author zhaoeryu * @since 2023/6/27 */ @Slf4j @Service
package cn.eu.generate.service.impl; /** * @author zhaoeryu * @since 2023/6/27 */ @Slf4j @Service
public class GenTableServiceImpl extends EuServiceImpl<GenTableMapper, GenTable> implements IGenTableService {
3
2023-10-20 07:08:37+00:00
12k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/recipe/specialRecipe/DSPRecipePool.java
[ { "identifier": "EUEveryAntimatter", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/system/DysonSphereProgram/logic/DSP_Values.java", "snippet": "public static final long EUEveryAntimatter = Config.EUEveryAntimatter;// default 4L * Integer.MAX_VALUE;" }, { "identifier": "EUEveryAntimatterF...
import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.AnnihilationConstrainer; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.Antimatter; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.AntimatterFuelRod; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.ArtificialStar; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.CriticalPhoton; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DSPLauncher; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DSPReceiver; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.DysonSphereFrameComponent; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.EmptySmallLaunchVehicle; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.GravitationalLens; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.ParticleTrapTimeSpaceShield; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.SmallLaunchVehicle; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.SolarSail; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.SpaceWarper; import static com.Nxer.TwistSpaceTechnology.common.GTCMItemList.StellarConstructionFrameMaterial; import static com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_Values.EUEveryAntimatter; import static com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_Values.EUEveryAntimatterFuelRod; import static com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_Values.EUTOfLaunchingNode; import static com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_Values.EUTOfLaunchingSolarSail; import static com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_Values.ticksOfLaunchingNode; import static com.Nxer.TwistSpaceTechnology.system.DysonSphereProgram.logic.DSP_Values.ticksOfLaunchingSolarSail; import static com.Nxer.TwistSpaceTechnology.util.TextHandler.texter; import static com.Nxer.TwistSpaceTechnology.util.Utils.copyAmount; import static com.github.technus.tectech.thing.CustomItemList.eM_Coil; import static com.github.technus.tectech.thing.CustomItemList.eM_Containment; import static com.github.technus.tectech.thing.CustomItemList.eM_Hollow; import static com.github.technus.tectech.thing.CustomItemList.eM_Power; import static com.github.technus.tectech.thing.CustomItemList.eM_Spacetime; import static com.github.technus.tectech.thing.CustomItemList.eM_Ultimate_Containment; import static com.github.technus.tectech.thing.CustomItemList.eM_Ultimate_Containment_Advanced; import static com.github.technus.tectech.thing.CustomItemList.eM_Ultimate_Containment_Field; import static de.katzenpapst.amunra.item.ARItems.jetItemIon; import static de.katzenpapst.amunra.item.ARItems.lightPlating; import static de.katzenpapst.amunra.item.ARItems.noseCone; import static gregtech.api.enums.TierEU.RECIPE_UEV; import static gregtech.api.enums.TierEU.RECIPE_UIV; import static gregtech.api.enums.TierEU.RECIPE_UMV; import static gregtech.api.enums.TierEU.RECIPE_UXV; import static gregtech.api.util.GT_RecipeBuilder.HOURS; import static gregtech.api.util.GT_RecipeConstants.AssemblyLine; import static gregtech.api.util.GT_RecipeConstants.RESEARCH_ITEM; import static gregtech.api.util.GT_RecipeConstants.RESEARCH_TIME; import static gtPlusPlus.core.material.ELEMENT.STANDALONE.ASTRAL_TITANIUM; import static gtPlusPlus.core.material.ELEMENT.STANDALONE.CELESTIAL_TUNGSTEN; import static gtPlusPlus.core.material.ELEMENT.STANDALONE.HYPOGEN; import static gtPlusPlus.xmod.gregtech.api.enums.GregtechItemList.Laser_Lens_Special; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import com.Nxer.TwistSpaceTechnology.common.recipeMap.GTCMRecipe; import com.Nxer.TwistSpaceTechnology.recipe.IRecipePool; import com.dreammaster.gthandler.CustomItemList; import com.dreammaster.gthandler.GT_CoreModSupport; import com.gtnewhorizons.gtnhintergalactic.block.IGBlocks; import com.gtnewhorizons.gtnhintergalactic.recipe.IGRecipeMaps; import galaxyspace.core.register.GSBlocks; import goodgenerator.items.MyMaterial; import gregtech.api.enums.GT_Values; import gregtech.api.enums.ItemList; import gregtech.api.enums.Materials; import gregtech.api.enums.MaterialsKevlar; import gregtech.api.enums.MaterialsUEVplus; import gregtech.api.enums.OrePrefixes; import gregtech.api.interfaces.IRecipeMap; import gregtech.api.recipe.RecipeMaps; import gregtech.api.util.GT_ModHandler; import gregtech.api.util.GT_OreDictUnificator; import gregtech.api.util.GT_Utility; import gtPlusPlus.api.recipe.GTPPRecipeMaps; import gtPlusPlus.core.material.Particle; import micdoodle8.mods.galacticraft.core.blocks.GCBlocks;
9,829
ItemList.Electric_Motor_UEV.get(64), ItemList.Electric_Piston_UEV.get(64), ItemList.Robot_Arm_UEV.get(64), ItemList.Sensor_UEV.get(64), StellarConstructionFrameMaterial.get(64), GT_OreDictUnificator.get(OrePrefixes.wireGt16, Materials.SuperconductorUEV, 64), GT_OreDictUnificator.get(OrePrefixes.gearGt, Materials.Infinity, 16), GT_OreDictUnificator.get(OrePrefixes.gearGt, Materials.Infinity, 16), lightPlating.getItemStack(64), eM_Power.get(64), new ItemStack(IGBlocks.SpaceElevatorCasing, 64), new ItemStack(GSBlocks.DysonSwarmBlocks, 64, 9)) .fluidInputs( new FluidStack(solderPlasma, 144 * 8192), Materials.UUMatter.getFluid(1000 * 128), Materials.SuperCoolant.getFluid(1000 * 1024), Materials.CosmicNeutronium.getMolten(144 * 1024)) .itemOutputs(DSPLauncher.get(1)) .eut(RECIPE_UIV) .duration(20 * 2400) .addTo(AssemblyLine); // eM_Ultimate_Containment_Advanced casing 13 GT_Values.RA.stdBuilder() .itemInputs( eM_Ultimate_Containment.get(64), GT_OreDictUnificator.get(OrePrefixes.plateDense, MaterialsUEVplus.Eternity, 64), GT_OreDictUnificator.get(OrePrefixes.foil, MaterialsUEVplus.SpaceTime, 64), GT_OreDictUnificator.get(OrePrefixes.foil, MaterialsUEVplus.SpaceTime, 64), ItemList.Tesseract.get(16), ItemList.EnergisedTesseract.get(16), ItemList.Field_Generator_UMV.get(8), copyAmount(64, Particle.getBaseParticle(Particle.HIGGS_BOSON))) .fluidInputs(MyMaterial.metastableOganesson.getMolten(144 * 256)) .itemOutputs(eM_Ultimate_Containment_Advanced.get(8)) .noOptimize() .eut(RECIPE_UXV) .duration(20 * 300) .addTo(Assembler); // eM_Ultimate_Containment casing 12 GT_Values.RA.stdBuilder() .itemInputs( eM_Containment.get(1), StellarConstructionFrameMaterial.get(1), GT_OreDictUnificator.get(OrePrefixes.plateDense, MaterialsUEVplus.TranscendentMetal, 16), HYPOGEN.getFoil(64), CELESTIAL_TUNGSTEN.getScrew(64), CELESTIAL_TUNGSTEN.getRing(64), ItemList.Field_Generator_UIV.get(1)) .fluidInputs(MyMaterial.preciousMetalAlloy.getMolten(144 * 64)) .itemOutputs(eM_Ultimate_Containment.get(1)) .noOptimize() .eut(RECIPE_UMV) .duration(20 * 300) .addTo(Assembler); // ArtificialStar GT_Values.RA.stdBuilder() .metadata(RESEARCH_ITEM, AnnihilationConstrainer.get(1)) .metadata(RESEARCH_TIME, 24 * HOURS) .itemInputs( StellarConstructionFrameMaterial.get(64), eM_Spacetime.get(64), eM_Ultimate_Containment_Field.get(64), ItemList.Casing_Dim_Bridge.get(64), eM_Ultimate_Containment_Advanced.get(64), eM_Coil.get(64), eM_Hollow.get(64), ItemList.Electric_Pump_UMV.get(64), AnnihilationConstrainer.get(64), ItemList.Field_Generator_UMV.get(64), CustomItemList.QuantumCircuit.get(64), CustomItemList.PikoCircuit.get(64), CustomItemList.HighEnergyFlowCircuit.get(64), ItemList.Tesseract.get(64), ItemList.EnergisedTesseract.get(64), GT_OreDictUnificator.get(OrePrefixes.plateDense, MaterialsUEVplus.SpaceTime, 64)) .fluidInputs( new FluidStack(solderPlasma, 144 * 8192), MaterialsUEVplus.TranscendentMetal.getMolten(144 * 8192), MaterialsUEVplus.SpaceTime.getMolten(144 * 8192), Materials.SuperconductorUMVBase.getMolten(144 * 8192)) .itemOutputs(ArtificialStar.get(1)) .eut(RECIPE_UXV) .duration(20 * 2400) .addTo(AssemblyLine); // launcher GT_Values.RA.stdBuilder() .itemInputs(SolarSail.get(1)) .itemOutputs(SolarSail.get(1)) .eut(EUTOfLaunchingSolarSail) .duration(ticksOfLaunchingSolarSail) .addTo(DSPLauncherRecipe); GT_Values.RA.stdBuilder() .itemInputs(SmallLaunchVehicle.get(1)) .itemOutputs( SmallLaunchVehicle.get(1) .setStackDisplayName( texter("99%% Return an Empty Small Launch Vehicle.", "NEI.EmptySmallLaunchVehicleRecipe.0")))
package com.Nxer.TwistSpaceTechnology.recipe.specialRecipe; public class DSPRecipePool implements IRecipePool { @Override public void loadRecipes() { final IRecipeMap DSPLauncherRecipe = GTCMRecipe.DSP_LauncherRecipes; final IRecipeMap SpaceAssembler = IGRecipeMaps.spaceAssemblerRecipes; final IRecipeMap Assembler = RecipeMaps.assemblerRecipes; final Fluid solderPlasma = FluidRegistry.getFluid("molten.mutatedlivingsolder"); // DSP Ray Receiving Station GT_Values.RA.stdBuilder() .metadata(RESEARCH_ITEM, DSPLauncher.get(1)) .metadata(RESEARCH_TIME, 24 * HOURS) .itemInputs( ItemList.ZPM3.get(1), GT_OreDictUnificator.get(OrePrefixes.frameGt, Materials.CosmicNeutronium, 64), CustomItemList.HighEnergyFlowCircuit.get(64), CustomItemList.PikoCircuit.get(64), ItemList.Sensor_UEV.get(64), ItemList.Sensor_UEV.get(64), ItemList.Emitter_UEV.get(64), ItemList.Emitter_UEV.get(64), StellarConstructionFrameMaterial.get(64), ItemList.Field_Generator_UEV.get(64), GT_OreDictUnificator.get(OrePrefixes.wireGt16, Materials.SuperconductorUEV, 64), Laser_Lens_Special.get(64), SpaceWarper.get(64), new ItemStack(IGBlocks.SpaceElevatorCasing, 64), new ItemStack(GSBlocks.DysonSwarmBlocks, 64, 9)) .fluidInputs( new FluidStack(solderPlasma, 144 * 8192), Materials.UUMatter.getFluid(1000 * 1024), FluidRegistry.getFluidStack("cryotheum", 1000 * 8192), Materials.CosmicNeutronium.getMolten(144 * 1024)) .itemOutputs(DSPReceiver.get(1)) .eut(RECIPE_UIV) .duration(20 * 2400) .addTo(AssemblyLine); // DSP Launch Site machine GT_Values.RA.stdBuilder() .metadata(RESEARCH_ITEM, new ItemStack(GCBlocks.landingPad, 1, 0)) .metadata(RESEARCH_TIME, 24 * HOURS) .itemInputs( new ItemStack(GCBlocks.landingPad, 64), GT_OreDictUnificator.get(OrePrefixes.frameGt, Materials.CosmicNeutronium, 64), ItemList.Field_Generator_UEV.get(64), CustomItemList.PikoCircuit.get(64), ItemList.Electric_Motor_UEV.get(64), ItemList.Electric_Piston_UEV.get(64), ItemList.Robot_Arm_UEV.get(64), ItemList.Sensor_UEV.get(64), StellarConstructionFrameMaterial.get(64), GT_OreDictUnificator.get(OrePrefixes.wireGt16, Materials.SuperconductorUEV, 64), GT_OreDictUnificator.get(OrePrefixes.gearGt, Materials.Infinity, 16), GT_OreDictUnificator.get(OrePrefixes.gearGt, Materials.Infinity, 16), lightPlating.getItemStack(64), eM_Power.get(64), new ItemStack(IGBlocks.SpaceElevatorCasing, 64), new ItemStack(GSBlocks.DysonSwarmBlocks, 64, 9)) .fluidInputs( new FluidStack(solderPlasma, 144 * 8192), Materials.UUMatter.getFluid(1000 * 128), Materials.SuperCoolant.getFluid(1000 * 1024), Materials.CosmicNeutronium.getMolten(144 * 1024)) .itemOutputs(DSPLauncher.get(1)) .eut(RECIPE_UIV) .duration(20 * 2400) .addTo(AssemblyLine); // eM_Ultimate_Containment_Advanced casing 13 GT_Values.RA.stdBuilder() .itemInputs( eM_Ultimate_Containment.get(64), GT_OreDictUnificator.get(OrePrefixes.plateDense, MaterialsUEVplus.Eternity, 64), GT_OreDictUnificator.get(OrePrefixes.foil, MaterialsUEVplus.SpaceTime, 64), GT_OreDictUnificator.get(OrePrefixes.foil, MaterialsUEVplus.SpaceTime, 64), ItemList.Tesseract.get(16), ItemList.EnergisedTesseract.get(16), ItemList.Field_Generator_UMV.get(8), copyAmount(64, Particle.getBaseParticle(Particle.HIGGS_BOSON))) .fluidInputs(MyMaterial.metastableOganesson.getMolten(144 * 256)) .itemOutputs(eM_Ultimate_Containment_Advanced.get(8)) .noOptimize() .eut(RECIPE_UXV) .duration(20 * 300) .addTo(Assembler); // eM_Ultimate_Containment casing 12 GT_Values.RA.stdBuilder() .itemInputs( eM_Containment.get(1), StellarConstructionFrameMaterial.get(1), GT_OreDictUnificator.get(OrePrefixes.plateDense, MaterialsUEVplus.TranscendentMetal, 16), HYPOGEN.getFoil(64), CELESTIAL_TUNGSTEN.getScrew(64), CELESTIAL_TUNGSTEN.getRing(64), ItemList.Field_Generator_UIV.get(1)) .fluidInputs(MyMaterial.preciousMetalAlloy.getMolten(144 * 64)) .itemOutputs(eM_Ultimate_Containment.get(1)) .noOptimize() .eut(RECIPE_UMV) .duration(20 * 300) .addTo(Assembler); // ArtificialStar GT_Values.RA.stdBuilder() .metadata(RESEARCH_ITEM, AnnihilationConstrainer.get(1)) .metadata(RESEARCH_TIME, 24 * HOURS) .itemInputs( StellarConstructionFrameMaterial.get(64), eM_Spacetime.get(64), eM_Ultimate_Containment_Field.get(64), ItemList.Casing_Dim_Bridge.get(64), eM_Ultimate_Containment_Advanced.get(64), eM_Coil.get(64), eM_Hollow.get(64), ItemList.Electric_Pump_UMV.get(64), AnnihilationConstrainer.get(64), ItemList.Field_Generator_UMV.get(64), CustomItemList.QuantumCircuit.get(64), CustomItemList.PikoCircuit.get(64), CustomItemList.HighEnergyFlowCircuit.get(64), ItemList.Tesseract.get(64), ItemList.EnergisedTesseract.get(64), GT_OreDictUnificator.get(OrePrefixes.plateDense, MaterialsUEVplus.SpaceTime, 64)) .fluidInputs( new FluidStack(solderPlasma, 144 * 8192), MaterialsUEVplus.TranscendentMetal.getMolten(144 * 8192), MaterialsUEVplus.SpaceTime.getMolten(144 * 8192), Materials.SuperconductorUMVBase.getMolten(144 * 8192)) .itemOutputs(ArtificialStar.get(1)) .eut(RECIPE_UXV) .duration(20 * 2400) .addTo(AssemblyLine); // launcher GT_Values.RA.stdBuilder() .itemInputs(SolarSail.get(1)) .itemOutputs(SolarSail.get(1)) .eut(EUTOfLaunchingSolarSail) .duration(ticksOfLaunchingSolarSail) .addTo(DSPLauncherRecipe); GT_Values.RA.stdBuilder() .itemInputs(SmallLaunchVehicle.get(1)) .itemOutputs( SmallLaunchVehicle.get(1) .setStackDisplayName( texter("99%% Return an Empty Small Launch Vehicle.", "NEI.EmptySmallLaunchVehicleRecipe.0")))
.eut(EUTOfLaunchingNode)
2
2023-10-16 09:57:15+00:00
12k
wyjsonGo/GoRouter
module_common/src/main/java/com/wyjson/router/helper/module_main/group_main/MainSplashActivityGoRouter.java
[ { "identifier": "GoRouter", "path": "GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java", "snippet": "public final class GoRouter {\n\n private final Handler mHandler = new Handler(Looper.getMainLooper());\n private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInsta...
import com.wyjson.router.GoRouter; import com.wyjson.router.model.Card; import com.wyjson.router.model.CardMeta; import java.lang.String;
8,932
package com.wyjson.router.helper.module_main.group_main; /** * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY GOROUTER. * 欢迎页 * {@link com.wyjson.module_main.activity.SplashActivity} */ public class MainSplashActivityGoRouter { public static String getPath() { return "/main/splash/activity"; } public static CardMeta getCardMeta() { return GoRouter.getInstance().build(getPath()).getCardMeta(); } public static <T> void postEvent(T value) { GoRouter.getInstance().postEvent(getPath(), value); }
package com.wyjson.router.helper.module_main.group_main; /** * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY GOROUTER. * 欢迎页 * {@link com.wyjson.module_main.activity.SplashActivity} */ public class MainSplashActivityGoRouter { public static String getPath() { return "/main/splash/activity"; } public static CardMeta getCardMeta() { return GoRouter.getInstance().build(getPath()).getCardMeta(); } public static <T> void postEvent(T value) { GoRouter.getInstance().postEvent(getPath(), value); }
public static Card build() {
1
2023-10-18 13:52:07+00:00
12k
trpc-group/trpc-java
trpc-core/src/main/java/com/tencent/trpc/core/rpc/def/DefMethodInfoRegister.java
[ { "identifier": "ProviderConfig", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/config/ProviderConfig.java", "snippet": "public class ProviderConfig<T> implements Cloneable {\n\n protected static final Logger logger = LoggerFactory.getLogger(ProviderConfig.class);\n /**\n * Bus...
import com.google.common.collect.Maps; import com.tencent.trpc.core.common.config.ProviderConfig; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.rpc.ProviderInvoker; import com.tencent.trpc.core.rpc.common.MethodRouterKey; import com.tencent.trpc.core.rpc.common.RpcMethodInfo; import com.tencent.trpc.core.rpc.common.RpcMethodInfoAndInvoker; import com.tencent.trpc.core.utils.PreconditionUtils; import com.tencent.trpc.core.utils.RpcUtils; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentMap;
8,603
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.rpc.def; /** * Default method route management class. */ public class DefMethodInfoRegister { private static final Logger logger = LoggerFactory.getLogger(DefMethodInfoRegister.class); /** * Service registration path, temporarily not supporting ANT style key: full path (base_path + func), value: func */ private static final Map<String, String> SERVICE_PATH_AND_FUNC = Maps.newConcurrentMap(); /** * Default service path. */ private static final String DEFAULT_SERVICE_PATH = "/trpc"; private ConcurrentMap<String, RpcMethodInfoAndInvoker> rpcMethodRouterMap = Maps.newConcurrentMap(); private ConcurrentMap<String, RpcMethodInfoAndInvoker> defaultRpcMethodRouterMap = Maps.newConcurrentMap(); /** * Register http mapping. * * @param providerInvoker provider */ public void register(ProviderInvoker<?> providerInvoker) { ProviderConfig<?> providerConfig = providerInvoker.getConfig(); Class<?> serviceInterface = providerConfig.getServiceInterface(); String serviceInterfaceName = serviceInterface.getName();
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.core.rpc.def; /** * Default method route management class. */ public class DefMethodInfoRegister { private static final Logger logger = LoggerFactory.getLogger(DefMethodInfoRegister.class); /** * Service registration path, temporarily not supporting ANT style key: full path (base_path + func), value: func */ private static final Map<String, String> SERVICE_PATH_AND_FUNC = Maps.newConcurrentMap(); /** * Default service path. */ private static final String DEFAULT_SERVICE_PATH = "/trpc"; private ConcurrentMap<String, RpcMethodInfoAndInvoker> rpcMethodRouterMap = Maps.newConcurrentMap(); private ConcurrentMap<String, RpcMethodInfoAndInvoker> defaultRpcMethodRouterMap = Maps.newConcurrentMap(); /** * Register http mapping. * * @param providerInvoker provider */ public void register(ProviderInvoker<?> providerInvoker) { ProviderConfig<?> providerConfig = providerInvoker.getConfig(); Class<?> serviceInterface = providerConfig.getServiceInterface(); String serviceInterfaceName = serviceInterface.getName();
String rpcServiceName = RpcUtils.parseRpcServiceName(serviceInterface, null);
8
2023-10-19 10:54:11+00:00
12k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/DialogCommentChecker.java
[ { "identifier": "Comment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/Comment.java", "snippet": "public class Comment {\r\n public String commentText;\r\n public String commentId;\r\n\r\n public Comment() {\r\n }\r\n\r\n\r\n public Comm...
import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.util.Base64; import android.view.View; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import java.util.Date; import java.util.Locale; import icu.freedomintrovert.YTSendCommAntiFraud.comment.Comment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoCommentSection; import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB; import icu.freedomintrovert.YTSendCommAntiFraud.grpcApi.nestedIntoBase64.SortBy; import icu.freedomintrovert.YTSendCommAntiFraud.rxObservables.FindCommentObservableOnSubscribe; import icu.freedomintrovert.YTSendCommAntiFraud.utils.OkHttpUtils; import icu.freedomintrovert.YTSendCommAntiFraud.utils.ProtobufUtils; import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressBarDialog; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.annotations.NonNull; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.observers.DisposableObserver; import io.reactivex.rxjava3.schedulers.Schedulers;
9,587
package icu.freedomintrovert.YTSendCommAntiFraud; public class DialogCommentChecker { Context context; StatisticsDB statisticsDB; Config config; CompositeDisposable compositeDisposable = new CompositeDisposable(); public DialogCommentChecker(Context context, StatisticsDB statisticsDB, Config config) { this.context = context; this.statisticsDB = statisticsDB; this.config = config; } public void check(Comment comment, String videoId, int commentSectionType, byte[] context1, Bundle headers, boolean needToWait, OnExitListener onExitListener, Date sendDate){
package icu.freedomintrovert.YTSendCommAntiFraud; public class DialogCommentChecker { Context context; StatisticsDB statisticsDB; Config config; CompositeDisposable compositeDisposable = new CompositeDisposable(); public DialogCommentChecker(Context context, StatisticsDB statisticsDB, Config config) { this.context = context; this.statisticsDB = statisticsDB; this.config = config; } public void check(Comment comment, String videoId, int commentSectionType, byte[] context1, Bundle headers, boolean needToWait, OnExitListener onExitListener, Date sendDate){
VideoCommentSection videoCommentSection = new VideoCommentSection(OkHttpUtils.getOkHttpClient(),
3
2023-10-15 01:18:28+00:00
12k
New-Barams/This-Year-Ajaja-BE
src/test/java/com/newbarams/ajaja/common/support/WebMvcTestSupport.java
[ { "identifier": "MockController", "path": "src/main/java/com/newbarams/ajaja/global/mock/MockController.java", "snippet": "@Tag(name = \"mock\", description = \"가짜 API\")\n@RestController\n@RequestMapping(\"/mock\")\n@RequiredArgsConstructor\npublic class MockController {\n\tprivate static final String ...
import static org.springframework.context.annotation.ComponentScan.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.FilterType; import org.springframework.context.annotation.Import; import org.springframework.test.web.servlet.MockMvc; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.databind.ObjectMapper; import com.newbarams.ajaja.common.annotation.ApiTest; import com.newbarams.ajaja.global.mock.MockController; import com.newbarams.ajaja.global.security.jwt.util.JwtParser; import com.newbarams.ajaja.module.ajaja.application.SwitchAjajaService; import com.newbarams.ajaja.module.auth.application.AuthMockBeans; import com.newbarams.ajaja.module.feedback.application.LoadFeedbackInfoService; import com.newbarams.ajaja.module.feedback.application.LoadTotalAchieveService; import com.newbarams.ajaja.module.feedback.application.UpdateFeedbackService; import com.newbarams.ajaja.module.plan.application.CreatePlanService; import com.newbarams.ajaja.module.plan.application.DeletePlanService; import com.newbarams.ajaja.module.plan.application.LoadPlanInfoService; import com.newbarams.ajaja.module.plan.application.LoadPlanService; import com.newbarams.ajaja.module.plan.application.UpdatePlanService; import com.newbarams.ajaja.module.plan.application.UpdateRemindInfoService; import com.newbarams.ajaja.module.remind.application.LoadRemindInfoService; import com.newbarams.ajaja.module.user.application.UserMockBeans; import com.newbarams.ajaja.module.user.application.port.out.GetMyPagePort;
9,100
package com.newbarams.ajaja.common.support; /** * Supports Cached Context On WebMvcTest with Monkey <br> * Scan All Controllers By Annotation and Manage MockBeans <br> * When Authentication is required USE @ApiTest * @see ApiTest * @author hejow */ @WebMvcTest( includeFilters = @Filter(type = FilterType.ANNOTATION, classes = RestController.class), excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MockController.class) ) @Import({UserMockBeans.class, AuthMockBeans.class}) public abstract class WebMvcTestSupport extends MonkeySupport { protected static final String USER_END_POINT = "/users"; protected static final String PLAN_END_POINT = "/plans"; protected static final String FEEDBACK_END_POINT = "/feedbacks"; @Autowired protected MockMvc mockMvc; @Autowired protected ObjectMapper objectMapper; // JWT @MockBean protected JwtParser jwtParser; // todo: delete after authentication aop applied // User @MockBean protected GetMyPagePort getMyPagePort; // Plan @MockBean protected CreatePlanService createPlanService; @MockBean protected LoadPlanService getPlanService; @MockBean protected DeletePlanService deletePlanService; @MockBean protected UpdatePlanService updatePlanService; @MockBean protected LoadPlanInfoService loadPlanInfoService; @MockBean protected UpdateRemindInfoService updateRemindInfoService; @MockBean protected SwitchAjajaService switchAjajaService; // Feedback @MockBean protected UpdateFeedbackService updateFeedbackService; @MockBean
package com.newbarams.ajaja.common.support; /** * Supports Cached Context On WebMvcTest with Monkey <br> * Scan All Controllers By Annotation and Manage MockBeans <br> * When Authentication is required USE @ApiTest * @see ApiTest * @author hejow */ @WebMvcTest( includeFilters = @Filter(type = FilterType.ANNOTATION, classes = RestController.class), excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = MockController.class) ) @Import({UserMockBeans.class, AuthMockBeans.class}) public abstract class WebMvcTestSupport extends MonkeySupport { protected static final String USER_END_POINT = "/users"; protected static final String PLAN_END_POINT = "/plans"; protected static final String FEEDBACK_END_POINT = "/feedbacks"; @Autowired protected MockMvc mockMvc; @Autowired protected ObjectMapper objectMapper; // JWT @MockBean protected JwtParser jwtParser; // todo: delete after authentication aop applied // User @MockBean protected GetMyPagePort getMyPagePort; // Plan @MockBean protected CreatePlanService createPlanService; @MockBean protected LoadPlanService getPlanService; @MockBean protected DeletePlanService deletePlanService; @MockBean protected UpdatePlanService updatePlanService; @MockBean protected LoadPlanInfoService loadPlanInfoService; @MockBean protected UpdateRemindInfoService updateRemindInfoService; @MockBean protected SwitchAjajaService switchAjajaService; // Feedback @MockBean protected UpdateFeedbackService updateFeedbackService; @MockBean
protected LoadTotalAchieveService loadTotalAchieveService;
5
2023-10-23 07:24:17+00:00
12k
eclipse-jgit/jgit
org.eclipse.jgit.lfs.server/src/org/eclipse/jgit/lfs/server/fs/FileLfsRepository.java
[ { "identifier": "HDR_AUTHORIZATION", "path": "org.eclipse.jgit/src/org/eclipse/jgit/util/HttpSupport.java", "snippet": "public static final String HDR_AUTHORIZATION = \"Authorization\"; //$NON-NLS-1$" }, { "identifier": "AtomicObjectOutputStream", "path": "org.eclipse.jgit.lfs/src/org/eclips...
import static org.eclipse.jgit.util.HttpSupport.HDR_AUTHORIZATION; import java.io.IOException; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Collections; import org.eclipse.jgit.annotations.Nullable; import org.eclipse.jgit.lfs.internal.AtomicObjectOutputStream; import org.eclipse.jgit.lfs.lib.AnyLongObjectId; import org.eclipse.jgit.lfs.lib.Constants; import org.eclipse.jgit.lfs.server.LargeFileRepository; import org.eclipse.jgit.lfs.server.Response; import org.eclipse.jgit.lfs.server.Response.Action;
7,401
/* * Copyright (C) 2015, Matthias Sohn <matthias.sohn@sap.com> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.lfs.server.fs; /** * Repository storing large objects in the file system * * @since 4.3 */ public class FileLfsRepository implements LargeFileRepository { private String url; private final Path dir; /** * <p> * Constructor for FileLfsRepository. * </p> * * @param url * external URL of this repository * @param dir * storage directory * @throws java.io.IOException * if an IO error occurred */ public FileLfsRepository(String url, Path dir) throws IOException { this.url = url; this.dir = dir; Files.createDirectories(dir); } @Override
/* * Copyright (C) 2015, Matthias Sohn <matthias.sohn@sap.com> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.lfs.server.fs; /** * Repository storing large objects in the file system * * @since 4.3 */ public class FileLfsRepository implements LargeFileRepository { private String url; private final Path dir; /** * <p> * Constructor for FileLfsRepository. * </p> * * @param url * external URL of this repository * @param dir * storage directory * @throws java.io.IOException * if an IO error occurred */ public FileLfsRepository(String url, Path dir) throws IOException { this.url = url; this.dir = dir; Files.createDirectories(dir); } @Override
public Response.Action getDownloadAction(AnyLongObjectId id) {
2
2023-10-20 15:09:17+00:00
12k
starfish-studios/Naturalist
fabric/src/main/java/com/starfish_studios/naturalist/common/item/fabric/CaughtMobItem.java
[ { "identifier": "Butterfly", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Butterfly.java", "snippet": "public class Butterfly extends Animal implements IAnimatable, FlyingAnimal, Catchable {\n private static final Logger LOGGER = LogUtils.getLogger();\n private final...
import com.starfish_studios.naturalist.common.entity.Butterfly; import com.starfish_studios.naturalist.common.entity.Moth; import com.starfish_studios.naturalist.common.entity.core.Catchable; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; 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.EntityType; import net.minecraft.world.entity.MobSpawnType; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.level.ClipContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.material.Fluid; import net.minecraft.world.phys.BlockHitResult; import net.minecraft.world.phys.HitResult; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List;
10,408
package com.starfish_studios.naturalist.common.item.fabric; public class CaughtMobItem extends MobBucketItem { private final EntityType<?> type; public CaughtMobItem(EntityType<?> entitySupplier, Fluid fluid, SoundEvent emptyingSound, Properties settings) { super(entitySupplier, fluid, emptyingSound, settings); this.type = entitySupplier; } @Override public void appendHoverText(ItemStack stack, Level level, List<Component> tooltip, TooltipFlag flagIn) { if (this.type == NaturalistEntityTypes.BUTTERFLY.get()) { CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null && compoundnbt.contains("Variant", 3)) { Butterfly.Variant variant = Butterfly.Variant.getTypeById(compoundnbt.getInt("Variant")); tooltip.add((Component.translatable(String.format("tooltip.naturalist.%s", variant.toString().toLowerCase())).withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY))); } } else if (this.type == NaturalistEntityTypes.MOTH.get()) { CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null && compoundnbt.contains("Variant", 3)) {
package com.starfish_studios.naturalist.common.item.fabric; public class CaughtMobItem extends MobBucketItem { private final EntityType<?> type; public CaughtMobItem(EntityType<?> entitySupplier, Fluid fluid, SoundEvent emptyingSound, Properties settings) { super(entitySupplier, fluid, emptyingSound, settings); this.type = entitySupplier; } @Override public void appendHoverText(ItemStack stack, Level level, List<Component> tooltip, TooltipFlag flagIn) { if (this.type == NaturalistEntityTypes.BUTTERFLY.get()) { CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null && compoundnbt.contains("Variant", 3)) { Butterfly.Variant variant = Butterfly.Variant.getTypeById(compoundnbt.getInt("Variant")); tooltip.add((Component.translatable(String.format("tooltip.naturalist.%s", variant.toString().toLowerCase())).withStyle(ChatFormatting.ITALIC, ChatFormatting.GRAY))); } } else if (this.type == NaturalistEntityTypes.MOTH.get()) { CompoundTag compoundnbt = stack.getTag(); if (compoundnbt != null && compoundnbt.contains("Variant", 3)) {
Moth.Variant variant = Moth.Variant.getTypeById(compoundnbt.getInt("Variant"));
1
2023-10-16 21:54:32+00:00
12k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/AbstractDbDc.java
[ { "identifier": "AbstractDc", "path": "internal/otel-dc/src/main/java/com/instana/dc/AbstractDc.java", "snippet": "public abstract class AbstractDc implements IDc {\n private final Map<String, Meter> meters = new ConcurrentHashMap<>();\n private final Map<String, RawMetric> rawMetricsMap;\n\n\n ...
import com.instana.dc.AbstractDc; import com.instana.dc.DcUtil; import com.instana.dc.IDc; import com.instana.dc.resources.ContainerResource; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.ResourceAttributes; import io.opentelemetry.semconv.SemanticAttributes; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import static com.instana.dc.DcUtil.*; import static com.instana.dc.rdb.DbDcUtil.*; import static io.opentelemetry.api.common.AttributeKey.stringKey;
8,586
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb; public abstract class AbstractDbDc extends AbstractDc implements IDc { private static final Logger logger = Logger.getLogger(AbstractDbDc.class.getName()); private final String dbSystem; private final String dbDriver; private String dbAddress; private long dbPort; private String dbConnUrl; private String dbUserName; private String dbPassword; private String dbName; private String dbVersion; private String dbEntityType; private String dbTenantId; private String dbTenantName; private final String otelBackendUrl; private final boolean otelUsingHttp; private final int pollInterval; private final int callbackInterval; private final String serviceName; private String serviceInstanceId; private String dbEntityParentId; private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); public AbstractDbDc(Map<String, String> properties, String dbSystem, String dbDriver) { super(new DbRawMetricRegistry().getMap()); this.dbSystem = dbSystem; this.dbDriver = dbDriver; String pollInt = properties.get(POLLING_INTERVAL); pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt); String callbackInt = properties.get(CALLBACK_INTERVAL); callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt); otelBackendUrl = properties.get(OTEL_BACKEND_URL); otelUsingHttp = "true".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP)); serviceName = properties.get(OTEL_SERVICE_NAME); serviceInstanceId = properties.get(OTEL_SERVICE_INSTANCE_ID); dbEntityParentId = properties.get(DB_ENTITY_PARENT_ID); dbAddress = properties.get(DB_ADDRESS); dbPort = Long.parseLong(properties.get(DB_PORT)); dbConnUrl = properties.get(DB_CONN_URL); dbUserName = properties.get(DB_USERNAME); dbPassword = properties.get(DB_PASSWORD); dbEntityType = properties.get(DB_ENTITY_TYPE); if (dbEntityType == null) { dbEntityType = DEFAULT_DB_ENTITY_TYPE; } dbEntityType = dbEntityType.toUpperCase(); dbTenantId = properties.get(DB_TENANT_ID); dbTenantName = properties.get(DB_TENANT_NAME); dbName = properties.get(DB_NAME); dbVersion = properties.get(DB_VERSION); } @Override public Resource getResourceAttributes() { Resource resource = Resource.getDefault() .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, serviceName, SemanticAttributes.DB_SYSTEM, dbSystem, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_ADDRESS, dbAddress, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_PORT, dbPort, SemanticAttributes.DB_NAME, dbName, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_VERSION, dbVersion ))) .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_INSTANCE_ID, serviceInstanceId, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_ENTITY_TYPE, dbEntityType, stringKey(DcUtil.INSTANA_PLUGIN), com.instana.agent.sensorsdk.semconv.ResourceAttributes.DATABASE ))); try { resource = resource.merge( Resource.create(Attributes.of(ResourceAttributes.HOST_NAME, InetAddress.getLocalHost().getHostName())) ); } catch (UnknownHostException e) { // Ignore } String tenantName = this.getDbTenantName(); if (tenantName != null) { resource = resource.merge( Resource.create(Attributes.of(stringKey("tenant.name"), tenantName)) ); } String entityParentId = this.getDbEntityParentId(); if (entityParentId != null) { resource = resource.merge( Resource.create(Attributes.of(com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_ENTITY_PARENT_ID, entityParentId)) ); } long pid = DcUtil.getPid(); if (pid >= 0) { resource = resource.merge( Resource.create(Attributes.of(ResourceAttributes.PROCESS_PID, pid)) ); }
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb; public abstract class AbstractDbDc extends AbstractDc implements IDc { private static final Logger logger = Logger.getLogger(AbstractDbDc.class.getName()); private final String dbSystem; private final String dbDriver; private String dbAddress; private long dbPort; private String dbConnUrl; private String dbUserName; private String dbPassword; private String dbName; private String dbVersion; private String dbEntityType; private String dbTenantId; private String dbTenantName; private final String otelBackendUrl; private final boolean otelUsingHttp; private final int pollInterval; private final int callbackInterval; private final String serviceName; private String serviceInstanceId; private String dbEntityParentId; private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); public AbstractDbDc(Map<String, String> properties, String dbSystem, String dbDriver) { super(new DbRawMetricRegistry().getMap()); this.dbSystem = dbSystem; this.dbDriver = dbDriver; String pollInt = properties.get(POLLING_INTERVAL); pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt); String callbackInt = properties.get(CALLBACK_INTERVAL); callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt); otelBackendUrl = properties.get(OTEL_BACKEND_URL); otelUsingHttp = "true".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP)); serviceName = properties.get(OTEL_SERVICE_NAME); serviceInstanceId = properties.get(OTEL_SERVICE_INSTANCE_ID); dbEntityParentId = properties.get(DB_ENTITY_PARENT_ID); dbAddress = properties.get(DB_ADDRESS); dbPort = Long.parseLong(properties.get(DB_PORT)); dbConnUrl = properties.get(DB_CONN_URL); dbUserName = properties.get(DB_USERNAME); dbPassword = properties.get(DB_PASSWORD); dbEntityType = properties.get(DB_ENTITY_TYPE); if (dbEntityType == null) { dbEntityType = DEFAULT_DB_ENTITY_TYPE; } dbEntityType = dbEntityType.toUpperCase(); dbTenantId = properties.get(DB_TENANT_ID); dbTenantName = properties.get(DB_TENANT_NAME); dbName = properties.get(DB_NAME); dbVersion = properties.get(DB_VERSION); } @Override public Resource getResourceAttributes() { Resource resource = Resource.getDefault() .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, serviceName, SemanticAttributes.DB_SYSTEM, dbSystem, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_ADDRESS, dbAddress, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_PORT, dbPort, SemanticAttributes.DB_NAME, dbName, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_VERSION, dbVersion ))) .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_INSTANCE_ID, serviceInstanceId, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_ENTITY_TYPE, dbEntityType, stringKey(DcUtil.INSTANA_PLUGIN), com.instana.agent.sensorsdk.semconv.ResourceAttributes.DATABASE ))); try { resource = resource.merge( Resource.create(Attributes.of(ResourceAttributes.HOST_NAME, InetAddress.getLocalHost().getHostName())) ); } catch (UnknownHostException e) { // Ignore } String tenantName = this.getDbTenantName(); if (tenantName != null) { resource = resource.merge( Resource.create(Attributes.of(stringKey("tenant.name"), tenantName)) ); } String entityParentId = this.getDbEntityParentId(); if (entityParentId != null) { resource = resource.merge( Resource.create(Attributes.of(com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_ENTITY_PARENT_ID, entityParentId)) ); } long pid = DcUtil.getPid(); if (pid >= 0) { resource = resource.merge( Resource.create(Attributes.of(ResourceAttributes.PROCESS_PID, pid)) ); }
resource = resource.merge(ContainerResource.get());
3
2023-10-23 01:16:38+00:00
12k
A1anSong/jd_unidbg
unidbg-ios/src/main/java/com/github/unidbg/ios/file/JarEntryFileIO.java
[ { "identifier": "Emulator", "path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java", "snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageA...
import com.github.unidbg.Emulator; import com.github.unidbg.arm.backend.Backend; import com.github.unidbg.file.ios.BaseDarwinFileIO; import com.github.unidbg.file.ios.StatStructure; import com.github.unidbg.ios.struct.kernel.StatFS; import com.github.unidbg.unix.IO; import com.sun.jna.Pointer; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.jar.JarEntry; import java.util.jar.JarFile;
7,220
package com.github.unidbg.ios.file; public class JarEntryFileIO extends BaseDarwinFileIO { private final String path; private final File jarFile; private final JarEntry entry; public JarEntryFileIO(int oflags, String path, File jarFile, JarEntry entry) { super(oflags); this.path = path; this.jarFile = jarFile; this.entry = entry; } private int pos; private JarFile openedJarFile; @Override public void close() { pos = 0; if (openedJarFile != null) { com.alibaba.fastjson.util.IOUtils.close(openedJarFile); openedJarFile = null; } } @Override public int read(Backend backend, Pointer buffer, int count) { try { if (pos >= entry.getSize()) { return 0; } if (openedJarFile == null) { openedJarFile = new JarFile(this.jarFile); } int remain = (int) entry.getSize() - pos; if (count > remain) { count = remain; } try (InputStream inputStream = openedJarFile.getInputStream(entry)) { if (inputStream.skip(pos) != pos) { throw new IllegalStateException(); } buffer.write(0, IOUtils.toByteArray(inputStream, count), 0, count); } pos += count; return count; } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int write(byte[] data) { throw new UnsupportedOperationException(); } @Override public int lseek(int offset, int whence) { switch (whence) { case SEEK_SET: pos = offset; return pos; case SEEK_CUR: pos += offset; return pos; case SEEK_END: pos = (int) entry.getSize() + offset; return pos; } return super.lseek(offset, whence); } @Override protected byte[] getMmapData(long addr, int offset, int length) { try (JarFile jarFile = new JarFile(this.jarFile); InputStream inputStream = jarFile.getInputStream(entry)) { if (offset == 0 && length == entry.getSize()) { return IOUtils.toByteArray(inputStream); } else { if (inputStream.skip(offset) != offset) { throw new IllegalStateException(); } return IOUtils.toByteArray(inputStream, length); } } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { int blockSize = emulator.getPageAlign(); stat.st_dev = 1;
package com.github.unidbg.ios.file; public class JarEntryFileIO extends BaseDarwinFileIO { private final String path; private final File jarFile; private final JarEntry entry; public JarEntryFileIO(int oflags, String path, File jarFile, JarEntry entry) { super(oflags); this.path = path; this.jarFile = jarFile; this.entry = entry; } private int pos; private JarFile openedJarFile; @Override public void close() { pos = 0; if (openedJarFile != null) { com.alibaba.fastjson.util.IOUtils.close(openedJarFile); openedJarFile = null; } } @Override public int read(Backend backend, Pointer buffer, int count) { try { if (pos >= entry.getSize()) { return 0; } if (openedJarFile == null) { openedJarFile = new JarFile(this.jarFile); } int remain = (int) entry.getSize() - pos; if (count > remain) { count = remain; } try (InputStream inputStream = openedJarFile.getInputStream(entry)) { if (inputStream.skip(pos) != pos) { throw new IllegalStateException(); } buffer.write(0, IOUtils.toByteArray(inputStream, count), 0, count); } pos += count; return count; } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int write(byte[] data) { throw new UnsupportedOperationException(); } @Override public int lseek(int offset, int whence) { switch (whence) { case SEEK_SET: pos = offset; return pos; case SEEK_CUR: pos += offset; return pos; case SEEK_END: pos = (int) entry.getSize() + offset; return pos; } return super.lseek(offset, whence); } @Override protected byte[] getMmapData(long addr, int offset, int length) { try (JarFile jarFile = new JarFile(this.jarFile); InputStream inputStream = jarFile.getInputStream(entry)) { if (offset == 0 && length == entry.getSize()) { return IOUtils.toByteArray(inputStream); } else { if (inputStream.skip(offset) != offset) { throw new IllegalStateException(); } return IOUtils.toByteArray(inputStream, length); } } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int ioctl(Emulator<?> emulator, long request, long argp) { return 0; } @Override public int fstat(Emulator<?> emulator, StatStructure stat) { int blockSize = emulator.getPageAlign(); stat.st_dev = 1;
stat.st_mode = (short) (IO.S_IFREG | 0x777);
5
2023-10-17 06:13:28+00:00
12k
aabssmc/Skuishy
src/main/java/lol/aabss/skuishy/Skuishy.java
[ { "identifier": "CustomEvents", "path": "src/main/java/lol/aabss/skuishy/events/CustomEvents.java", "snippet": "public class CustomEvents implements Listener {\n\n @EventHandler\n public void onShieldBreak(PlayerItemCooldownEvent e) {\n if (e.getType() == Material.SHIELD) {\n if ...
import ch.njol.skript.Skript; import ch.njol.skript.SkriptAddon; import lol.aabss.skuishy.events.CustomEvents; import lol.aabss.skuishy.hooks.Metrics; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.IOException;
7,568
package lol.aabss.skuishy; public class Skuishy extends JavaPlugin{ public static Skuishy instance; private SkriptAddon addon; public static long start = System.currentTimeMillis()/50; public void onEnable() { getServer().getPluginManager().registerEvents(new CustomEvents(), this);
package lol.aabss.skuishy; public class Skuishy extends JavaPlugin{ public static Skuishy instance; private SkriptAddon addon; public static long start = System.currentTimeMillis()/50; public void onEnable() { getServer().getPluginManager().registerEvents(new CustomEvents(), this);
Metrics metrics = new Metrics(this, 20162);
1
2023-10-24 23:48:14+00:00
12k
histevehu/12306
business/src/main/java/com/steve/train/business/service/SkTokenService.java
[ { "identifier": "SkToken", "path": "business/src/main/java/com/steve/train/business/domain/SkToken.java", "snippet": "public class SkToken {\n private Long id;\n\n private Date date;\n\n private String trainCode;\n\n private Integer count;\n\n private Date createTime;\n\n private Date ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjectUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.business.domain.SkToken; import com.steve.train.business.domain.SkTokenExample; import com.steve.train.business.enums.RedisKeyTypeEnum; import com.steve.train.business.mapper.SkTokenMapper; import com.steve.train.business.mapper.custom.SkTokenMapperCust; import com.steve.train.business.req.SkTokenQueryReq; import com.steve.train.business.req.SkTokenSaveReq; import com.steve.train.business.resp.SkTokenQueryResp; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import jakarta.annotation.Resource; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit;
7,313
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-11-15 14:11:05 * @description: 秒杀令牌服务(FreeMarker生成) */ @Service public class SkTokenService { private static final Logger LOG = LoggerFactory.getLogger(SkTokenService.class); @Resource
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-11-15 14:11:05 * @description: 秒杀令牌服务(FreeMarker生成) */ @Service public class SkTokenService { private static final Logger LOG = LoggerFactory.getLogger(SkTokenService.class); @Resource
private SkTokenMapper skTokenMapper;
3
2023-10-23 01:20:56+00:00
12k
team-moabam/moabam-BE
src/test/java/com/moabam/api/presentation/CouponControllerTest.java
[ { "identifier": "CouponMapper", "path": "src/main/java/com/moabam/api/application/coupon/CouponMapper.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class CouponMapper {\n\n\tpublic static Coupon toEntity(Long adminId, CreateCouponRequest coupon) {\n\t\treturn Coupon.b...
import static org.hamcrest.Matchers.*; import static org.mockito.BDDMockito.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import java.time.LocalDate; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.databind.ObjectMapper; import com.moabam.api.application.coupon.CouponMapper; import com.moabam.api.domain.coupon.Coupon; import com.moabam.api.domain.coupon.CouponType; import com.moabam.api.domain.coupon.CouponWallet; import com.moabam.api.domain.coupon.repository.CouponRepository; import com.moabam.api.domain.coupon.repository.CouponWalletRepository; import com.moabam.api.domain.member.Role; import com.moabam.api.domain.member.repository.MemberRepository; import com.moabam.api.dto.coupon.CouponStatusRequest; import com.moabam.api.dto.coupon.CreateCouponRequest; import com.moabam.api.infrastructure.redis.ValueRedisRepository; import com.moabam.api.infrastructure.redis.ZSetRedisRepository; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.model.ErrorMessage; import com.moabam.support.annotation.WithMember; import com.moabam.support.common.WithoutFilterSupporter; import com.moabam.support.fixture.CouponFixture; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.snippet.CouponSnippet; import com.moabam.support.snippet.CouponWalletSnippet; import com.moabam.support.snippet.ErrorSnippet;
8,682
package com.moabam.api.presentation; @Transactional @SpringBootTest @AutoConfigureMockMvc @AutoConfigureRestDocs class CouponControllerTest extends WithoutFilterSupporter { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @Autowired MemberRepository memberRepository; @Autowired CouponRepository couponRepository; @Autowired CouponWalletRepository couponWalletRepository; @SpyBean ClockHolder clockHolder; @MockBean ZSetRedisRepository zSetRedisRepository; @MockBean
package com.moabam.api.presentation; @Transactional @SpringBootTest @AutoConfigureMockMvc @AutoConfigureRestDocs class CouponControllerTest extends WithoutFilterSupporter { @Autowired MockMvc mockMvc; @Autowired ObjectMapper objectMapper; @Autowired MemberRepository memberRepository; @Autowired CouponRepository couponRepository; @Autowired CouponWalletRepository couponWalletRepository; @SpyBean ClockHolder clockHolder; @MockBean ZSetRedisRepository zSetRedisRepository; @MockBean
ValueRedisRepository valueRedisRepository;
8
2023-10-20 06:15:43+00:00
12k
liukanshan1/PrivateTrace-Core
src/main/java/Priloc/protocol/Main2.java
[ { "identifier": "Circle", "path": "src/main/java/Priloc/area/basic/Circle.java", "snippet": "public class Circle implements Serializable {\n private Point center;\n private double radius;\n public static final circleFilter DISTANCE_FILTER = new distantFilter();\n public static final circleFi...
import Priloc.area.basic.Circle; import Priloc.area.basic.EncryptedCircle; import Priloc.area.shape.Polygon; import Priloc.area.shape.Shape; import Priloc.area.shape.Triangle; import Priloc.data.EncTrajectory; import Priloc.data.TimeLocationData; import Priloc.data.Trajectory; import Priloc.geo.Location; import Priloc.utils.Constant; import Priloc.utils.Pair; import Priloc.utils.User; import org.springframework.util.StopWatch; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static Priloc.protocol.Main.getEncTrajectories;
8,639
package Priloc.protocol; public class Main2 { public static void main(String[] args) throws Exception { System.out.println(Constant.toStr()); User.pai.setDecryption(User.prikey); ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD); StopWatch stopWatch = new StopWatch(); // Part-1 范围比较 // 生成范围 stopWatch.start("创建范围"); Location l1 = new Location(39.913385, 116.415884); Location l2 = new Location(39.915744, 116.417761); Location l3 = new Location(39.91306, 116.419576); Triangle triangle = new Triangle(l1, l2, l3); // 王府井 市中心三角 l1 = new Location(40.004086, 116.393274); l2 = new Location(39.994413, 116.393884); l3 = new Location(39.994911, 116.407646); Location l4 = new Location(40.004721, 116.407036); Polygon p1 = new Polygon(l1, l2, l3, l4); // 国家体育中心鸟巢 Shape[] shapes = new Shape[2]; shapes[0] = triangle; shapes[1] = p1; stopWatch.stop(); System.out.println(stopWatch.getTotalTimeSeconds()); // 拟合 Future<Circle[]>[] futures = new Future[shapes.length]; Circle[][] temp = new Circle[shapes.length][]; stopWatch.start("拟合"); for (int i = 0; i < shapes.length; i++) { futures[i] = pool.submit(shapes[i]::fit); } for (int i = 0; i < shapes.length; i++) { temp[i] = futures[i].get(); } stopWatch.stop(); List<Circle> cs = new ArrayList<>(); for (int i = 0; i < shapes.length; i++) { System.out.println("拟合效果:" + shapes[i].checkCoverage(10000000, temp[i])); cs.addAll(Arrays.asList(temp[i])); } Circle[] circles = cs.toArray(new Circle[cs.size()]); System.out.println(stopWatch.getTotalTimeSeconds()); // 加密
package Priloc.protocol; public class Main2 { public static void main(String[] args) throws Exception { System.out.println(Constant.toStr()); User.pai.setDecryption(User.prikey); ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD); StopWatch stopWatch = new StopWatch(); // Part-1 范围比较 // 生成范围 stopWatch.start("创建范围"); Location l1 = new Location(39.913385, 116.415884); Location l2 = new Location(39.915744, 116.417761); Location l3 = new Location(39.91306, 116.419576); Triangle triangle = new Triangle(l1, l2, l3); // 王府井 市中心三角 l1 = new Location(40.004086, 116.393274); l2 = new Location(39.994413, 116.393884); l3 = new Location(39.994911, 116.407646); Location l4 = new Location(40.004721, 116.407036); Polygon p1 = new Polygon(l1, l2, l3, l4); // 国家体育中心鸟巢 Shape[] shapes = new Shape[2]; shapes[0] = triangle; shapes[1] = p1; stopWatch.stop(); System.out.println(stopWatch.getTotalTimeSeconds()); // 拟合 Future<Circle[]>[] futures = new Future[shapes.length]; Circle[][] temp = new Circle[shapes.length][]; stopWatch.start("拟合"); for (int i = 0; i < shapes.length; i++) { futures[i] = pool.submit(shapes[i]::fit); } for (int i = 0; i < shapes.length; i++) { temp[i] = futures[i].get(); } stopWatch.stop(); List<Circle> cs = new ArrayList<>(); for (int i = 0; i < shapes.length; i++) { System.out.println("拟合效果:" + shapes[i].checkCoverage(10000000, temp[i])); cs.addAll(Arrays.asList(temp[i])); } Circle[] circles = cs.toArray(new Circle[cs.size()]); System.out.println(stopWatch.getTotalTimeSeconds()); // 加密
EncryptedCircle[] encCircles = new EncryptedCircle[circles.length];
1
2023-10-22 06:28:51+00:00
12k
tuxming/xmfx
Example/src/main/java/com/xm2013/example/example/MainApplication.java
[ { "identifier": "XmFontIcon", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/icon/XmFontIcon.java", "snippet": "public class XmFontIcon extends XmIcon {\n private final static String USER_AGENT_STYLESHEET = FxKit.getResourceURL(\"/css/control.css\");\n\n private static Font iconFont = null;\...
import java.io.IOException; import com.xm2013.jfx.control.icon.XmFontIcon; import com.xm2013.jfx.ui.DefaultTheme; import com.xm2013.jfx.ui.FxWindow; import javafx.application.Application; import javafx.scene.image.Image; import javafx.stage.Stage;
7,337
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.example.example; public class MainApplication extends Application { private DefaultTheme layout = null; @Override public void start(Stage stage) throws IOException { layout = new DefaultTheme();
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.example.example; public class MainApplication extends Application { private DefaultTheme layout = null; @Override public void start(Stage stage) throws IOException { layout = new DefaultTheme();
FxWindow window = new FxWindow(1200, 900, layout);
2
2023-10-17 08:57:08+00:00
12k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/gui/controllers/RegistersController.java
[ { "identifier": "AbstractJArmEmuModule", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/AbstractJArmEmuModule.java", "snippet": "public class AbstractJArmEmuModule implements Initializable {\n\n protected final JArmEmuApplication application;\n\n public AbstractJArmEmuModule(JArmEmuApplication...
import atlantafx.base.theme.Styles; import atlantafx.base.theme.Tweaks; import fr.dwightstudio.jarmemu.gui.AbstractJArmEmuModule; import fr.dwightstudio.jarmemu.gui.JArmEmuApplication; import fr.dwightstudio.jarmemu.gui.factory.FlagTableCell; import fr.dwightstudio.jarmemu.gui.factory.ValueTableCell; import fr.dwightstudio.jarmemu.gui.view.RegisterView; import fr.dwightstudio.jarmemu.sim.obj.Register; import fr.dwightstudio.jarmemu.sim.obj.StateContainer; import javafx.collections.ObservableList; import javafx.geometry.Pos; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.TextFieldTableCell; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import org.kordamp.ikonli.javafx.FontIcon; import org.kordamp.ikonli.material2.Material2OutlinedAL; import org.kordamp.ikonli.material2.Material2OutlinedMZ; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Logger;
9,394
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * 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 fr.dwightstudio.jarmemu.gui.controllers; public class RegistersController extends AbstractJArmEmuModule { private final Logger logger = Logger.getLogger(getClass().getName()); private TableColumn<RegisterView, String> col0; private TableColumn<RegisterView, Number> col1; private TableColumn<RegisterView, Register> col2; private ObservableList<RegisterView> views; private TableView<RegisterView> registersTable;
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * 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 fr.dwightstudio.jarmemu.gui.controllers; public class RegistersController extends AbstractJArmEmuModule { private final Logger logger = Logger.getLogger(getClass().getName()); private TableColumn<RegisterView, String> col0; private TableColumn<RegisterView, Number> col1; private TableColumn<RegisterView, Register> col2; private ObservableList<RegisterView> views; private TableView<RegisterView> registersTable;
public RegistersController(JArmEmuApplication application) {
1
2023-10-17 18:22:09+00:00
12k
GTNewHorizons/FarmingForEngineers
src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java
[ { "identifier": "Compat", "path": "src/main/java/com/guigs44/farmingforengineers/compat/Compat.java", "snippet": "public class Compat {\n\n public static final String HARVESTCRAFT = \"harvestcraft\";\n public static final String MOUSETWEAKS = \"mousetweaks\";\n public static final String AGRICR...
import java.io.File; import java.util.Optional; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.common.config.Configuration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.guigs44.farmingforengineers.compat.Compat; import com.guigs44.farmingforengineers.compat.VanillaAddon; import com.guigs44.farmingforengineers.entity.EntityMerchant; import com.guigs44.farmingforengineers.network.GuiHandler; import com.guigs44.farmingforengineers.network.NetworkHandler; import com.guigs44.farmingforengineers.registry.AbstractRegistry; import com.guigs44.farmingforengineers.registry.MarketRegistry; import com.guigs44.farmingforengineers.utilities.ChatComponentBuilder; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry;
8,622
package com.guigs44.farmingforengineers; @Mod( modid = FarmingForEngineers.MOD_ID, name = "Farming for Engineers", dependencies = "after:mousetweaks[2.8,);after:forestry;after:agricraft") // @Mod.EventBusSubscriber public class FarmingForEngineers { public static final String MOD_ID = "farmingforengineers"; @Mod.Instance(MOD_ID) public static FarmingForEngineers instance; @SidedProxy( clientSide = "com.guigs44.farmingforengineers.client.ClientProxy", serverSide = "com.guigs44.farmingforengineers.CommonProxy") public static CommonProxy proxy; public static final Logger logger = LogManager.getLogger(); public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) { @Override public Item getTabIconItem() { return Item.getItemFromBlock(FarmingForEngineers.blockMarket); } }; public static File configDir; public static Block blockMarket; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { configDir = new File(event.getModConfigurationDirectory(), "FarmingForEngineers"); if (!configDir.exists() && !configDir.mkdirs()) { throw new RuntimeException("Couldn't create Farming for Engineers configuration directory"); } Configuration config = new Configuration(new File(configDir, "FarmingForEngineers.cfg")); config.load(); ModConfig.preInit(config); proxy.preInit(event); if (config.hasChanged()) { config.save(); } } @Mod.EventHandler public void init(FMLInitializationEvent event) { NetworkHandler.init();
package com.guigs44.farmingforengineers; @Mod( modid = FarmingForEngineers.MOD_ID, name = "Farming for Engineers", dependencies = "after:mousetweaks[2.8,);after:forestry;after:agricraft") // @Mod.EventBusSubscriber public class FarmingForEngineers { public static final String MOD_ID = "farmingforengineers"; @Mod.Instance(MOD_ID) public static FarmingForEngineers instance; @SidedProxy( clientSide = "com.guigs44.farmingforengineers.client.ClientProxy", serverSide = "com.guigs44.farmingforengineers.CommonProxy") public static CommonProxy proxy; public static final Logger logger = LogManager.getLogger(); public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) { @Override public Item getTabIconItem() { return Item.getItemFromBlock(FarmingForEngineers.blockMarket); } }; public static File configDir; public static Block blockMarket; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { configDir = new File(event.getModConfigurationDirectory(), "FarmingForEngineers"); if (!configDir.exists() && !configDir.mkdirs()) { throw new RuntimeException("Couldn't create Farming for Engineers configuration directory"); } Configuration config = new Configuration(new File(configDir, "FarmingForEngineers.cfg")); config.load(); ModConfig.preInit(config); proxy.preInit(event); if (config.hasChanged()) { config.save(); } } @Mod.EventHandler public void init(FMLInitializationEvent event) { NetworkHandler.init();
NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());
3
2023-10-17 00:25:50+00:00
12k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/conll/DepToPTB.java
[ { "identifier": "OptionParser", "path": "src/berkeley_parser/edu/berkeley/nlp/PCFGLA/OptionParser.java", "snippet": "public class OptionParser {\n\n\tprivate final Map<String, Option> nameToOption = new HashMap<String, Option>();\n\n\tprivate final Map<String, Field> nameToField = new HashMap<String, Fi...
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import edu.berkeley.nlp.PCFGLA.Option; import edu.berkeley.nlp.PCFGLA.OptionParser; import edu.berkeley.nlp.syntax.Tree;
7,844
/** * */ package edu.berkeley.nlp.conll; /** * @author petrov * */ public class DepToPTB { public static class Options { @Option(name = "-in", required = true, usage = "Input File for Grammar (Required)") public String inFileName; @Option(name = "-finePOStags", usage = "Use fine POS tags (Default: false=coarse") public boolean useFinePOS = false; } public static void main(String[] args) { // String[] sentence = { // "1 The _ DT DT _ 4 NMOD _ _\n", // "2 luxury _ NN NN _ 4 NMOD _ _\n", // "3 auto _ NN NN _ 4 NMOD _ _\n", // "4 maker _ NN NN _ 7 SBJ _ _\n", // "5 last _ JJ JJ _ 6 NMOD _ _\n", // "6 year _ NN NN _ 7 VMOD _ _\n", // "7 sold _ VB VBD _ 0 ROOT _ _\n", // "8 1,214 _ CD CD _ 9 NMOD _ _\n", // "9 cars _ NN NNS _ 7 OBJ _ _\n", // "10 in _ IN IN _ 7 ADV _ _\n", // "11 the _ DT DT _ 12 NMOD _ _\n", // "12 U.S. _ NN NNP _ 10 PMOD _ _\n"};
/** * */ package edu.berkeley.nlp.conll; /** * @author petrov * */ public class DepToPTB { public static class Options { @Option(name = "-in", required = true, usage = "Input File for Grammar (Required)") public String inFileName; @Option(name = "-finePOStags", usage = "Use fine POS tags (Default: false=coarse") public boolean useFinePOS = false; } public static void main(String[] args) { // String[] sentence = { // "1 The _ DT DT _ 4 NMOD _ _\n", // "2 luxury _ NN NN _ 4 NMOD _ _\n", // "3 auto _ NN NN _ 4 NMOD _ _\n", // "4 maker _ NN NN _ 7 SBJ _ _\n", // "5 last _ JJ JJ _ 6 NMOD _ _\n", // "6 year _ NN NN _ 7 VMOD _ _\n", // "7 sold _ VB VBD _ 0 ROOT _ _\n", // "8 1,214 _ CD CD _ 9 NMOD _ _\n", // "9 cars _ NN NNS _ 7 OBJ _ _\n", // "10 in _ IN IN _ 7 ADV _ _\n", // "11 the _ DT DT _ 12 NMOD _ _\n", // "12 U.S. _ NN NNP _ 10 PMOD _ _\n"};
OptionParser optParser = new OptionParser(Options.class);
0
2023-10-22 13:13:22+00:00
12k
neftalito/R-Info-Plus
arbol/sentencia/primitiva/Iniciar.java
[ { "identifier": "DeclaracionProcesos", "path": "arbol/DeclaracionProcesos.java", "snippet": "public class DeclaracionProcesos extends AST {\n public ArrayList<Proceso> procesos;\n\n public ArrayList<Proceso> getProcesos() {\n return this.procesos;\n }\n\n public void setProcesos(final...
import arbol.DeclaracionProcesos; import form.Robot; import form.EjecucionRobot; import arbol.Cuerpo; import arbol.Variable; import arbol.sentencia.Sentencia; import java.util.ArrayList; import arbol.DeclaracionVariable; import arbol.DeclaracionRobots; import arbol.Identificador; import arbol.RobotAST;
10,076
package arbol.sentencia.primitiva; public class Iniciar extends Primitiva { RobotAST r; int x; int y; Identificador Ident; DeclaracionRobots robAST; DeclaracionVariable varAST; public Iniciar(final Identificador I, final int x, final int y, final DeclaracionRobots robAST, final DeclaracionVariable varAST) throws Exception { this.varAST = varAST; this.robAST = robAST; this.Ident = I; this.x = x; this.y = y; if (varAST.EstaVariable(I.toString())) { this.r = varAST.findByName(I.toString()).getR(); System.out.println("para la variable " + I.toString() + " el robot es : " + this.r.getNombre()); return; } throw new Exception("El robot tiene que estar declarado en las variables"); } @Override public void ejecutar() throws Exception { Robot rob = null; Cuerpo cu = this.r.getCuerpo(); final DeclaracionVariable dv = this.r.getDV();
package arbol.sentencia.primitiva; public class Iniciar extends Primitiva { RobotAST r; int x; int y; Identificador Ident; DeclaracionRobots robAST; DeclaracionVariable varAST; public Iniciar(final Identificador I, final int x, final int y, final DeclaracionRobots robAST, final DeclaracionVariable varAST) throws Exception { this.varAST = varAST; this.robAST = robAST; this.Ident = I; this.x = x; this.y = y; if (varAST.EstaVariable(I.toString())) { this.r = varAST.findByName(I.toString()).getR(); System.out.println("para la variable " + I.toString() + " el robot es : " + this.r.getNombre()); return; } throw new Exception("El robot tiene que estar declarado en las variables"); } @Override public void ejecutar() throws Exception { Robot rob = null; Cuerpo cu = this.r.getCuerpo(); final DeclaracionVariable dv = this.r.getDV();
final DeclaracionProcesos procAST = this.r.getProcAST();
0
2023-10-20 15:45:37+00:00
12k
hmcts/opal-fines-service
src/main/java/uk/gov/hmcts/opal/service/DefendantAccountService.java
[ { "identifier": "AccountDetailsDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountDetailsDto.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AccountDetailsDto implements ToJsonString {\n\n //defendant_accounts.account_number\n private String account...
import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import uk.gov.hmcts.opal.dto.AccountDetailsDto; import uk.gov.hmcts.opal.dto.AccountEnquiryDto; import uk.gov.hmcts.opal.dto.AccountSearchDto; import uk.gov.hmcts.opal.dto.AccountSearchResultsDto; import uk.gov.hmcts.opal.dto.AccountSummaryDto; import uk.gov.hmcts.opal.entity.DefendantAccountEntity; import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity; import uk.gov.hmcts.opal.entity.DefendantAccountSummary; import uk.gov.hmcts.opal.entity.EnforcersEntity; import uk.gov.hmcts.opal.entity.NoteEntity; import uk.gov.hmcts.opal.entity.PartyEntity; import uk.gov.hmcts.opal.entity.PaymentTermsEntity; import uk.gov.hmcts.opal.repository.DebtorDetailRepository; import uk.gov.hmcts.opal.repository.DefendantAccountPartiesRepository; import uk.gov.hmcts.opal.repository.DefendantAccountRepository; import uk.gov.hmcts.opal.repository.EnforcersRepository; import uk.gov.hmcts.opal.repository.NoteRepository; import uk.gov.hmcts.opal.repository.PaymentTermsRepository; import uk.gov.hmcts.opal.repository.jpa.DefendantAccountSpecs; import uk.gov.hmcts.opal.entity.DefendantAccountSummary.PartyLink; import uk.gov.hmcts.opal.entity.DefendantAccountSummary.PartyDefendantAccountSummary; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static uk.gov.hmcts.opal.dto.ToJsonString.newObjectMapper;
7,355
package uk.gov.hmcts.opal.service; @Service @Transactional @Slf4j @RequiredArgsConstructor public class DefendantAccountService { private final DefendantAccountRepository defendantAccountRepository; private final DefendantAccountPartiesRepository defendantAccountPartiesRepository; private final PaymentTermsRepository paymentTermsRepository; private final DebtorDetailRepository debtorDetailRepository; private final EnforcersRepository enforcersRepository;
package uk.gov.hmcts.opal.service; @Service @Transactional @Slf4j @RequiredArgsConstructor public class DefendantAccountService { private final DefendantAccountRepository defendantAccountRepository; private final DefendantAccountPartiesRepository defendantAccountPartiesRepository; private final PaymentTermsRepository paymentTermsRepository; private final DebtorDetailRepository debtorDetailRepository; private final EnforcersRepository enforcersRepository;
private final NoteRepository noteRepository;
16
2023-10-23 14:12:11+00:00
12k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/service/SubscriberService.java
[ { "identifier": "ConflictException", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/error/ConflictException.java", "snippet": "public class ConflictException extends RuntimeException {\n\n public ConflictException(String message) {\n super(message);\n }\n\n}...
import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.moonstoneid.aerocast.aggregator.error.ConflictException; import com.moonstoneid.aerocast.aggregator.error.NotFoundException; import com.moonstoneid.aerocast.aggregator.eth.EthSubscriberAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber; import com.moonstoneid.aerocast.aggregator.model.Subscriber; import com.moonstoneid.aerocast.aggregator.model.Subscription; import com.moonstoneid.aerocast.aggregator.repo.SubscriberRepo; import com.moonstoneid.aerocast.aggregator.repo.SubscriptionRepo; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.stereotype.Service;
9,787
package com.moonstoneid.aerocast.aggregator.service; @Service @Slf4j public class SubscriberService implements EthSubscriberAdapter.EventCallback { public interface EventListener { void onSubscriptionChange(String subContractAddr); } private final SubscriberRepo subscriberRepo; private final SubscriptionRepo subscriptionRepo; private final PublisherService publisherService; private final EthSubscriberAdapter ethSubscriberAdapter; private final List<EventListener> eventListeners = new ArrayList<>(); public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo, PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) { this.subscriberRepo = subscriberRepo; this.subscriptionRepo = subscriptionRepo; this.publisherService = publisherService; this.ethSubscriberAdapter = ethSubscriberAdapter; } public void registerEventListener(EventListener listener) { eventListeners.add(listener); } public void unregisterEventListener(EventListener listener) { eventListeners.remove(listener); } // Register listeners after Spring Boot has started @org.springframework.context.event.EventListener(ApplicationReadyEvent.class) public void initEventListener() { getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener( s.getContractAddress(), s.getBlockNumber(), this)); } @Override public void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); createSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } @Override public void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); removeSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } public List<Subscriber> getSubscribers() { return subscriberRepo.findAll(); } private Optional<Subscriber> findSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); return subscriberRepo.findById(accountAddr); } public Subscriber getSubscriber(String subAccountAddr) { Optional<Subscriber> subscriber = findSubscriber(subAccountAddr); return subscriber
package com.moonstoneid.aerocast.aggregator.service; @Service @Slf4j public class SubscriberService implements EthSubscriberAdapter.EventCallback { public interface EventListener { void onSubscriptionChange(String subContractAddr); } private final SubscriberRepo subscriberRepo; private final SubscriptionRepo subscriptionRepo; private final PublisherService publisherService; private final EthSubscriberAdapter ethSubscriberAdapter; private final List<EventListener> eventListeners = new ArrayList<>(); public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo, PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) { this.subscriberRepo = subscriberRepo; this.subscriptionRepo = subscriptionRepo; this.publisherService = publisherService; this.ethSubscriberAdapter = ethSubscriberAdapter; } public void registerEventListener(EventListener listener) { eventListeners.add(listener); } public void unregisterEventListener(EventListener listener) { eventListeners.remove(listener); } // Register listeners after Spring Boot has started @org.springframework.context.event.EventListener(ApplicationReadyEvent.class) public void initEventListener() { getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener( s.getContractAddress(), s.getBlockNumber(), this)); } @Override public void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); createSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } @Override public void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); removeSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } public List<Subscriber> getSubscribers() { return subscriberRepo.findAll(); } private Optional<Subscriber> findSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); return subscriberRepo.findById(accountAddr); } public Subscriber getSubscriber(String subAccountAddr) { Optional<Subscriber> subscriber = findSubscriber(subAccountAddr); return subscriber
.orElseThrow(() -> new NotFoundException("Subscriber was not found!"));
1
2023-10-23 20:33:07+00:00
12k
UnityFoundation-io/Libre311
app/src/main/java/app/RootController.java
[ { "identifier": "DiscoveryDTO", "path": "app/src/main/java/app/dto/discovery/DiscoveryDTO.java", "snippet": "@Introspected\n@JsonRootName(\"discovery\")\npublic class DiscoveryDTO {\n\n private String changeset;\n private String contact;\n\n @JsonProperty(\"key_service\")\n private String ke...
import app.dto.discovery.DiscoveryDTO; import app.dto.download.DownloadRequestsArgumentsDTO; import app.dto.service.ServiceDTO; import app.dto.service.ServiceList; import app.dto.servicerequest.*; import app.model.service.servicedefinition.ServiceDefinition; import app.service.discovery.DiscoveryEndpointService; import app.service.jurisdiction.JurisdictionService; import app.service.service.ServiceService; import app.service.servicerequest.ServiceRequestService; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.google.common.xml.XmlEscapers; import io.micronaut.core.annotation.Nullable; import io.micronaut.data.model.Page; import io.micronaut.data.model.Pageable; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.MediaType; import io.micronaut.http.annotation.*; import io.micronaut.http.server.types.files.StreamedFile; import io.micronaut.scheduling.TaskExecutors; import io.micronaut.scheduling.annotation.ExecuteOn; import io.micronaut.security.annotation.Secured; import io.micronaut.security.rules.SecurityRule; import javax.validation.Valid; import java.net.MalformedURLException; import java.util.List; import java.util.Map;
9,008
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app; @Controller("/api") @Secured(SecurityRule.IS_ANONYMOUS) public class RootController { private final ServiceService serviceService;
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app; @Controller("/api") @Secured(SecurityRule.IS_ANONYMOUS) public class RootController { private final ServiceService serviceService;
private final ServiceRequestService serviceRequestService;
8
2023-10-18 15:37:36+00:00
12k
JonnyOnlineYT/xenza
src/minecraft/net/augustus/modules/render/ClickGUI.java
[ { "identifier": "Augustus", "path": "src/minecraft/net/augustus/Augustus.java", "snippet": "@Getter\n@Setter\npublic class Augustus {\n private static final Augustus instance = new Augustus();\n private String name = null;\n private String version = \"reborn b2\";\n private String dev = null;\n ...
import java.awt.Color; import net.augustus.Augustus; import net.augustus.clickgui.ClickGui; import net.augustus.events.EventClickGui; import net.augustus.events.EventTick; import net.augustus.material.themes.Dark; import net.augustus.modules.Categorys; import net.augustus.modules.Module; import net.augustus.settings.StringValue; import net.lenni0451.eventapi.manager.EventManager; import net.lenni0451.eventapi.reflection.EventTarget;
9,251
package net.augustus.modules.render; public class ClickGUI extends Module { public StringValue sorting = new StringValue(1, "Sorting", this, "Random", new String[]{"Random", "Length", "Alphabet"}); public StringValue mode = new StringValue(25, "Mode", this, "Default", new String[]{"Default", "Clean", "New"}); public ClickGUI() { super("ClickGui", Color.BLACK, Categorys.RENDER); } @Override public void onEnable() { Augustus.getInstance().getConverter().moduleSaver(mm.getModules()); Augustus.getInstance().getConverter().settingSaver(sm.getStgs()); if(mode.getSelected().equalsIgnoreCase("Default")) { mc.displayGuiScreen(Augustus.getInstance().getClickGui()); //} else if(mode.getSelected().equalsIgnoreCase("Clean")) { // mc.displayGuiScreen(Augustus.getInstance().getCleanClickGui()); } else if(mode.getSelected().equalsIgnoreCase("New")) {
package net.augustus.modules.render; public class ClickGUI extends Module { public StringValue sorting = new StringValue(1, "Sorting", this, "Random", new String[]{"Random", "Length", "Alphabet"}); public StringValue mode = new StringValue(25, "Mode", this, "Default", new String[]{"Default", "Clean", "New"}); public ClickGUI() { super("ClickGui", Color.BLACK, Categorys.RENDER); } @Override public void onEnable() { Augustus.getInstance().getConverter().moduleSaver(mm.getModules()); Augustus.getInstance().getConverter().settingSaver(sm.getStgs()); if(mode.getSelected().equalsIgnoreCase("Default")) { mc.displayGuiScreen(Augustus.getInstance().getClickGui()); //} else if(mode.getSelected().equalsIgnoreCase("Clean")) { // mc.displayGuiScreen(Augustus.getInstance().getCleanClickGui()); } else if(mode.getSelected().equalsIgnoreCase("New")) {
EventManager.call(new EventClickGui());
2
2023-10-15 00:21:15+00:00
12k
LeGhast/Miniaturise
src/main/java/de/leghast/miniaturise/util/Util.java
[ { "identifier": "Miniaturise", "path": "src/main/java/de/leghast/miniaturise/Miniaturise.java", "snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n ...
import de.leghast.miniaturise.Miniaturise; import de.leghast.miniaturise.instance.region.Region; import de.leghast.miniaturise.instance.settings.AdjusterSettings; import de.leghast.miniaturise.ui.Page; import de.leghast.miniaturise.ui.page.PageUtil; import net.wesjd.anvilgui.AnvilGUI; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.entity.BlockDisplay; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
7,965
package de.leghast.miniaturise.util; public class Util { public static final String PREFIX = "§7[§eMiniaturise§7] "; public static String getDimensionName(String string){ switch (string){ case "NORMAL" -> { return "minecraft:overworld"; } case "NETHER" -> { return "minecraft:the_nether"; } case "THE_END" -> { return "minecraft:the_end"; } default -> { return "Invalid dimension"; } } } public static List<BlockDisplay> getBlockDisplaysFromRegion(Player player, Region region){ List<BlockDisplay> blockDisplays = new ArrayList<>(); for(Chunk chunk : player.getWorld().getLoadedChunks()){ for(Entity entity : chunk.getEntities()){ if(entity instanceof BlockDisplay && region.contains(entity.getLocation())){ blockDisplays.add((BlockDisplay) entity); } } } return blockDisplays; }
package de.leghast.miniaturise.util; public class Util { public static final String PREFIX = "§7[§eMiniaturise§7] "; public static String getDimensionName(String string){ switch (string){ case "NORMAL" -> { return "minecraft:overworld"; } case "NETHER" -> { return "minecraft:the_nether"; } case "THE_END" -> { return "minecraft:the_end"; } default -> { return "Invalid dimension"; } } } public static List<BlockDisplay> getBlockDisplaysFromRegion(Player player, Region region){ List<BlockDisplay> blockDisplays = new ArrayList<>(); for(Chunk chunk : player.getWorld().getLoadedChunks()){ for(Entity entity : chunk.getEntities()){ if(entity instanceof BlockDisplay && region.contains(entity.getLocation())){ blockDisplays.add((BlockDisplay) entity); } } } return blockDisplays; }
public static void setCustomNumberInput(Miniaturise main, Player player, Page page){
3
2023-10-15 09:08:33+00:00
12k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/Utilities.java
[ { "identifier": "SLogger", "path": "src/com/identityworksllc/iiq/common/logging/SLogger.java", "snippet": "public class SLogger implements org.apache.commons.logging.Log {\n\t\n\t/**\n\t * Helper class to format an object for logging. The format is only derived\n\t * when the {@link #toString()} is call...
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.identityworksllc.iiq.common.logging.SLogger; import com.identityworksllc.iiq.common.query.ContextConnectionWrapper; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import sailpoint.api.MessageAccumulator; import sailpoint.api.ObjectAlreadyLockedException; import sailpoint.api.ObjectUtil; import sailpoint.api.PersistenceManager; import sailpoint.api.SailPointContext; import sailpoint.api.SailPointFactory; import sailpoint.object.*; import sailpoint.rest.BaseResource; import sailpoint.server.AbstractSailPointContext; import sailpoint.server.Environment; import sailpoint.server.SPKeyStore; import sailpoint.server.SailPointConsole; import sailpoint.tools.BrandingServiceFactory; import sailpoint.tools.Console; import sailpoint.tools.GeneralException; import sailpoint.tools.Message; import sailpoint.tools.RFC4180LineParser; import sailpoint.tools.Reflection; import sailpoint.tools.Util; import sailpoint.tools.VelocityUtil; import sailpoint.tools.xml.ConfigurationException; import sailpoint.tools.xml.XMLObjectFactory; import sailpoint.web.BaseBean; import sailpoint.web.UserContext; import sailpoint.web.util.WebUtil; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream;
9,309
* @param expectedType The expected type of the output objects * @param <S> The input type * @param <T> The output type * @return A list of the extracted values * @throws GeneralException if extraction goes wrong */ @SuppressWarnings("unchecked") public static <S, T> List<T> extractProperty(List<S> input, String property, Class<T> expectedType) throws GeneralException { List<T> output = new ArrayList<>(); for (S inputObject : Util.safeIterable(input)) { output.add((T) Utilities.getProperty(inputObject, property)); } return output; } /** * Transfors an input Filter into a MatchExpression * * @param input The Filter * @return The MatchExpression */ public static IdentitySelector.MatchExpression filterToMatchExpression(Filter input) { IdentitySelector.MatchExpression expression = new IdentitySelector.MatchExpression(); expression.addTerm(filterToMatchTerm(input)); return expression; } /** * Transfors an input Filter into a MatchTerm * * @param input The Filter * @return The MatchTerm */ public static IdentitySelector.MatchTerm filterToMatchTerm(Filter input) { IdentitySelector.MatchTerm matchTerm = null; if (input instanceof Filter.CompositeFilter) { matchTerm = new IdentitySelector.MatchTerm(); matchTerm.setContainer(true); Filter.CompositeFilter compositeFilter = (Filter.CompositeFilter) input; if (compositeFilter.getOperation().equals(Filter.BooleanOperation.AND)) { matchTerm.setAnd(true); } else if (compositeFilter.getOperation().equals(Filter.BooleanOperation.NOT)) { throw new UnsupportedOperationException("MatchExpressions do not support NOT filters"); } for (Filter child : Util.safeIterable(compositeFilter.getChildren())) { matchTerm.addChild(filterToMatchTerm(child)); } } else if (input instanceof Filter.LeafFilter) { matchTerm = new IdentitySelector.MatchTerm(); Filter.LeafFilter leafFilter = (Filter.LeafFilter) input; if (leafFilter.getOperation().equals(Filter.LogicalOperation.IN)) { matchTerm.setContainer(true); List<String> values = Util.otol(leafFilter.getValue()); if (values == null) { throw new IllegalArgumentException("For IN filters, only List<String> values are accepted"); } for (String value : values) { IdentitySelector.MatchTerm child = new IdentitySelector.MatchTerm(); child.setName(leafFilter.getProperty()); child.setValue(value); child.setType(IdentitySelector.MatchTerm.Type.Entitlement); matchTerm.addChild(child); } } else if (leafFilter.getOperation().equals(Filter.LogicalOperation.EQ)) { matchTerm.setName(leafFilter.getProperty()); matchTerm.setValue(Util.otoa(leafFilter.getValue())); matchTerm.setType(IdentitySelector.MatchTerm.Type.Entitlement); } else if (leafFilter.getOperation().equals(Filter.LogicalOperation.ISNULL)) { matchTerm.setName(leafFilter.getProperty()); matchTerm.setType(IdentitySelector.MatchTerm.Type.Entitlement); } else { throw new UnsupportedOperationException("MatchExpressions do not support " + leafFilter.getOperation() + " operations"); } } return matchTerm; } /** * Returns the first item in the list that is not null or empty. If all items are null * or empty, or the input is itself a null or empty array, an empty string will be returned. * This method will never return null. * * @param inputs The input strings * @return The first not null or empty item, or an empty string if none is found */ public static String firstNotNullOrEmpty(String... inputs) { if (inputs == null || inputs.length == 0) { return ""; } for (String in : inputs) { if (Util.isNotNullOrEmpty(in)) { return in; } } return ""; } /** * Formats the input message template using Java's MessageFormat class * and the SLogger.Formatter class. * <p> * If no parameters are provided, the message template is returned as-is. * * @param messageTemplate The message template into which parameters should be injected * @param params The parameters to be injected * @return The resulting string */ public static String format(String messageTemplate, Object... params) { if (params == null || params.length == 0) { return messageTemplate; } Object[] formattedParams = new Object[params.length]; for (int p = 0; p < params.length; p++) {
package com.identityworksllc.iiq.common; /** * Static utility methods that are useful throughout any IIQ codebase, supplementing * SailPoint's {@link Util} in many places. */ @SuppressWarnings("unused") public class Utilities { /** * Used as an indicator that the quick property lookup produced nothing. * All instances of this class are always identical via equals(). */ public static final class PropertyLookupNone { private PropertyLookupNone() { } @Override public boolean equals(Object o) { if (this == o) return true; return o instanceof PropertyLookupNone; } @Override public int hashCode() { return Objects.hash(""); } } /** * The name of the worker pool, stored in CustomGlobal by default */ public static final String IDW_WORKER_POOL = "idw.worker.pool"; /** * The key used to store the user's most recent locale on their UIPrefs, * captured by {@link #tryCaptureLocationInfo(SailPointContext, Identity)} */ public static final String MOST_RECENT_LOCALE = "mostRecentLocale"; /** * The key used to store the user's most recent timezone on their UIPrefs, * captured by {@link #tryCaptureLocationInfo(SailPointContext, Identity)} */ public static final String MOST_RECENT_TIMEZONE = "mostRecentTimezone"; /** * A magic constant for use with the {@link Utilities#getQuickProperty(Object, String)} method. * If the property is not an available 'quick property', this object will be returned. */ public static final Object NONE = new PropertyLookupNone(); private static final AtomicReference<ObjectMapper> DEFAULT_OBJECT_MAPPER = new AtomicReference<>(); /** * Indicates whether velocity has been initialized in this Utilities class */ private static final AtomicBoolean VELOCITY_INITIALIZED = new AtomicBoolean(); /** * The internal logger */ private static final Log logger = LogFactory.getLog(Utilities.class); /** * Adds the given value to a {@link Collection} at the given key in the map. * <p> * If the map does not have a {@link Collection} at the given key, a new {@link ArrayList} is added, then the value is added to that. * <p> * This method is null safe. If the map or key is null, this method has no effect. * * @param map The map to modify * @param key The map key that points to the list to add the value to * @param value The value to add to the list * @param <S> The key type * @param <T> The list element type */ @SuppressWarnings({"unchecked"}) public static <S, T extends Collection<S>> void addMapped(Map<String, T> map, String key, S value) { if (map != null && key != null) { if (!map.containsKey(key)) { map.put(key, (T) new ArrayList<>()); } map.get(key).add(value); } } /** * Adds a message banner to the current browser session which will show up at the * top of each page. This requires that a FacesContext exist in the current * session. You can't always assume this to be the case. * * If you're using the BaseCommonPluginResource class, it has a method to construct * a new FacesContext if one doesn't exist. * * @param context The IIQ context * @param message The Message to add * @throws GeneralException if anything goes wrong */ public static void addSessionMessage(SailPointContext context, Message message) throws GeneralException { FacesContext fc = FacesContext.getCurrentInstance(); if (fc != null) { try { BaseBean bean = (BaseBean) fc.getApplication().evaluateExpressionGet(fc, "#{base}", Object.class); bean.addMessageToSession(message); } catch (Exception e) { throw new GeneralException(e); } } } /** * Adds a new MatchTerm as an 'and' to an existing MatchExpression, transforming an * existing 'or' into a sub-expression if needed. * * @param input The input MatchExpression * @param newTerm The new term to 'and' with the existing expressions * @return The resulting match term */ public static IdentitySelector.MatchExpression andMatchTerm(IdentitySelector.MatchExpression input, IdentitySelector.MatchTerm newTerm) { if (input.isAnd()) { input.addTerm(newTerm); } else { IdentitySelector.MatchTerm bigOr = new IdentitySelector.MatchTerm(); for (IdentitySelector.MatchTerm existing : Util.safeIterable(input.getTerms())) { bigOr.addChild(existing); } bigOr.setContainer(true); bigOr.setAnd(false); List<IdentitySelector.MatchTerm> newChildren = new ArrayList<>(); newChildren.add(bigOr); newChildren.add(newTerm); input.setAnd(true); input.setTerms(newChildren); } return input; } /** * Boxes a primitive type into its java Object type * * @param prim The primitive type class * @return The boxed type */ /*package*/ static Class<?> box(Class<?> prim) { Objects.requireNonNull(prim, "The class to box must not be null"); if (prim.equals(Long.TYPE)) { return Long.class; } else if (prim.equals(Integer.TYPE)) { return Integer.class; } else if (prim.equals(Short.TYPE)) { return Short.class; } else if (prim.equals(Character.TYPE)) { return Character.class; } else if (prim.equals(Byte.TYPE)) { return Byte.class; } else if (prim.equals(Boolean.TYPE)) { return Boolean.class; } else if (prim.equals(Float.TYPE)) { return Float.class; } else if (prim.equals(Double.TYPE)) { return Double.class; } throw new IllegalArgumentException("Unrecognized primitive type: " + prim.getName()); } /** * Returns true if the collection contains the given value ignoring case * * @param collection The collection to check * @param value The value to check for * @return True if the collection contains the value, comparing case-insensitively */ public static boolean caseInsensitiveContains(Collection<? extends Object> collection, Object value) { if (collection == null || collection.isEmpty()) { return false; } // Most of the Set classes have efficient implementations // of contains which we should check first for case-sensitive matches. if (collection instanceof Set && collection.contains(value)) { return true; } if (value instanceof String) { String s2 = (String) value; for (Object o : collection) { if (o instanceof String) { String s1 = (String) o; if (s1.equalsIgnoreCase(s2)) { return true; } } } return false; } return collection.contains(value); } /** * Gets a global singleton value from CustomGlobal. If it doesn't exist, uses * the supplied factory (in a synchronized thread) to create it. * <p> * NOTE: This should NOT be an instance of a class defined in a plugin. If the * plugin is redeployed and its classloader refreshes, it will cause the return * value from this method to NOT match the "new" class in the new classloader, * causing ClassCastExceptions. * * @param key The key * @param factory The factory to use if the stored value is null * @param <T> the expected output type * @return the object from the global cache */ @SuppressWarnings("unchecked") public static <T> T computeGlobalSingleton(String key, Supplier<T> factory) { T output = (T) CustomGlobal.get(key); if (output == null && factory != null) { synchronized (CustomGlobal.class) { output = (T) CustomGlobal.get(key); if (output == null) { output = factory.get(); if (output != null) { CustomGlobal.put(key, output); } } } } return output; } /** * Invokes a command via the IIQ console which will run as though it was * typed at the command prompt * * @param command The command to run * @return the results of the command * @throws Exception if a failure occurs during run */ public static String consoleInvoke(String command) throws Exception { final Console console = new SailPointConsole(); final SailPointContext context = SailPointFactory.getCurrentContext(); try { SailPointFactory.setContext(null); try (StringWriter stringWriter = new StringWriter()) { try (PrintWriter writer = new PrintWriter(stringWriter)) { Method doCommand = console.getClass().getSuperclass().getDeclaredMethod("doCommand", String.class, PrintWriter.class); doCommand.setAccessible(true); doCommand.invoke(console, command, writer); } return stringWriter.getBuffer().toString(); } } finally { SailPointFactory.setContext(context); } } /** * Returns true if the Throwable message (or any of its causes) contain the given message * * @param t The throwable to check * @param cause The message to check for * @return True if the message appears anywhere */ public static boolean containsMessage(Throwable t, String cause) { if (t == null || t.toString() == null || cause == null || cause.isEmpty()) { return false; } if (t.toString().contains(cause)) { return true; } if (t.getCause() != null) { return containsMessage(t.getCause(), cause); } return false; } /** * Returns true if the given match expression references the given property anywhere. This is * mainly intended for one-off operations to find roles with particular selectors. * * @param input The filter input * @param property The property to check for * @return True if the MatchExpression references the given property anywhere in its tree */ public static boolean containsProperty(IdentitySelector.MatchExpression input, String property) { for (IdentitySelector.MatchTerm term : Util.safeIterable(input.getTerms())) { boolean contains = containsProperty(term, property); if (contains) { return true; } } return false; } /** * Returns true if the given match term references the given property anywhere. This is * mainly intended for one-off operations to find roles with particular selectors. * * @param term The MatchTerm to check * @param property The property to check for * @return True if the MatchTerm references the given property anywhere in its tree */ public static boolean containsProperty(IdentitySelector.MatchTerm term, String property) { if (term.isContainer()) { for (IdentitySelector.MatchTerm child : Util.safeIterable(term.getChildren())) { boolean contains = containsProperty(child, property); if (contains) { return true; } } } else { return Util.nullSafeCaseInsensitiveEq(term.getName(), property); } return false; } /** * Returns true if the given filter references the given property anywhere. This is * mainly intended for one-off operations to find roles with particular selectors. * <p> * If either the filter or the property is null, returns false. * * @param input The filter input * @param property The property to check for * @return True if the Filter references the given property anywhere in its tree */ public static boolean containsProperty(Filter input, String property) { if (Util.isNullOrEmpty(property)) { return false; } if (input instanceof Filter.CompositeFilter) { Filter.CompositeFilter compositeFilter = (Filter.CompositeFilter) input; for (Filter child : Util.safeIterable(compositeFilter.getChildren())) { boolean contains = containsProperty(child, property); if (contains) { return true; } } } else if (input instanceof Filter.LeafFilter) { Filter.LeafFilter leafFilter = (Filter.LeafFilter) input; return Util.nullSafeCaseInsensitiveEq(leafFilter.getProperty(), property) || Util.nullSafeCaseInsensitiveEq(leafFilter.getSubqueryProperty(), property); } return false; } /** * Converts the input object using the two date formats provided by invoking * the four-argument {@link #convertDateFormat(Object, String, String, ZoneId)}. * * The system default ZoneId will be used. * * @param something The input object, which can be a string or various date objects * @param inputDateFormat The input date format, which will be applied to a string input * @param outputDateFormat The output date format, which will be applied to the intermediate date * @return The input object formatted according to the output date format * @throws java.time.format.DateTimeParseException if there is a failure parsing the date */ public static String convertDateFormat(Object something, String inputDateFormat, String outputDateFormat) { return convertDateFormat(something, inputDateFormat, outputDateFormat, ZoneId.systemDefault()); } /** * Converts the input object using the two date formats provided. * * If the input object is a String (the most likely case), it will be * transformed into an intermediate date using the inputDateFormat. Date * type inputs (Date, LocalDate, LocalDateTime, and Long) will be * converted directly to an intermediate date. * * JDBC classes like Date and Timestamp extend java.util.Date, so that * logic would apply here. * * The intermediate date will then be formatted using the outputDateFormat * at the appropriate ZoneId. * * @param something The input object, which can be a string or various date objects * @param inputDateFormat The input date format, which will be applied to a string input * @param outputDateFormat The output date format, which will be applied to the intermediate date * @param zoneId The time zone to use for parsing and formatting * @return The input object formatted according to the output date format * @throws java.time.format.DateTimeParseException if there is a failure parsing the date */ public static String convertDateFormat(Object something, String inputDateFormat, String outputDateFormat, ZoneId zoneId) { if (something == null) { return null; } LocalDateTime intermediateDate; DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern(inputDateFormat).withZone(zoneId); DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern(outputDateFormat).withZone(zoneId); if (something instanceof String) { if (Util.isNullOrEmpty((String) something)) { return null; } String inputString = (String) something; intermediateDate = LocalDateTime.parse(inputString, inputFormat); } else if (something instanceof Date) { Date somethingDate = (Date) something; intermediateDate = somethingDate.toInstant().atZone(zoneId).toLocalDateTime(); } else if (something instanceof LocalDate) { intermediateDate = ((LocalDate) something).atStartOfDay(); } else if (something instanceof LocalDateTime) { intermediateDate = (LocalDateTime) something; } else if (something instanceof Number) { long timestamp = ((Number) something).longValue(); intermediateDate = Instant.ofEpochMilli(timestamp).atZone(zoneId).toLocalDateTime(); } else { throw new IllegalArgumentException("The input type is not valid (expected String, Date, LocalDate, LocalDateTime, or Long"); } return intermediateDate.format(outputFormat); } /** * Determines whether the test date is at least N days ago. * * @param testDate The test date * @param days The number of dates * @return True if this date is equal to or earlier than the calendar date N days ago */ public static boolean dateAtLeastDaysAgo(Date testDate, int days) { LocalDate ldt1 = testDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate ldt2 = LocalDate.now().minus(days, ChronoUnit.DAYS); return !ldt1.isAfter(ldt2); } /** * Determines whether the test date is at least N years ago. * * NOTE: This method checks using actual calendar years, rather than * calculating a number of days and comparing that. It will take into * account leap years and other date weirdness. * * @param testDate The test date * @param years The number of years * @return True if this date is equal to or earlier than the calendar date N years ago */ public static boolean dateAtLeastYearsAgo(Date testDate, int years) { LocalDate ldt1 = testDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate ldt2 = LocalDate.now().minus(years, ChronoUnit.YEARS); return !ldt1.isAfter(ldt2); } /** * Converts two Date objects to {@link LocalDate} at the system default * time zone and returns the number of days between them. * * If you pass the dates in the wrong order (first parameter is the later * date), they will be silently swapped before returning the Duration. * * @param firstTime The first time to compare * @param secondTime The second time to compare * @return The {@link Period} between the two days */ public static Period dateDifference(Date firstTime, Date secondTime) { if (firstTime == null || secondTime == null) { throw new IllegalArgumentException("Both arguments to dateDifference must be non-null"); } LocalDate ldt1 = firstTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate ldt2 = secondTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // Swap the dates if they're backwards if (ldt1.isAfter(ldt2)) { LocalDate tmp = ldt2; ldt2 = ldt1; ldt1 = tmp; } return Period.between(ldt1, ldt2); } /** * Coerces the long millisecond timestamps to Date objects, then returns the * result of {@link #dateDifference(Date, Date)}. * * @param firstTimeMillis The first time to compare * @param secondTimeMillis The second time to compare * @return The {@link Period} between the two days */ public static Period dateDifference(long firstTimeMillis, long secondTimeMillis) { return dateDifference(new Date(firstTimeMillis), new Date(secondTimeMillis)); } /** * Detaches the given object as much as possible from the database context by converting it to XML and back again. * <p> * Converting to XML requires resolving all Hibernate lazy-loaded references. * * @param context The context to use to parse the XML * @param o The object to detach * @return A reference to the object detached from any Hibernate session * @param <T> A class extending SailPointObject * @throws GeneralException if a parsing failure occurs */ public static <T extends SailPointObject> T detach(SailPointContext context, T o) throws GeneralException { @SuppressWarnings("unchecked") T retVal = (T) SailPointObject.parseXml(context, o.toXml()); context.decache(o); return retVal; } /** * Throws an exception if the string is null or empty * * @param values The strings to test */ public static void ensureAllNotNullOrEmpty(String... values) { if (values == null || Util.isAnyNullOrEmpty(values)) { throw new NullPointerException(); } } /** * Throws an exception if the string is null or empty * * @param value The string to test */ public static void ensureNotNullOrEmpty(String value) { if (Util.isNullOrEmpty(value)) { throw new NullPointerException(); } } /** * Uses reflection to evict the RuleRunner pool cache * * @throws Exception if anything goes wrong */ public static void evictRuleRunnerPool() throws Exception { RuleRunner ruleRunner = Environment.getEnvironment().getRuleRunner(); java.lang.reflect.Field _poolField = ruleRunner.getClass().getDeclaredField("_pool"); _poolField.setAccessible(true); Object poolObject = _poolField.get(ruleRunner); _poolField.setAccessible(false); java.lang.reflect.Method clearMethod = poolObject.getClass().getMethod("clear"); clearMethod.invoke(poolObject); } /** * Extracts the value of the given property from each item in the list and returns * a new list containing those property values. * <p> * If the input list is null or empty, an empty list will be returned. * <p> * This is roughly identical to * <p> * input.stream().map(item -> (T)Utilities.getProperty(item, property)).collect(Collectors.toList()) * * @param input The input list * @param property The property to extract * @param expectedType The expected type of the output objects * @param <S> The input type * @param <T> The output type * @return A list of the extracted values * @throws GeneralException if extraction goes wrong */ @SuppressWarnings("unchecked") public static <S, T> List<T> extractProperty(List<S> input, String property, Class<T> expectedType) throws GeneralException { List<T> output = new ArrayList<>(); for (S inputObject : Util.safeIterable(input)) { output.add((T) Utilities.getProperty(inputObject, property)); } return output; } /** * Transfors an input Filter into a MatchExpression * * @param input The Filter * @return The MatchExpression */ public static IdentitySelector.MatchExpression filterToMatchExpression(Filter input) { IdentitySelector.MatchExpression expression = new IdentitySelector.MatchExpression(); expression.addTerm(filterToMatchTerm(input)); return expression; } /** * Transfors an input Filter into a MatchTerm * * @param input The Filter * @return The MatchTerm */ public static IdentitySelector.MatchTerm filterToMatchTerm(Filter input) { IdentitySelector.MatchTerm matchTerm = null; if (input instanceof Filter.CompositeFilter) { matchTerm = new IdentitySelector.MatchTerm(); matchTerm.setContainer(true); Filter.CompositeFilter compositeFilter = (Filter.CompositeFilter) input; if (compositeFilter.getOperation().equals(Filter.BooleanOperation.AND)) { matchTerm.setAnd(true); } else if (compositeFilter.getOperation().equals(Filter.BooleanOperation.NOT)) { throw new UnsupportedOperationException("MatchExpressions do not support NOT filters"); } for (Filter child : Util.safeIterable(compositeFilter.getChildren())) { matchTerm.addChild(filterToMatchTerm(child)); } } else if (input instanceof Filter.LeafFilter) { matchTerm = new IdentitySelector.MatchTerm(); Filter.LeafFilter leafFilter = (Filter.LeafFilter) input; if (leafFilter.getOperation().equals(Filter.LogicalOperation.IN)) { matchTerm.setContainer(true); List<String> values = Util.otol(leafFilter.getValue()); if (values == null) { throw new IllegalArgumentException("For IN filters, only List<String> values are accepted"); } for (String value : values) { IdentitySelector.MatchTerm child = new IdentitySelector.MatchTerm(); child.setName(leafFilter.getProperty()); child.setValue(value); child.setType(IdentitySelector.MatchTerm.Type.Entitlement); matchTerm.addChild(child); } } else if (leafFilter.getOperation().equals(Filter.LogicalOperation.EQ)) { matchTerm.setName(leafFilter.getProperty()); matchTerm.setValue(Util.otoa(leafFilter.getValue())); matchTerm.setType(IdentitySelector.MatchTerm.Type.Entitlement); } else if (leafFilter.getOperation().equals(Filter.LogicalOperation.ISNULL)) { matchTerm.setName(leafFilter.getProperty()); matchTerm.setType(IdentitySelector.MatchTerm.Type.Entitlement); } else { throw new UnsupportedOperationException("MatchExpressions do not support " + leafFilter.getOperation() + " operations"); } } return matchTerm; } /** * Returns the first item in the list that is not null or empty. If all items are null * or empty, or the input is itself a null or empty array, an empty string will be returned. * This method will never return null. * * @param inputs The input strings * @return The first not null or empty item, or an empty string if none is found */ public static String firstNotNullOrEmpty(String... inputs) { if (inputs == null || inputs.length == 0) { return ""; } for (String in : inputs) { if (Util.isNotNullOrEmpty(in)) { return in; } } return ""; } /** * Formats the input message template using Java's MessageFormat class * and the SLogger.Formatter class. * <p> * If no parameters are provided, the message template is returned as-is. * * @param messageTemplate The message template into which parameters should be injected * @param params The parameters to be injected * @return The resulting string */ public static String format(String messageTemplate, Object... params) { if (params == null || params.length == 0) { return messageTemplate; } Object[] formattedParams = new Object[params.length]; for (int p = 0; p < params.length; p++) {
formattedParams[p] = new SLogger.Formatter(params[p]);
0
2023-10-20 15:20:16+00:00
12k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/config/CTseServerApp.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private...
import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.JsonAdapter; import com.google.gson.internal.bind.ObjectTypeAdapter; import com.google.gson.reflect.TypeToken; import org.apache.commons.lang3.builder.ToStringBuilder; import static org.apache.commons.lang3.builder.ToStringStyle.SHORT_PREFIX_STYLE; import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.data.FcdTraversal; import com.dcaiti.mosaic.app.fxd.messages.FcdUpdateMessage; import com.dcaiti.mosaic.app.tse.TseServerApp; import com.dcaiti.mosaic.app.tse.gson.TimeBasedProcessorTypeAdapterFactory; import com.dcaiti.mosaic.app.tse.gson.TraversalBasedProcessorTypeAdapterFactory; import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage; import com.dcaiti.mosaic.app.tse.processors.SpatioTemporalProcessor; import com.dcaiti.mosaic.app.tse.processors.ThresholdProcessor; import com.google.gson.Gson; import com.google.gson.ToNumberPolicy; import com.google.gson.TypeAdapter;
8,542
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse.config; /** * An extension of {@link CFxdReceiverApp}, holding the configuration of the {@link TseServerApp}, * which manly includes configuration parameters for the database. * Additionally, the {@link TypeAdapterFactory TypeAdapterFactories} for the relevant * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor processors} is added. */ @JsonAdapter(CTseServerApp.TypeExtendingTypeAdapterFactory.class) public class CTseServerApp extends CFxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage> { /** * Implementation to be used for the {@link FcdDataStorage}. */ public FcdDataStorage fcdDataStorage = null; /** * Set to {@code true}, if the database should be kept and not reset before every simulation. * Can be useful to be used as a threshold from a prior long simulation in a shorter new simulation on the same network. */ public boolean isPersistent = false; /** * Optional path to the database file. If no path is configured, * the database will be created in the application directory. */ public String databasePath = null; /** * Optional path to the db file. If there is none, one will be created. */ public String databaseFileName = null; /** * If {@code true}, all {@link FcdRecord FcdRecords} will be stored to the database. * Can be turned off, to safe storage and compute time, as metrics are computed from memory, not from records in the database. */ public boolean storeRawFcd = false; @Override public String toString() { return new ToStringBuilder(this, SHORT_PREFIX_STYLE) .appendSuper(super.toString()) .append("isPersistent", isPersistent) .append("databasePath", databasePath) .append("databaseFileName", databaseFileName) .toString(); } /** * This {@link TypeAdapterFactory} is used to register additional package search information * to the {@link TimeBasedProcessorTypeAdapterFactory} and {@link TraversalBasedProcessorTypeAdapterFactory}. */ static class TypeExtendingTypeAdapterFactory implements TypeAdapterFactory { static {
/* * Copyright (c) 2023 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: mosaic@fokus.fraunhofer.de */ package com.dcaiti.mosaic.app.tse.config; /** * An extension of {@link CFxdReceiverApp}, holding the configuration of the {@link TseServerApp}, * which manly includes configuration parameters for the database. * Additionally, the {@link TypeAdapterFactory TypeAdapterFactories} for the relevant * {@link com.dcaiti.mosaic.app.tse.processors.FxdProcessor processors} is added. */ @JsonAdapter(CTseServerApp.TypeExtendingTypeAdapterFactory.class) public class CTseServerApp extends CFxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage> { /** * Implementation to be used for the {@link FcdDataStorage}. */ public FcdDataStorage fcdDataStorage = null; /** * Set to {@code true}, if the database should be kept and not reset before every simulation. * Can be useful to be used as a threshold from a prior long simulation in a shorter new simulation on the same network. */ public boolean isPersistent = false; /** * Optional path to the database file. If no path is configured, * the database will be created in the application directory. */ public String databasePath = null; /** * Optional path to the db file. If there is none, one will be created. */ public String databaseFileName = null; /** * If {@code true}, all {@link FcdRecord FcdRecords} will be stored to the database. * Can be turned off, to safe storage and compute time, as metrics are computed from memory, not from records in the database. */ public boolean storeRawFcd = false; @Override public String toString() { return new ToStringBuilder(this, SHORT_PREFIX_STYLE) .appendSuper(super.toString()) .append("isPersistent", isPersistent) .append("databasePath", databasePath) .append("databaseFileName", databaseFileName) .toString(); } /** * This {@link TypeAdapterFactory} is used to register additional package search information * to the {@link TimeBasedProcessorTypeAdapterFactory} and {@link TraversalBasedProcessorTypeAdapterFactory}. */ static class TypeExtendingTypeAdapterFactory implements TypeAdapterFactory { static {
TimeBasedProcessorTypeAdapterFactory.registerAdditionalPackageForSearch(ThresholdProcessor.class.getPackage());
4
2023-10-23 16:39:40+00:00
12k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/items/PrimogemCraftItems.java
[ { "identifier": "PrimogemCraftMobEffects", "path": "src/main/java/com/primogemstudio/primogemcraft/effects/PrimogemCraftMobEffects.java", "snippet": "public class PrimogemCraftMobEffects {\n public static final AbnormalDiseaseMobEffect ABNORMAL_DISEASE = register(\"abnormal_disease\", new AbnormalDis...
import com.primogemstudio.primogemcraft.effects.PrimogemCraftMobEffects; import com.primogemstudio.primogemcraft.items.instances.*; import com.primogemstudio.primogemcraft.items.instances.curios.SocietyTicketItem; import com.primogemstudio.primogemcraft.items.instances.materials.agnidus.*; import com.primogemstudio.primogemcraft.items.instances.materials.nagadus.*; import com.primogemstudio.primogemcraft.items.instances.materials.vajrada.*; import com.primogemstudio.primogemcraft.items.instances.materials.vayuda.*; import com.primogemstudio.primogemcraft.items.instances.mora.*; import com.primogemstudio.primogemcraft.items.instances.primogem.*; import com.primogemstudio.primogemcraft.items.instances.records.*; import com.primogemstudio.primogemcraft.items.instances.templates.SmithingTemplateElement1Item; import com.primogemstudio.primogemcraft.items.instances.templates.SmithingTemplateElement2Item; import com.primogemstudio.primogemcraft.items.instances.templates.SmithingTemplateMoraItem; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.Rarity; import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID;
8,695
public static final MoraArmorItem.MoraLeggings MORA_LEGGINGS_ITEM = register("mora_leggings", new MoraArmorItem.MoraLeggings()); public static final MoraArmorItem.MoraBoots MORA_BOOTS_ITEM = register("mora_boots", new MoraArmorItem.MoraBoots()); public static final Item TEYVAT_STICK_ITEM = register("teyvat_stick", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_ITEM = register("vayuda_turquoise_gemstone", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_PIECE_ITEM = register("vayuda_turquoise_gemstone_piece", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_FRAGMENT_ITEM = register("vayuda_turquoise_gemstone_fragment", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final Item VAYUDA_TURQUOISE_GEMSTONE_SLIVER_ITEM = register("vayuda_turquoise_gemstone_sliver", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final VayudaTurquoiseGemstoneHoeItem VAYUDA_TURQUOISE_GEMSTONE_HOE_ITEM = register("vayuda_turquoise_gemstone_hoe", new VayudaTurquoiseGemstoneHoeItem()); public static final VayudaTurquoiseGemstoneAxeItem VAYUDA_TURQUOISE_GEMSTONE_AXE_ITEM = register("vayuda_turquoise_gemstone_axe", new VayudaTurquoiseGemstoneAxeItem()); public static final VayudaTurquoiseGemstonePickaxeItem VAYUDA_TURQUOISE_GEMSTONE_PICKAXE_ITEM = register("vayuda_turquoise_gemstone_pickaxe", new VayudaTurquoiseGemstonePickaxeItem()); public static final VayudaTurquoiseGemstoneShovelItem VAYUDA_TURQUOISE_GEMSTONE_SHOVEL_ITEM = register("vayuda_turquoise_gemstone_shovel", new VayudaTurquoiseGemstoneShovelItem()); public static final VayudaTurquoiseGemstoneIronItem VAYUDA_TURQUOISE_GEMSTONE_IRON_ITEM = register("vayuda_turquoise_gemstone_iron", new VayudaTurquoiseGemstoneIronItem()); public static final VayudaTurquoiseGemstoneDiamondItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_ITEM = register("vayuda_turquoise_gemstone_diamond", new VayudaTurquoiseGemstoneDiamondItem()); public static final VayudaTurquoiseGemstoneNetheriteItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_ITEM = register("vayuda_turquoise_gemstone_netherite", new VayudaTurquoiseGemstoneNetheriteItem()); public static final VayudaTurquoiseGemstoneIronSwordItem VAYUDA_TURQUOISE_GEMSTONE_IRON_SWORD_ITEM = register("vayuda_turquoise_gemstone_iron_sword", new VayudaTurquoiseGemstoneIronSwordItem()); public static final VayudaTurquoiseGemstoneDiamondSwordItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_SWORD_ITEM = register("vayuda_turquoise_gemstone_diamond_sword", new VayudaTurquoiseGemstoneDiamondSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteSwordItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_SWORD_ITEM = register("vayuda_turquoise_gemstone_netherite_sword", new VayudaTurquoiseGemstoneNetheriteSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_HELMET_ITEM = register("vayuda_turquoise_gemstone_netherite_helmet", new VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_netherite_chestplate", new VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_netherite_leggings", new VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_BOOTS_ITEM = register("vayuda_turquoise_gemstone_netherite_boots", new VayudaTurquoiseGemstoneNetheriteArmorItem.Boots()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_HELMET_ITEM = register("vayuda_turquoise_gemstone_diamond_helmet", new VayudaTurquoiseGemstoneDiamondArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_diamond_chestplate", new VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_diamond_leggings", new VayudaTurquoiseGemstoneDiamondArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_BOOTS_ITEM = register("vayuda_turquoise_gemstone_diamond_boots", new VayudaTurquoiseGemstoneDiamondArmorItem.Boots()); public static final VayudaTurquoiseGemstoneIronArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_IRON_HELMET_ITEM = register("vayuda_turquoise_gemstone_iron_helmet", new VayudaTurquoiseGemstoneIronArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneIronArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_IRON_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_iron_chestplate", new VayudaTurquoiseGemstoneIronArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneIronArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_IRON_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_iron_leggings", new VayudaTurquoiseGemstoneIronArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneIronArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_IRON_BOOTS_ITEM = register("vayuda_turquoise_gemstone_iron_boots", new VayudaTurquoiseGemstoneIronArmorItem.Boots()); public static final Item VAJRADA_AMETHYST_ITEM = register("vajrada_amethyst", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_SLIVER_ITEM = register("vajrada_amethyst_sliver", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_FRAGMENT_ITEM = register("vajrada_amethyst_fragment", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_PIECE_ITEM = register("vajrada_amethyst_piece", new Item(new Item.Properties())); public static final DendroCoreItem DENDRO_CORE_ITEM = register("dendro_core", new DendroCoreItem()); public static final VajradaAmethystHoeItem VAJRADA_AMETHYST_HOE_ITEM = register("vajrada_amethyst_hoe", new VajradaAmethystHoeItem()); public static final VajradaAmethystAxeItem VAJRADA_AMETHYST_AXE_ITEM = register("vajrada_amethyst_axe", new VajradaAmethystAxeItem()); public static final VajradaAmethystPickaxeItem VAJRADA_AMETHYST_PICKAXE_ITEM = register("vajrada_amethyst_pickaxe", new VajradaAmethystPickaxeItem()); public static final VajradaAmethystShovelItem VAJRADA_AMETHYST_SHOVEL_ITEM = register("vajrada_amethyst_shovel", new VajradaAmethystShovelItem()); public static final VajradaAmethystIronItem VAJRADA_AMETHYST_IRON_ITEM = register("vajrada_amethyst_iron", new VajradaAmethystIronItem()); public static final VajradaAmethystDiamondItem VAJRADA_AMETHYST_DIAMOND_ITEM = register("vajrada_amethyst_diamond", new VajradaAmethystDiamondItem()); public static final VajradaAmethystNetheriteItem VAJRADA_AMETHYST_NETHERITE_ITEM = register("vajrada_amethyst_netherite", new VajradaAmethystNetheriteItem()); public static final VajradaAmethystIronSwordItem VAJRADA_AMETHYST_IRON_SWORD_ITEM = register("vajrada_amethyst_iron_sword", new VajradaAmethystIronSwordItem()); public static final VajradaAmethystDiamondSwordItem VAJRADA_AMETHYST_DIAMOND_SWORD_ITEM = register("vajrada_amethyst_diamond_sword", new VajradaAmethystDiamondSwordItem()); public static final VajradaAmethystNetheriteSwordItem VAJRADA_AMETHYST_NETHERITE_SWORD_ITEM = register("vajrada_amethyst_netherite_sword", new VajradaAmethystNetheriteSwordItem()); public static final VajradaAmethystIronArmorItem.Helmet VAJRADA_AMETHYST_IRON_HELMET_ITEM = register("vajrada_amethyst_iron_helmet", new VajradaAmethystIronArmorItem.Helmet()); public static final VajradaAmethystIronArmorItem.Chestplate VAJRADA_AMETHYST_IRON_CHESTPLATE_ITEM = register("vajrada_amethyst_iron_chestplate", new VajradaAmethystIronArmorItem.Chestplate()); public static final VajradaAmethystIronArmorItem.Leggings VAJRADA_AMETHYST_IRON_LEGGINGS_ITEM = register("vajrada_amethyst_iron_leggings", new VajradaAmethystIronArmorItem.Leggings()); public static final VajradaAmethystIronArmorItem.Boots VAJRADA_AMETHYST_IRON_BOOTS_ITEM = register("vajrada_amethyst_iron_boots", new VajradaAmethystIronArmorItem.Boots()); public static final VajradaAmethystDiamondArmorItem.Helmet VAJRADA_AMETHYST_DIAMOND_HELMET_ITEM = register("vajrada_amethyst_diamond_helmet", new VajradaAmethystDiamondArmorItem.Helmet()); public static final VajradaAmethystDiamondArmorItem.Chestplate VAJRADA_AMETHYST_DIAMOND_CHESTPLATE_ITEM = register("vajrada_amethyst_diamond_chestplate", new VajradaAmethystDiamondArmorItem.Chestplate()); public static final VajradaAmethystDiamondArmorItem.Leggings VAJRADA_AMETHYST_DIAMOND_LEGGINGS_ITEM = register("vajrada_amethyst_diamond_leggings", new VajradaAmethystDiamondArmorItem.Leggings()); public static final VajradaAmethystDiamondArmorItem.Boots VAJRADA_AMETHYST_DIAMOND_BOOTS_ITEM = register("vajrada_amethyst_diamond_boots", new VajradaAmethystDiamondArmorItem.Boots()); public static final VajradaAmethystNetheriteArmorItem.Helmet VAJRADA_AMETHYST_NETHERITE_HELMET_ITEM = register("vajrada_amethyst_netherite_helmet", new VajradaAmethystNetheriteArmorItem.Helmet()); public static final VajradaAmethystNetheriteArmorItem.Chestplate VAJRADA_AMETHYST_NETHERITE_CHESTPLATE_ITEM = register("vajrada_amethyst_netherite_chestplate", new VajradaAmethystNetheriteArmorItem.Chestplate()); public static final VajradaAmethystNetheriteArmorItem.Leggings VAJRADA_AMETHYST_NETHERITE_LEGGINGS_ITEM = register("vajrada_amethyst_netherite_leggings", new VajradaAmethystNetheriteArmorItem.Leggings()); public static final VajradaAmethystNetheriteArmorItem.Boots VAJRADA_AMETHYST_NETHERITE_BOOTS_ITEM = register("vajrada_amethyst_netherite_boots", new VajradaAmethystNetheriteArmorItem.Boots()); public static final SmithingTemplateMoraItem SMITHING_TEMPLATE_MORA_ITEM = register("smithing_template_mora", new SmithingTemplateMoraItem()); public static final SmithingTemplateElement1Item SMITHING_TEMPLATE_ELEMENT_1_ITEM = register("smithing_template_element1", new SmithingTemplateElement1Item()); public static final SmithingTemplateElement2Item SMITHING_TEMPLATE_ELEMENT_2_ITEM = register("smithing_template_element2", new SmithingTemplateElement2Item()); public static final Item ELEMENT_CRYSTAL_ITEM = register("element_crystal", new Item(new Item.Properties().fireResistant().rarity(Rarity.EPIC))); public static final Item NAGADUS_EMERALD_ITEM = register("nagadus_emerald", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_SLIVER_ITEM = register("nagadus_emerald_sliver", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_FRAGMENT_ITEM = register("nagadus_emerald_fragment", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_PIECE_ITEM = register("nagadus_emerald_piece", new Item(new Item.Properties())); public static final NagadusEmeraldHoeItem NAGADUS_EMERALD_HOE_ITEM = register("nagadus_emerald_hoe", new NagadusEmeraldHoeItem()); public static final NagadusEmeraldAxeItem NAGADUS_EMERALD_AXE_ITEM = register("nagadus_emerald_axe", new NagadusEmeraldAxeItem()); public static final Item NAGADUS_EMERALD_IRON_ITEM = register("nagadus_emerald_iron", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_DIAMOND_ITEM = register("nagadus_emerald_diamond", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_NETHERITE_ITEM = register("nagadus_emerald_netherite", new Item(new Item.Properties())); public static final NagadusEmeraldShovelItem NAGADUS_EMERALD_SHOVEL_ITEM = register("nagadus_emerald_shovel", new NagadusEmeraldShovelItem()); public static final NagadusEmeraldIronSwordItem NAGADUS_EMERALD_IRON_SWORD_ITEM = register("nagadus_emerald_iron_sword", new NagadusEmeraldIronSwordItem()); public static final NagadusEmeraldDiamondSwordItem NAGADUS_EMERALD_DIAMOND_SWORD_ITEM = register("nagadus_emerald_diamond_sword", new NagadusEmeraldDiamondSwordItem()); public static final NagadusEmeraldNetheriteSwordItem NAGADUS_EMERALD_NETHERITE_SWORD_ITEM = register("nagadus_emerald_netherite_sword", new NagadusEmeraldNetheriteSwordItem()); public static final NagadusEmeraldIronArmorItem.Helmet NAGADUS_EMERALD_IRON_HELMET_ITEM = register("nagadus_emerald_iron_helmet", new NagadusEmeraldIronArmorItem.Helmet()); public static final NagadusEmeraldIronArmorItem.Chestplate NAGADUS_EMERALD_IRON_CHESTPLATE_ITEM = register("nagadus_emerald_iron_chestplate", new NagadusEmeraldIronArmorItem.Chestplate()); public static final NagadusEmeraldIronArmorItem.Leggings NAGADUS_EMERALD_IRON_LEGGINGS_ITEM = register("nagadus_emerald_iron_leggings", new NagadusEmeraldIronArmorItem.Leggings()); public static final NagadusEmeraldIronArmorItem.Boots NAGADUS_EMERALD_IRON_BOOTS_ITEM = register("nagadus_emerald_iron_boots", new NagadusEmeraldIronArmorItem.Boots()); public static final NagadusEmeraldDiamondArmorItem.Helmet NAGADUS_EMERALD_DIAMOND_HELMET_ITEM = register("nagadus_emerald_diamond_helmet", new NagadusEmeraldDiamondArmorItem.Helmet()); public static final NagadusEmeraldDiamondArmorItem.Chestplate NAGADUS_EMERALD_DIAMOND_CHESTPLATE_ITEM = register("nagadus_emerald_diamond_chestplate", new NagadusEmeraldDiamondArmorItem.Chestplate()); public static final NagadusEmeraldDiamondArmorItem.Leggings NAGADUS_EMERALD_DIAMOND_LEGGINGS_ITEM = register("nagadus_emerald_diamond_leggings", new NagadusEmeraldDiamondArmorItem.Leggings()); public static final NagadusEmeraldDiamondArmorItem.Boots NAGADUS_EMERALD_DIAMOND_BOOTS_ITEM = register("nagadus_emerald_diamond_boots", new NagadusEmeraldDiamondArmorItem.Boots()); public static final NagadusEmeraldNetheriteArmorItem.Helmet NAGADUS_EMERALD_NETHERITE_HELMET_ITEM = register("nagadus_emerald_netherite_helmet", new NagadusEmeraldNetheriteArmorItem.Helmet()); public static final NagadusEmeraldNetheriteArmorItem.Chestplate NAGADUS_EMERALD_NETHERITE_CHESTPLATE_ITEM = register("nagadus_emerald_netherite_chestplate", new NagadusEmeraldNetheriteArmorItem.Chestplate()); public static final NagadusEmeraldNetheriteArmorItem.Leggings NAGADUS_EMERALD_NETHERITE_LEGGINGS_ITEM = register("nagadus_emerald_netherite_leggings", new NagadusEmeraldNetheriteArmorItem.Leggings()); public static final NagadusEmeraldNetheriteArmorItem.Boots NAGADUS_EMERALD_NETHERITE_BOOTS_ITEM = register("nagadus_emerald_netherite_boots", new NagadusEmeraldNetheriteArmorItem.Boots()); public static final Item AGNIDUS_AGATE_ITEM = register("agnidus_agate", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_SLIVER_ITEM = register("agnidus_agate_sliver", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_FRAGMENT_ITEM = register("agnidus_agate_fragment", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_PIECE_ITEM = register("agnidus_agate_piece", new Item(new Item.Properties())); public static final AgnidusAgateIronItem AGNIDUS_AGATE_IRON_ITEM = register("agnidus_agate_iron", new AgnidusAgateIronItem()); public static final AgnidusAgateDiamondItem AGNIDUS_AGATE_DIAMOND_ITEM = register("agnidus_agate_diamond", new AgnidusAgateDiamondItem()); public static final AgnidusAgateNetheriteItem AGNIDUS_AGATE_NETHERITE_ITEM = register("agnidus_agate_netherite", new AgnidusAgateNetheriteItem()); public static final AgnidusAgateShovelItem AGNIDUS_AGATE_SHOVEL_ITEM = register("agnidus_agate_shovel", new AgnidusAgateShovelItem()); public static final AgnidusAgateHoeItem AGNIDUS_AGATE_HOE_ITEM = register("agnidus_agate_hoe", new AgnidusAgateHoeItem()); public static final ElementCrystalDustItem ELEMENT_CRYSTAL_DUST_ITEM = register("element_crystal_dust", new ElementCrystalDustItem()); public static final AgnidusAgateAxeItem AGNIDUS_AGATE_AXE_ITEM = register("agnidus_agate_axe", new AgnidusAgateAxeItem()); public static final AgnidusAgatePickaxeItem AGNIDUS_AGATE_PICKAXE_ITEM = register("agnidus_agate_pickaxe", new AgnidusAgatePickaxeItem()); public static final AgnidusAgateIronSwordItem AGNIDUS_AGATE_IRON_SWORD_ITEM = register("agnidus_agate_iron_sword", new AgnidusAgateIronSwordItem()); public static final AgnidusAgateDiamondSwordItem AGNIDUS_AGATE_DIAMOND_SWORD_ITEM = register("agnidus_agate_diamond_sword", new AgnidusAgateDiamondSwordItem()); public static final AgnidusAgateNetheriteSwordItem AGNIDUS_AGATE_NETHERITE_SWORD_ITEM = register("agnidus_agate_netherite_sword", new AgnidusAgateNetheriteSwordItem()); public static final AgnidusAgateIronArmorItem.Helmet AGNIDUS_AGATE_IRON_HELMET_ITEM = register("agnidus_agate_iron_helmet", new AgnidusAgateIronArmorItem.Helmet()); public static final AgnidusAgateIronArmorItem.Chestplate AGNIDUS_AGATE_IRON_CHESTPLATE_ITEM = register("agnidus_agate_iron_chestplate", new AgnidusAgateIronArmorItem.Chestplate()); public static final AgnidusAgateIronArmorItem.Leggings AGNIDUS_AGATE_IRON_LEGGINGS_ITEM = register("agnidus_agate_iron_leggings", new AgnidusAgateIronArmorItem.Leggings()); public static final AgnidusAgateIronArmorItem.Boots AGNIDUS_AGATE_IRON_BOOTS_ITEM = register("agnidus_agate_iron_boots", new AgnidusAgateIronArmorItem.Boots()); public static final AgnidusAgateDiamondArmorItem.Helmet AGNIDUS_AGATE_DIAMOND_HELMET_ITEM = register("agnidus_agate_diamond_helmet", new AgnidusAgateDiamondArmorItem.Helmet()); public static final AgnidusAgateDiamondArmorItem.Chestplate AGNIDUS_AGATE_DIAMOND_CHESTPLATE_ITEM = register("agnidus_agate_diamond_chestplate", new AgnidusAgateDiamondArmorItem.Chestplate()); public static final AgnidusAgateDiamondArmorItem.Leggings AGNIDUS_AGATE_DIAMOND_LEGGINGS_ITEM = register("agnidus_agate_diamond_leggings", new AgnidusAgateDiamondArmorItem.Leggings()); public static final AgnidusAgateDiamondArmorItem.Boots AGNIDUS_AGATE_DIAMOND_BOOTS_ITEM = register("agnidus_agate_diamond_boots", new AgnidusAgateDiamondArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Boots AGNIDUS_AGATE_NETHERITE_BOOTS_ITEM = register("agnidus_agate_netherite_boots", new AgnidusAgateNetheriteArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Helmet AGNIDUS_AGATE_NETHERITE_HELMET_ITEM = register("agnidus_agate_netherite_helmet", new AgnidusAgateNetheriteArmorItem.Helmet()); public static final AgnidusAgateNetheriteArmorItem.Chestplate AGNIDUS_AGATE_NETHERITE_CHESTPLATE_ITEM = register("agnidus_agate_netherite_chestplate", new AgnidusAgateNetheriteArmorItem.Chestplate()); public static final AgnidusAgateNetheriteArmorItem.Leggings AGNIDUS_AGATE_NETHERITE_LEGGINGS_ITEM = register("agnidus_agate_netherite_leggings", new AgnidusAgateNetheriteArmorItem.Leggings()); public static final Item PRITHVA_TOPAZ_ITEM = register("prithva_topaz", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_FRAGMENT_ITEM = register("prithva_topaz_fragment", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_SLIVER_ITEM = register("prithva_topaz_sliver", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_PIECE_ITEM = register("prithva_topaz_piece", new Item(new Item.Properties())); public static void init() {
package com.primogemstudio.primogemcraft.items; public class PrimogemCraftItems { public static final TheAllBeginningItem THE_ALL_BEGINNING_ITEM = register("the_all_beginning", new TheAllBeginningItem()); public static final PrimogemItem PRIMOGEM_ITEM = register("primogem", new PrimogemItem()); public static final OldStoneItem OLD_STONE_ITEM = register("old_stone", new OldStoneItem()); public static final Item MASTER_LESS_STAR_DUST_ITEM = register("masterless_stardust", new Item(new Item.Properties().stacksTo(64).rarity(Rarity.COMMON))); public static final Item MASTER_LESS_STARG_LITTER_ITEM = register("masterless_starglitter", new Item(new Item.Properties().stacksTo(64).rarity(Rarity.COMMON))); public static final PrimogemBilletItem PRIMOGEM_BILLET_ITEM = register("primogem_billet", new PrimogemBilletItem()); public static final IntertwinedFateItem INTERTWINED_FATE_ITEM = register("intertwined_fate", new IntertwinedFateItem()); public static final AcquaintFateItem ACQUAINT_FATE_ITEM = register("acquaint_fate", new AcquaintFateItem()); public static final NagadusEmeraldPickaxeItem NAGADUS_EMERALD_PICKAXE_ITEM = register("nagadus_emerald_pickaxe", new NagadusEmeraldPickaxeItem()); public static final PrimogemPickaxeItem PRIMOGEM_PICKAXE_ITEM = register("primogem_pickaxe", new PrimogemPickaxeItem()); public static final PrimogemHoeItem PRIMOGEM_HOE_ITEM = register("primogem_hoe", new PrimogemHoeItem()); public static final PrimogemAxeItem PRIMOGEM_AXE_ITEM = register("primogem_axe", new PrimogemAxeItem()); public static final PrimogemShovelItem PRIMOGEM_SHOVEL_ITEM = register("primogem_shovel", new PrimogemShovelItem()); public static final PrimogemSwordItem PRIMOGEM_SWORD_ITEM = register("primogem_sword", new PrimogemSwordItem()); public static final DullBladeItem DULL_BLADE_ITEM = register("dull_blade", new DullBladeItem()); public static final ANewDayWithHopeRecordItem A_NEW_DAY_WITH_HOPE_RECORD_ITEM = register("music_disc_a_new_day_with_hope", new ANewDayWithHopeRecordItem()); public static final TheFadingStoriesRecordItem THE_FADING_STORIES_RECORD_ITEM = register("music_disc_the_fading_stories", new TheFadingStoriesRecordItem()); public static final HakushinLullabyRecordItem HAKUSHIN_LULLABY_RECORD_ITEM = register("music_disc_hakushin_lullaby", new HakushinLullabyRecordItem()); public static final VillageSurroundedByGreenRecordItem VILLAGE_SURROUNDED_BY_GREEN_RECORD_ITEM = register("music_disc_village_surrounded_by_green", new VillageSurroundedByGreenRecordItem()); public static final BalladofManyWatersRecordItem BALLAD_OF_MANY_WATERS_RECORD_ITEM = register("music_disc_ballad_of_many_waters", new BalladofManyWatersRecordItem()); public static final SpaceWalkRecordItem SPACE_WALK_RECORD_ITEM = register("music_disc_space_walk", new SpaceWalkRecordItem()); public static final SaltyMoonRecordItem SALTY_MOON_RECORD_ITEM = register("music_disc_salty_moon", new SaltyMoonRecordItem()); public static final TakeTheJourneyRecordItem TAKE_THE_JOURNEY_RECORD_ITEM = register("music_disc_take_the_journey", new TakeTheJourneyRecordItem()); public static final IntertwinedFateTenTimesItem INTERTWINED_FATE_TEN_ITEM = register("intertwined_fate_ten", new IntertwinedFateTenTimesItem()); public static final Item MORA_BILLET_ITEM = register("mora_billet", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final Item MORA_ITEM = register("mora", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final ExquisiteMoraItem EXQUISITE_MORA_ITEM = register("exquisite_mora", new ExquisiteMoraItem()); public static final ExquisiteMoraBagItem EXQUISITE_MORA_BAG_ITEM = register("exquisite_mora_bag", new ExquisiteMoraBagItem()); public static final MoraWalletItem MORA_WALLET_ITEM = register("mora_wallet", new MoraWalletItem()); public static final CosmicFragmentsItem COSMIC_FRAGMENTS_ITEM = register("cosmic_fragments", new CosmicFragmentsItem()); public static final SocietyTicketItem SOCIETY_TICKET_ITEM = register("society_ticket", new SocietyTicketItem()); public static final StrangePrimogemSwordItem STRANGE_PRIMOGEM_SWORD_ITEM = register("strange_primogem_sword", new StrangePrimogemSwordItem()); public static final MoraPickaxeItem MORA_PICKAXE_ITEM = register("mora_pickaxe", new MoraPickaxeItem()); public static final MoraSwordItem MORA_SWORD_ITEM = register("mora_sword", new MoraSwordItem()); public static final MoraShovelItem MORA_SHOVEL_ITEM = register("mora_shovel", new MoraShovelItem()); public static final MoraHoeItem MORA_HOE_ITEM = register("mora_hoe", new MoraHoeItem()); public static final MoraAxeItem MORA_AXE_ITEM = register("mora_axe", new MoraAxeItem()); public static final MoraArmorItem.MoraHelmet MORA_HELMET_ITEM = register("mora_helmet", new MoraArmorItem.MoraHelmet()); public static final MoraArmorItem.MoraChestplate MORA_CHESTPLATE_ITEM = register("mora_chestplate", new MoraArmorItem.MoraChestplate()); public static final MoraArmorItem.MoraLeggings MORA_LEGGINGS_ITEM = register("mora_leggings", new MoraArmorItem.MoraLeggings()); public static final MoraArmorItem.MoraBoots MORA_BOOTS_ITEM = register("mora_boots", new MoraArmorItem.MoraBoots()); public static final Item TEYVAT_STICK_ITEM = register("teyvat_stick", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_ITEM = register("vayuda_turquoise_gemstone", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_PIECE_ITEM = register("vayuda_turquoise_gemstone_piece", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_FRAGMENT_ITEM = register("vayuda_turquoise_gemstone_fragment", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final Item VAYUDA_TURQUOISE_GEMSTONE_SLIVER_ITEM = register("vayuda_turquoise_gemstone_sliver", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final VayudaTurquoiseGemstoneHoeItem VAYUDA_TURQUOISE_GEMSTONE_HOE_ITEM = register("vayuda_turquoise_gemstone_hoe", new VayudaTurquoiseGemstoneHoeItem()); public static final VayudaTurquoiseGemstoneAxeItem VAYUDA_TURQUOISE_GEMSTONE_AXE_ITEM = register("vayuda_turquoise_gemstone_axe", new VayudaTurquoiseGemstoneAxeItem()); public static final VayudaTurquoiseGemstonePickaxeItem VAYUDA_TURQUOISE_GEMSTONE_PICKAXE_ITEM = register("vayuda_turquoise_gemstone_pickaxe", new VayudaTurquoiseGemstonePickaxeItem()); public static final VayudaTurquoiseGemstoneShovelItem VAYUDA_TURQUOISE_GEMSTONE_SHOVEL_ITEM = register("vayuda_turquoise_gemstone_shovel", new VayudaTurquoiseGemstoneShovelItem()); public static final VayudaTurquoiseGemstoneIronItem VAYUDA_TURQUOISE_GEMSTONE_IRON_ITEM = register("vayuda_turquoise_gemstone_iron", new VayudaTurquoiseGemstoneIronItem()); public static final VayudaTurquoiseGemstoneDiamondItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_ITEM = register("vayuda_turquoise_gemstone_diamond", new VayudaTurquoiseGemstoneDiamondItem()); public static final VayudaTurquoiseGemstoneNetheriteItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_ITEM = register("vayuda_turquoise_gemstone_netherite", new VayudaTurquoiseGemstoneNetheriteItem()); public static final VayudaTurquoiseGemstoneIronSwordItem VAYUDA_TURQUOISE_GEMSTONE_IRON_SWORD_ITEM = register("vayuda_turquoise_gemstone_iron_sword", new VayudaTurquoiseGemstoneIronSwordItem()); public static final VayudaTurquoiseGemstoneDiamondSwordItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_SWORD_ITEM = register("vayuda_turquoise_gemstone_diamond_sword", new VayudaTurquoiseGemstoneDiamondSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteSwordItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_SWORD_ITEM = register("vayuda_turquoise_gemstone_netherite_sword", new VayudaTurquoiseGemstoneNetheriteSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_HELMET_ITEM = register("vayuda_turquoise_gemstone_netherite_helmet", new VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_netherite_chestplate", new VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_netherite_leggings", new VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_BOOTS_ITEM = register("vayuda_turquoise_gemstone_netherite_boots", new VayudaTurquoiseGemstoneNetheriteArmorItem.Boots()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_HELMET_ITEM = register("vayuda_turquoise_gemstone_diamond_helmet", new VayudaTurquoiseGemstoneDiamondArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_diamond_chestplate", new VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_diamond_leggings", new VayudaTurquoiseGemstoneDiamondArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_BOOTS_ITEM = register("vayuda_turquoise_gemstone_diamond_boots", new VayudaTurquoiseGemstoneDiamondArmorItem.Boots()); public static final VayudaTurquoiseGemstoneIronArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_IRON_HELMET_ITEM = register("vayuda_turquoise_gemstone_iron_helmet", new VayudaTurquoiseGemstoneIronArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneIronArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_IRON_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_iron_chestplate", new VayudaTurquoiseGemstoneIronArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneIronArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_IRON_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_iron_leggings", new VayudaTurquoiseGemstoneIronArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneIronArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_IRON_BOOTS_ITEM = register("vayuda_turquoise_gemstone_iron_boots", new VayudaTurquoiseGemstoneIronArmorItem.Boots()); public static final Item VAJRADA_AMETHYST_ITEM = register("vajrada_amethyst", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_SLIVER_ITEM = register("vajrada_amethyst_sliver", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_FRAGMENT_ITEM = register("vajrada_amethyst_fragment", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_PIECE_ITEM = register("vajrada_amethyst_piece", new Item(new Item.Properties())); public static final DendroCoreItem DENDRO_CORE_ITEM = register("dendro_core", new DendroCoreItem()); public static final VajradaAmethystHoeItem VAJRADA_AMETHYST_HOE_ITEM = register("vajrada_amethyst_hoe", new VajradaAmethystHoeItem()); public static final VajradaAmethystAxeItem VAJRADA_AMETHYST_AXE_ITEM = register("vajrada_amethyst_axe", new VajradaAmethystAxeItem()); public static final VajradaAmethystPickaxeItem VAJRADA_AMETHYST_PICKAXE_ITEM = register("vajrada_amethyst_pickaxe", new VajradaAmethystPickaxeItem()); public static final VajradaAmethystShovelItem VAJRADA_AMETHYST_SHOVEL_ITEM = register("vajrada_amethyst_shovel", new VajradaAmethystShovelItem()); public static final VajradaAmethystIronItem VAJRADA_AMETHYST_IRON_ITEM = register("vajrada_amethyst_iron", new VajradaAmethystIronItem()); public static final VajradaAmethystDiamondItem VAJRADA_AMETHYST_DIAMOND_ITEM = register("vajrada_amethyst_diamond", new VajradaAmethystDiamondItem()); public static final VajradaAmethystNetheriteItem VAJRADA_AMETHYST_NETHERITE_ITEM = register("vajrada_amethyst_netherite", new VajradaAmethystNetheriteItem()); public static final VajradaAmethystIronSwordItem VAJRADA_AMETHYST_IRON_SWORD_ITEM = register("vajrada_amethyst_iron_sword", new VajradaAmethystIronSwordItem()); public static final VajradaAmethystDiamondSwordItem VAJRADA_AMETHYST_DIAMOND_SWORD_ITEM = register("vajrada_amethyst_diamond_sword", new VajradaAmethystDiamondSwordItem()); public static final VajradaAmethystNetheriteSwordItem VAJRADA_AMETHYST_NETHERITE_SWORD_ITEM = register("vajrada_amethyst_netherite_sword", new VajradaAmethystNetheriteSwordItem()); public static final VajradaAmethystIronArmorItem.Helmet VAJRADA_AMETHYST_IRON_HELMET_ITEM = register("vajrada_amethyst_iron_helmet", new VajradaAmethystIronArmorItem.Helmet()); public static final VajradaAmethystIronArmorItem.Chestplate VAJRADA_AMETHYST_IRON_CHESTPLATE_ITEM = register("vajrada_amethyst_iron_chestplate", new VajradaAmethystIronArmorItem.Chestplate()); public static final VajradaAmethystIronArmorItem.Leggings VAJRADA_AMETHYST_IRON_LEGGINGS_ITEM = register("vajrada_amethyst_iron_leggings", new VajradaAmethystIronArmorItem.Leggings()); public static final VajradaAmethystIronArmorItem.Boots VAJRADA_AMETHYST_IRON_BOOTS_ITEM = register("vajrada_amethyst_iron_boots", new VajradaAmethystIronArmorItem.Boots()); public static final VajradaAmethystDiamondArmorItem.Helmet VAJRADA_AMETHYST_DIAMOND_HELMET_ITEM = register("vajrada_amethyst_diamond_helmet", new VajradaAmethystDiamondArmorItem.Helmet()); public static final VajradaAmethystDiamondArmorItem.Chestplate VAJRADA_AMETHYST_DIAMOND_CHESTPLATE_ITEM = register("vajrada_amethyst_diamond_chestplate", new VajradaAmethystDiamondArmorItem.Chestplate()); public static final VajradaAmethystDiamondArmorItem.Leggings VAJRADA_AMETHYST_DIAMOND_LEGGINGS_ITEM = register("vajrada_amethyst_diamond_leggings", new VajradaAmethystDiamondArmorItem.Leggings()); public static final VajradaAmethystDiamondArmorItem.Boots VAJRADA_AMETHYST_DIAMOND_BOOTS_ITEM = register("vajrada_amethyst_diamond_boots", new VajradaAmethystDiamondArmorItem.Boots()); public static final VajradaAmethystNetheriteArmorItem.Helmet VAJRADA_AMETHYST_NETHERITE_HELMET_ITEM = register("vajrada_amethyst_netherite_helmet", new VajradaAmethystNetheriteArmorItem.Helmet()); public static final VajradaAmethystNetheriteArmorItem.Chestplate VAJRADA_AMETHYST_NETHERITE_CHESTPLATE_ITEM = register("vajrada_amethyst_netherite_chestplate", new VajradaAmethystNetheriteArmorItem.Chestplate()); public static final VajradaAmethystNetheriteArmorItem.Leggings VAJRADA_AMETHYST_NETHERITE_LEGGINGS_ITEM = register("vajrada_amethyst_netherite_leggings", new VajradaAmethystNetheriteArmorItem.Leggings()); public static final VajradaAmethystNetheriteArmorItem.Boots VAJRADA_AMETHYST_NETHERITE_BOOTS_ITEM = register("vajrada_amethyst_netherite_boots", new VajradaAmethystNetheriteArmorItem.Boots()); public static final SmithingTemplateMoraItem SMITHING_TEMPLATE_MORA_ITEM = register("smithing_template_mora", new SmithingTemplateMoraItem()); public static final SmithingTemplateElement1Item SMITHING_TEMPLATE_ELEMENT_1_ITEM = register("smithing_template_element1", new SmithingTemplateElement1Item()); public static final SmithingTemplateElement2Item SMITHING_TEMPLATE_ELEMENT_2_ITEM = register("smithing_template_element2", new SmithingTemplateElement2Item()); public static final Item ELEMENT_CRYSTAL_ITEM = register("element_crystal", new Item(new Item.Properties().fireResistant().rarity(Rarity.EPIC))); public static final Item NAGADUS_EMERALD_ITEM = register("nagadus_emerald", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_SLIVER_ITEM = register("nagadus_emerald_sliver", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_FRAGMENT_ITEM = register("nagadus_emerald_fragment", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_PIECE_ITEM = register("nagadus_emerald_piece", new Item(new Item.Properties())); public static final NagadusEmeraldHoeItem NAGADUS_EMERALD_HOE_ITEM = register("nagadus_emerald_hoe", new NagadusEmeraldHoeItem()); public static final NagadusEmeraldAxeItem NAGADUS_EMERALD_AXE_ITEM = register("nagadus_emerald_axe", new NagadusEmeraldAxeItem()); public static final Item NAGADUS_EMERALD_IRON_ITEM = register("nagadus_emerald_iron", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_DIAMOND_ITEM = register("nagadus_emerald_diamond", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_NETHERITE_ITEM = register("nagadus_emerald_netherite", new Item(new Item.Properties())); public static final NagadusEmeraldShovelItem NAGADUS_EMERALD_SHOVEL_ITEM = register("nagadus_emerald_shovel", new NagadusEmeraldShovelItem()); public static final NagadusEmeraldIronSwordItem NAGADUS_EMERALD_IRON_SWORD_ITEM = register("nagadus_emerald_iron_sword", new NagadusEmeraldIronSwordItem()); public static final NagadusEmeraldDiamondSwordItem NAGADUS_EMERALD_DIAMOND_SWORD_ITEM = register("nagadus_emerald_diamond_sword", new NagadusEmeraldDiamondSwordItem()); public static final NagadusEmeraldNetheriteSwordItem NAGADUS_EMERALD_NETHERITE_SWORD_ITEM = register("nagadus_emerald_netherite_sword", new NagadusEmeraldNetheriteSwordItem()); public static final NagadusEmeraldIronArmorItem.Helmet NAGADUS_EMERALD_IRON_HELMET_ITEM = register("nagadus_emerald_iron_helmet", new NagadusEmeraldIronArmorItem.Helmet()); public static final NagadusEmeraldIronArmorItem.Chestplate NAGADUS_EMERALD_IRON_CHESTPLATE_ITEM = register("nagadus_emerald_iron_chestplate", new NagadusEmeraldIronArmorItem.Chestplate()); public static final NagadusEmeraldIronArmorItem.Leggings NAGADUS_EMERALD_IRON_LEGGINGS_ITEM = register("nagadus_emerald_iron_leggings", new NagadusEmeraldIronArmorItem.Leggings()); public static final NagadusEmeraldIronArmorItem.Boots NAGADUS_EMERALD_IRON_BOOTS_ITEM = register("nagadus_emerald_iron_boots", new NagadusEmeraldIronArmorItem.Boots()); public static final NagadusEmeraldDiamondArmorItem.Helmet NAGADUS_EMERALD_DIAMOND_HELMET_ITEM = register("nagadus_emerald_diamond_helmet", new NagadusEmeraldDiamondArmorItem.Helmet()); public static final NagadusEmeraldDiamondArmorItem.Chestplate NAGADUS_EMERALD_DIAMOND_CHESTPLATE_ITEM = register("nagadus_emerald_diamond_chestplate", new NagadusEmeraldDiamondArmorItem.Chestplate()); public static final NagadusEmeraldDiamondArmorItem.Leggings NAGADUS_EMERALD_DIAMOND_LEGGINGS_ITEM = register("nagadus_emerald_diamond_leggings", new NagadusEmeraldDiamondArmorItem.Leggings()); public static final NagadusEmeraldDiamondArmorItem.Boots NAGADUS_EMERALD_DIAMOND_BOOTS_ITEM = register("nagadus_emerald_diamond_boots", new NagadusEmeraldDiamondArmorItem.Boots()); public static final NagadusEmeraldNetheriteArmorItem.Helmet NAGADUS_EMERALD_NETHERITE_HELMET_ITEM = register("nagadus_emerald_netherite_helmet", new NagadusEmeraldNetheriteArmorItem.Helmet()); public static final NagadusEmeraldNetheriteArmorItem.Chestplate NAGADUS_EMERALD_NETHERITE_CHESTPLATE_ITEM = register("nagadus_emerald_netherite_chestplate", new NagadusEmeraldNetheriteArmorItem.Chestplate()); public static final NagadusEmeraldNetheriteArmorItem.Leggings NAGADUS_EMERALD_NETHERITE_LEGGINGS_ITEM = register("nagadus_emerald_netherite_leggings", new NagadusEmeraldNetheriteArmorItem.Leggings()); public static final NagadusEmeraldNetheriteArmorItem.Boots NAGADUS_EMERALD_NETHERITE_BOOTS_ITEM = register("nagadus_emerald_netherite_boots", new NagadusEmeraldNetheriteArmorItem.Boots()); public static final Item AGNIDUS_AGATE_ITEM = register("agnidus_agate", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_SLIVER_ITEM = register("agnidus_agate_sliver", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_FRAGMENT_ITEM = register("agnidus_agate_fragment", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_PIECE_ITEM = register("agnidus_agate_piece", new Item(new Item.Properties())); public static final AgnidusAgateIronItem AGNIDUS_AGATE_IRON_ITEM = register("agnidus_agate_iron", new AgnidusAgateIronItem()); public static final AgnidusAgateDiamondItem AGNIDUS_AGATE_DIAMOND_ITEM = register("agnidus_agate_diamond", new AgnidusAgateDiamondItem()); public static final AgnidusAgateNetheriteItem AGNIDUS_AGATE_NETHERITE_ITEM = register("agnidus_agate_netherite", new AgnidusAgateNetheriteItem()); public static final AgnidusAgateShovelItem AGNIDUS_AGATE_SHOVEL_ITEM = register("agnidus_agate_shovel", new AgnidusAgateShovelItem()); public static final AgnidusAgateHoeItem AGNIDUS_AGATE_HOE_ITEM = register("agnidus_agate_hoe", new AgnidusAgateHoeItem()); public static final ElementCrystalDustItem ELEMENT_CRYSTAL_DUST_ITEM = register("element_crystal_dust", new ElementCrystalDustItem()); public static final AgnidusAgateAxeItem AGNIDUS_AGATE_AXE_ITEM = register("agnidus_agate_axe", new AgnidusAgateAxeItem()); public static final AgnidusAgatePickaxeItem AGNIDUS_AGATE_PICKAXE_ITEM = register("agnidus_agate_pickaxe", new AgnidusAgatePickaxeItem()); public static final AgnidusAgateIronSwordItem AGNIDUS_AGATE_IRON_SWORD_ITEM = register("agnidus_agate_iron_sword", new AgnidusAgateIronSwordItem()); public static final AgnidusAgateDiamondSwordItem AGNIDUS_AGATE_DIAMOND_SWORD_ITEM = register("agnidus_agate_diamond_sword", new AgnidusAgateDiamondSwordItem()); public static final AgnidusAgateNetheriteSwordItem AGNIDUS_AGATE_NETHERITE_SWORD_ITEM = register("agnidus_agate_netherite_sword", new AgnidusAgateNetheriteSwordItem()); public static final AgnidusAgateIronArmorItem.Helmet AGNIDUS_AGATE_IRON_HELMET_ITEM = register("agnidus_agate_iron_helmet", new AgnidusAgateIronArmorItem.Helmet()); public static final AgnidusAgateIronArmorItem.Chestplate AGNIDUS_AGATE_IRON_CHESTPLATE_ITEM = register("agnidus_agate_iron_chestplate", new AgnidusAgateIronArmorItem.Chestplate()); public static final AgnidusAgateIronArmorItem.Leggings AGNIDUS_AGATE_IRON_LEGGINGS_ITEM = register("agnidus_agate_iron_leggings", new AgnidusAgateIronArmorItem.Leggings()); public static final AgnidusAgateIronArmorItem.Boots AGNIDUS_AGATE_IRON_BOOTS_ITEM = register("agnidus_agate_iron_boots", new AgnidusAgateIronArmorItem.Boots()); public static final AgnidusAgateDiamondArmorItem.Helmet AGNIDUS_AGATE_DIAMOND_HELMET_ITEM = register("agnidus_agate_diamond_helmet", new AgnidusAgateDiamondArmorItem.Helmet()); public static final AgnidusAgateDiamondArmorItem.Chestplate AGNIDUS_AGATE_DIAMOND_CHESTPLATE_ITEM = register("agnidus_agate_diamond_chestplate", new AgnidusAgateDiamondArmorItem.Chestplate()); public static final AgnidusAgateDiamondArmorItem.Leggings AGNIDUS_AGATE_DIAMOND_LEGGINGS_ITEM = register("agnidus_agate_diamond_leggings", new AgnidusAgateDiamondArmorItem.Leggings()); public static final AgnidusAgateDiamondArmorItem.Boots AGNIDUS_AGATE_DIAMOND_BOOTS_ITEM = register("agnidus_agate_diamond_boots", new AgnidusAgateDiamondArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Boots AGNIDUS_AGATE_NETHERITE_BOOTS_ITEM = register("agnidus_agate_netherite_boots", new AgnidusAgateNetheriteArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Helmet AGNIDUS_AGATE_NETHERITE_HELMET_ITEM = register("agnidus_agate_netherite_helmet", new AgnidusAgateNetheriteArmorItem.Helmet()); public static final AgnidusAgateNetheriteArmorItem.Chestplate AGNIDUS_AGATE_NETHERITE_CHESTPLATE_ITEM = register("agnidus_agate_netherite_chestplate", new AgnidusAgateNetheriteArmorItem.Chestplate()); public static final AgnidusAgateNetheriteArmorItem.Leggings AGNIDUS_AGATE_NETHERITE_LEGGINGS_ITEM = register("agnidus_agate_netherite_leggings", new AgnidusAgateNetheriteArmorItem.Leggings()); public static final Item PRITHVA_TOPAZ_ITEM = register("prithva_topaz", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_FRAGMENT_ITEM = register("prithva_topaz_fragment", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_SLIVER_ITEM = register("prithva_topaz_sliver", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_PIECE_ITEM = register("prithva_topaz_piece", new Item(new Item.Properties())); public static void init() {
PrimogemCraftMobEffects.init();
0
2023-10-15 08:07:06+00:00
12k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/formats/TmCompatibilityTable.java
[ { "identifier": "DataManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/DataManager.java", "snippet": "public class DataManager\n{\n public static final String SHEET_STRINGS_PATH = \"pokeditor/sheet_strings\";\n\n public static DefaultSheetPanel<PersonalData, ?> createPersonalSheet(P...
import com.formdev.flatlaf.extras.components.FlatPopupMenu; import io.github.turtleisaac.pokeditor.DataManager; import io.github.turtleisaac.pokeditor.formats.moves.MoveData; import io.github.turtleisaac.pokeditor.formats.personal.PersonalData; import io.github.turtleisaac.pokeditor.formats.personal.PersonalParser; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gamedata.TextFiles; import io.github.turtleisaac.pokeditor.gui.EditorComboBox; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.CellTypes; import io.github.turtleisaac.pokeditor.gui.sheets.tables.DefaultTable; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import javax.swing.*; import javax.swing.table.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List;
8,094
@Override public Object getValueFor(int entryIdx, TmCompatibilityColumns property) { TextBankData speciesNames = getTextBankData().get(TextFiles.SPECIES_NAMES.getValue()); PersonalData entry = getData().get(entryIdx); switch (property) { case ID -> { return entryIdx; } case NAME -> { if(entryIdx < speciesNames.size()) return speciesNames.get(entryIdx).getText(); else return ""; } case TM -> { return entry.getTmCompatibility()[property.repetition]; } } return null; } @Override protected CellTypes getCellType(int columnIndex) { return CellTypes.CHECKBOX; } @Override public FormatModel<PersonalData, TmCompatibilityColumns> getFrozenColumnModel() { return new TmCompatibilityModel(getData(), getTextBankData()) { @Override public int getColumnCount() { return super.getNumFrozenColumns(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return super.getValueAt(rowIndex, columnIndex - super.getNumFrozenColumns()); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { super.setValueAt(aValue, rowIndex, columnIndex - super.getNumFrozenColumns()); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }; } } public enum TmCompatibilityColumns { ID(-2, "id", CellTypes.INTEGER), NAME(-1, "name", CellTypes.STRING), TM(0, "name", CellTypes.CHECKBOX), NUMBER_OF_COLUMNS(1, null, null); private final int idx; private final String key; private final CellTypes cellType; int repetition; TmCompatibilityColumns(int idx, String key, CellTypes cellType) { this.idx = idx; this.key = key; this.cellType = cellType; } static TmCompatibilityColumns getColumn(int idx) { for (TmCompatibilityColumns column : TmCompatibilityColumns.values()) { if (column.idx == idx) { return column; } } return NUMBER_OF_COLUMNS; } } public void setupEditableHeader() { String[] moveNames = getFormatModel().getTextBankData().get(TextFiles.MOVE_NAMES.getValue()).getStringList().toArray(String[]::new); tableHeader.setEnabled(true); tableHeader.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2) { int columnIndex = tableHeader.columnAtPoint(event.getPoint()); if (columnIndex >= 0) { TableColumn column = tableHeader.getColumnModel().getColumn(columnIndex); Rectangle rect = tableHeader.getHeaderRect(columnIndex); JPopupMenu popupMenu = new JPopupMenu(); DefaultListModel<EditorComboBox.ComboBoxItem> items = new DefaultListModel<>(); for (String moveName : moveNames) { items.addElement(new EditorComboBox.ComboBoxItem(moveName)); } JList<EditorComboBox.ComboBoxItem> list = new JList<>(items); list.setSelectedIndex(PersonalParser.tmMoveIdNumbers[columnIndex]); list.addListSelectionListener(e -> {
package io.github.turtleisaac.pokeditor.gui.sheets.tables.formats; public class TmCompatibilityTable extends DefaultTable<PersonalData, TmCompatibilityTable.TmCompatibilityColumns> { //todo 0xF0BFC is address of TMs table static final int[] columnWidths = new int[102]; static { Arrays.fill(columnWidths, 120); } public TmCompatibilityTable(List<PersonalData> data, List<TextBankData> textData) { super(new TmCompatibilityModel(data, textData), textData, columnWidths, null); String[] moveNames = textData.get(TextFiles.MOVE_NAMES.getValue()).getStringList().toArray(String[]::new); TableCellRenderer renderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (value != null) { if (value instanceof Integer val) { if (val < moveNames.length) { this.setText(moveNames[val]); } } else if (value instanceof String s) { int val = Integer.parseInt(s); if (val < moveNames.length) { this.setText(moveNames[val]); } } } return this; } }; Enumeration<TableColumn> columns = getColumnModel().getColumns(); while (columns.hasMoreElements()) { columns.nextElement().setHeaderRenderer(renderer); } setupEditableHeader(); } @Override public Queue<String[]> obtainTextSources(List<TextBankData> textData) { Queue<String[]> textSources = new LinkedList<>(); return textSources; } @Override public Class<PersonalData> getDataClass() { return PersonalData.class; } public static class TmCompatibilityModel extends FormatModel<PersonalData, TmCompatibilityColumns> { public TmCompatibilityModel(List<PersonalData> data, List<TextBankData> textBankData) { super(data, textBankData); } @Override public int getNumFrozenColumns() { return 2; } @Override public String getColumnNameKey(int columnIndex) { return TmCompatibilityColumns.getColumn(columnIndex).key; } @Override public String getColumnName(int column) { if (column < 0) return super.getColumnName(column); return "" + PersonalParser.tmMoveIdNumbers[column]; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (columnIndex >= 0) { TmCompatibilityColumns c = TmCompatibilityColumns.getColumn(0); c.repetition = columnIndex; setValueFor(aValue, rowIndex, c); } } @Override public void setValueFor(Object aValue, int entryIdx, TmCompatibilityColumns property) { PersonalData entry = getData().get(entryIdx); if (property == TmCompatibilityColumns.TM) { aValue = prepareObjectForWriting(aValue, property.cellType); entry.getTmCompatibility()[property.repetition] = (boolean) aValue; } } @Override public int getColumnCount() { return 100; } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex >= 0) { TmCompatibilityColumns c = TmCompatibilityColumns.getColumn(0); c.repetition = columnIndex; return getValueFor(rowIndex, c); } return getValueFor(rowIndex, TmCompatibilityColumns.getColumn(columnIndex)); } @Override public Object getValueFor(int entryIdx, TmCompatibilityColumns property) { TextBankData speciesNames = getTextBankData().get(TextFiles.SPECIES_NAMES.getValue()); PersonalData entry = getData().get(entryIdx); switch (property) { case ID -> { return entryIdx; } case NAME -> { if(entryIdx < speciesNames.size()) return speciesNames.get(entryIdx).getText(); else return ""; } case TM -> { return entry.getTmCompatibility()[property.repetition]; } } return null; } @Override protected CellTypes getCellType(int columnIndex) { return CellTypes.CHECKBOX; } @Override public FormatModel<PersonalData, TmCompatibilityColumns> getFrozenColumnModel() { return new TmCompatibilityModel(getData(), getTextBankData()) { @Override public int getColumnCount() { return super.getNumFrozenColumns(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return super.getValueAt(rowIndex, columnIndex - super.getNumFrozenColumns()); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { super.setValueAt(aValue, rowIndex, columnIndex - super.getNumFrozenColumns()); } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } }; } } public enum TmCompatibilityColumns { ID(-2, "id", CellTypes.INTEGER), NAME(-1, "name", CellTypes.STRING), TM(0, "name", CellTypes.CHECKBOX), NUMBER_OF_COLUMNS(1, null, null); private final int idx; private final String key; private final CellTypes cellType; int repetition; TmCompatibilityColumns(int idx, String key, CellTypes cellType) { this.idx = idx; this.key = key; this.cellType = cellType; } static TmCompatibilityColumns getColumn(int idx) { for (TmCompatibilityColumns column : TmCompatibilityColumns.values()) { if (column.idx == idx) { return column; } } return NUMBER_OF_COLUMNS; } } public void setupEditableHeader() { String[] moveNames = getFormatModel().getTextBankData().get(TextFiles.MOVE_NAMES.getValue()).getStringList().toArray(String[]::new); tableHeader.setEnabled(true); tableHeader.addMouseListener(new MouseAdapter(){ @Override public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2) { int columnIndex = tableHeader.columnAtPoint(event.getPoint()); if (columnIndex >= 0) { TableColumn column = tableHeader.getColumnModel().getColumn(columnIndex); Rectangle rect = tableHeader.getHeaderRect(columnIndex); JPopupMenu popupMenu = new JPopupMenu(); DefaultListModel<EditorComboBox.ComboBoxItem> items = new DefaultListModel<>(); for (String moveName : moveNames) { items.addElement(new EditorComboBox.ComboBoxItem(moveName)); } JList<EditorComboBox.ComboBoxItem> list = new JList<>(items); list.setSelectedIndex(PersonalParser.tmMoveIdNumbers[columnIndex]); list.addListSelectionListener(e -> {
PersonalParser.updateTmType(columnIndex, list.getSelectedIndex(), DataManager.getData(null, MoveData.class));
0
2023-10-15 05:00:57+00:00
12k
eclipse-egit/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/op/DeleteBranchOperation.java
[ { "identifier": "Activator", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/Activator.java", "snippet": "public class Activator extends Plugin {\n\n\t/** The plug-in ID for Egit core. */\n\tpublic static final String PLUGIN_ID = \"org.eclipse.egit.core\"; //$NON-NLS-1$\n\n\tprivate static Acti...
import static java.util.Arrays.asList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.egit.core.Activator; import org.eclipse.egit.core.EclipseGitProgressTransformer; import org.eclipse.egit.core.internal.CoreText; import org.eclipse.egit.core.internal.job.RuleUtil; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.errors.CannotDeleteCurrentBranchException; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.api.errors.JGitInternalException; import org.eclipse.jgit.api.errors.NotMergedException; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.osgi.util.NLS;
9,058
/******************************************************************************* * Copyright (C) 2010, 2023 Mathias Kinzler <mathias.kinzler@sap.com> and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Lars Vogel <Lars.Vogel@vogella.com> - Bug 497630 *******************************************************************************/ package org.eclipse.egit.core.op; /** * This class implements deletion of a branch. */ public class DeleteBranchOperation implements IEGitOperation { /** Operation was performed */ public final static int OK = 0; /** Current branch cannot be deleted */ public final static int REJECTED_CURRENT = 1; /** * Branch to be deleted has not been fully merged; use force to delete * anyway */ public final static int REJECTED_UNMERGED = 2; /** This operation was not executed yet */ public final static int NOT_TRIED = -1; private int status = NOT_TRIED; private final Repository repository; private final Set<Ref> branches; private final boolean force; /** * @param repository * @param branch * the branch to delete * @param force */ public DeleteBranchOperation(Repository repository, Ref branch, boolean force) { this(repository, new HashSet<>(asList(branch)), force); } /** * @param repository * @param branches * the list of branches to deleted * @param force */ public DeleteBranchOperation(Repository repository, Set<Ref> branches, boolean force) { this.repository = repository; this.branches = branches; this.force = force; } /** * @return one of {@link #OK}, {@link #REJECTED_CURRENT}, * {@link #REJECTED_UNMERGED}, {@link #NOT_TRIED} */ public int getStatus() { return status; } @Override public void execute(IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { String taskName; List<String> branchNames = branches.stream().map(Ref::getName) .collect(Collectors.toList()); if (branchNames.size() == 1) { taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, branchNames.get(0)); } else { String names = branchNames.stream() .collect(Collectors.joining(", ")); //$NON-NLS-1$ taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, names); } SubMonitor progress = SubMonitor.convert(actMonitor, taskName, branches.size()); try (Git git = new Git(repository)) { git.branchDelete() .setBranchNames(branchNames) .setForce(force) .setProgressMonitor( new EclipseGitProgressTransformer(progress)) .call(); status = OK; } catch (NotMergedException e) { status = REJECTED_UNMERGED; } catch (CannotDeleteCurrentBranchException e) { status = REJECTED_CURRENT; } catch (JGitInternalException | GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } if (progress.isCanceled()) { throw new OperationCanceledException( CoreText.DeleteBranchOperation_Canceled); } } }; // lock workspace to protect working tree changes ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); } @Override public ISchedulingRule getSchedulingRule() {
/******************************************************************************* * Copyright (C) 2010, 2023 Mathias Kinzler <mathias.kinzler@sap.com> and others * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Lars Vogel <Lars.Vogel@vogella.com> - Bug 497630 *******************************************************************************/ package org.eclipse.egit.core.op; /** * This class implements deletion of a branch. */ public class DeleteBranchOperation implements IEGitOperation { /** Operation was performed */ public final static int OK = 0; /** Current branch cannot be deleted */ public final static int REJECTED_CURRENT = 1; /** * Branch to be deleted has not been fully merged; use force to delete * anyway */ public final static int REJECTED_UNMERGED = 2; /** This operation was not executed yet */ public final static int NOT_TRIED = -1; private int status = NOT_TRIED; private final Repository repository; private final Set<Ref> branches; private final boolean force; /** * @param repository * @param branch * the branch to delete * @param force */ public DeleteBranchOperation(Repository repository, Ref branch, boolean force) { this(repository, new HashSet<>(asList(branch)), force); } /** * @param repository * @param branches * the list of branches to deleted * @param force */ public DeleteBranchOperation(Repository repository, Set<Ref> branches, boolean force) { this.repository = repository; this.branches = branches; this.force = force; } /** * @return one of {@link #OK}, {@link #REJECTED_CURRENT}, * {@link #REJECTED_UNMERGED}, {@link #NOT_TRIED} */ public int getStatus() { return status; } @Override public void execute(IProgressMonitor monitor) throws CoreException { IWorkspaceRunnable action = new IWorkspaceRunnable() { @Override public void run(IProgressMonitor actMonitor) throws CoreException { String taskName; List<String> branchNames = branches.stream().map(Ref::getName) .collect(Collectors.toList()); if (branchNames.size() == 1) { taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, branchNames.get(0)); } else { String names = branchNames.stream() .collect(Collectors.joining(", ")); //$NON-NLS-1$ taskName = NLS.bind( CoreText.DeleteBranchOperation_TaskName, names); } SubMonitor progress = SubMonitor.convert(actMonitor, taskName, branches.size()); try (Git git = new Git(repository)) { git.branchDelete() .setBranchNames(branchNames) .setForce(force) .setProgressMonitor( new EclipseGitProgressTransformer(progress)) .call(); status = OK; } catch (NotMergedException e) { status = REJECTED_UNMERGED; } catch (CannotDeleteCurrentBranchException e) { status = REJECTED_CURRENT; } catch (JGitInternalException | GitAPIException e) { throw new CoreException(Activator.error(e.getMessage(), e)); } if (progress.isCanceled()) { throw new OperationCanceledException( CoreText.DeleteBranchOperation_Canceled); } } }; // lock workspace to protect working tree changes ResourcesPlugin.getWorkspace().run(action, getSchedulingRule(), IWorkspace.AVOID_UPDATE, monitor); } @Override public ISchedulingRule getSchedulingRule() {
return RuleUtil.getRule(repository);
3
2023-10-20 15:17:51+00:00
12k
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java
src/main/application/driver/adapter/usecase/Game.java
[ { "identifier": "BigBoard", "path": "src/main/application/driver/adapter/usecase/board/BigBoard.java", "snippet": "public class BigBoard implements BoardCollection<Enemy> {\n private final Enemy[][] squares;\n private final PatternsIterator<Enemy> iterator;\n private static final int ROWS = 8;\...
import java.util.ArrayList; import java.util.List; import main.application.driver.adapter.usecase.board.BigBoard; import main.application.driver.adapter.usecase.expression.ConjunctionExpression; import main.application.driver.adapter.usecase.expression.Context; import main.application.driver.adapter.usecase.expression.AlternativeExpression; import main.application.driver.adapter.usecase.expression.EnemyExpression; import main.application.driver.adapter.usecase.factory_enemies.EnemyBasicMethod; import main.application.driver.adapter.usecase.factory_enemies.EnemyHighMethod; import main.application.driver.adapter.usecase.factory_enemies.EnemyMiddleMethod; import main.application.driver.adapter.usecase.mission.BasicMission; import main.application.driver.adapter.usecase.mission.HighMission; import main.application.driver.adapter.usecase.mission.MiddleMission; import main.application.driver.port.usecase.EnemyMethod; import main.application.driver.port.usecase.Expression; import main.application.driver.port.usecase.GameableUseCase; import main.application.driver.port.usecase.iterator.BoardCollection; import main.application.driver.port.usecase.iterator.PatternsIterator; import main.domain.model.ArmyFactory; import main.domain.model.CaretakerPlayer; import main.domain.model.Command; import main.domain.model.Enemy; import main.domain.model.FavorableEnvironment; import main.domain.model.Healable; import main.domain.model.Mission; import main.domain.model.Player; import main.domain.model.Player.MementoPlayer; import main.domain.model.command.Attack; import main.domain.model.command.HealingPlayer; import main.domain.model.Visitor;
7,385
package main.application.driver.adapter.usecase; public class Game implements GameableUseCase { private final ArmyFactory armyFactory; private EnemyMethod enemyMethod; private final Player player; private BoardCollection<Enemy> board; private PatternsIterator<Enemy> enemyIterator; private FavorableEnvironment favorableEnvironments; private final Frostbite frostbite; private final CaretakerPlayer caretakerPlayer; private Mission mission; private int level; public Game(final ArmyFactory armyFactory, final Player player) { this.armyFactory = armyFactory; this.player = player; this.frostbite = new Frostbite(); this.caretakerPlayer = new CaretakerPlayer(); } @Override public void startGame() { this.enemyMethod = new EnemyBasicMethod(armyFactory); this.board = new BigBoard(this.enemyMethod.createEnemies()); this.enemyIterator = this.board.getIterator(); this.mission = new BasicMission(this.board); this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments(); this.level = 1; } @Override public boolean verifyAnUpLevel() { if (this.mission.isMissionComplete()) { if (this.level == 1) {
package main.application.driver.adapter.usecase; public class Game implements GameableUseCase { private final ArmyFactory armyFactory; private EnemyMethod enemyMethod; private final Player player; private BoardCollection<Enemy> board; private PatternsIterator<Enemy> enemyIterator; private FavorableEnvironment favorableEnvironments; private final Frostbite frostbite; private final CaretakerPlayer caretakerPlayer; private Mission mission; private int level; public Game(final ArmyFactory armyFactory, final Player player) { this.armyFactory = armyFactory; this.player = player; this.frostbite = new Frostbite(); this.caretakerPlayer = new CaretakerPlayer(); } @Override public void startGame() { this.enemyMethod = new EnemyBasicMethod(armyFactory); this.board = new BigBoard(this.enemyMethod.createEnemies()); this.enemyIterator = this.board.getIterator(); this.mission = new BasicMission(this.board); this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments(); this.level = 1; } @Override public boolean verifyAnUpLevel() { if (this.mission.isMissionComplete()) { if (this.level == 1) {
this.enemyMethod = new EnemyMiddleMethod(armyFactory);
7
2023-10-20 18:36:47+00:00
12k
Squawkykaka/when_pigs_fly
src/main/java/com/squawkykaka/when_pigs_fly/WhenPigsFly.java
[ { "identifier": "Heal_Feed", "path": "src/main/java/com/squawkykaka/when_pigs_fly/commands/Heal_Feed.java", "snippet": "public class Heal_Feed {\n public Heal_Feed() {\n new CommandBase(\"heal\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String ...
import com.squawkykaka.when_pigs_fly.commands.Heal_Feed; import com.squawkykaka.when_pigs_fly.commands.Menu; import com.squawkykaka.when_pigs_fly.commands.Spawn; import com.squawkykaka.when_pigs_fly.util.EventUtil; import com.squawkykaka.when_pigs_fly.util.Metrics; import org.bukkit.plugin.java.JavaPlugin;
9,215
package com.squawkykaka.when_pigs_fly; public final class WhenPigsFly extends JavaPlugin { private static WhenPigsFly instance; @Override public void onEnable() { instance = this; // Set the instance to the current plugin saveDefaultConfig(); getLogger().info("------------------------"); getLogger().info("---- Plugin Loading ----"); EventUtil.register(new AxolotlThrowListener(this)); EventUtil.register(new PluginEvents());
package com.squawkykaka.when_pigs_fly; public final class WhenPigsFly extends JavaPlugin { private static WhenPigsFly instance; @Override public void onEnable() { instance = this; // Set the instance to the current plugin saveDefaultConfig(); getLogger().info("------------------------"); getLogger().info("---- Plugin Loading ----"); EventUtil.register(new AxolotlThrowListener(this)); EventUtil.register(new PluginEvents());
new Heal_Feed();
0
2023-10-17 02:07:39+00:00
12k
greatwqs/finance-manager
src/main/java/com/github/greatwqs/app/service/impl/OrderExcelServiceImpl.java
[ { "identifier": "AppConstants", "path": "src/main/java/com/github/greatwqs/app/common/AppConstants.java", "snippet": "public class AppConstants {\n\n // default locale\n public static final Locale LOCALE = new Locale(\"zh\", \"CN\");\n\n /**\n * ErrorCode i18n properties prefix key.\n *...
import com.github.greatwqs.app.common.AppConstants; import com.github.greatwqs.app.domain.dto.OrderDownloadDto; import com.github.greatwqs.app.domain.dto.OrderDto; import com.github.greatwqs.app.domain.po.UserPo; import com.github.greatwqs.app.domain.vo.OrderVo; import com.github.greatwqs.app.domain.vo.SubjectVo; import com.github.greatwqs.app.domain.vo.TicketTypeVo; import com.github.greatwqs.app.manager.SubjectManager; import com.github.greatwqs.app.manager.TicketTypeManager; import com.github.greatwqs.app.mapper.OrderlistMapper; import com.github.greatwqs.app.service.OrderExcelService; import com.github.greatwqs.app.service.OrderService; import com.github.greatwqs.app.utils.JsonUtil; import com.github.greatwqs.app.utils.UrlUtil; import com.github.greatwqs.app.utils.collection.Lists; import com.github.greatwqs.app.utils.excel.ExcelExport; import com.github.greatwqs.app.utils.excel.ExcelParseUtil; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Workbook; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.util.*; import java.util.stream.Collectors;
8,397
package com.github.greatwqs.app.service.impl; /** * @author greatwqs * Create on 2020/7/9 */ @Slf4j @Service public class OrderExcelServiceImpl implements OrderExcelService { @Autowired private ModelMapper modelMapper; @Autowired private OrderlistMapper orderlistMapper; @Autowired private SubjectManager subjectManager; @Autowired private TicketTypeManager ticketTypeManager; @Autowired private OrderService orderService; @Override public void download(HttpServletResponse response, OrderDownloadDto downloadDto, UserPo userPo) throws IOException { // orderVoList to ExcelExport List<OrderVo> orderVoList = orderService.queryDownload(downloadDto, userPo); ExcelExport<OrderVo> excelExport = buildExcelExport(orderVoList); // response response.setContentType("application/msexcel;charset=UTF-8"); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, this.buildFileDownloadHeader(excelExport.getFileName())); excelExport.downloadExcel(response.getOutputStream()); } /*** * http response header file name. * @param fileName * @return */ private String buildFileDownloadHeader(String fileName) { return "attachment;filename*=UTF-8''" + UrlUtil.escapeContentDisposition(fileName); } /*** * 构建 Excel 导出数据 * @param orderVoList * @return */ private ExcelExport<OrderVo> buildExcelExport(List<OrderVo> orderVoList) { ExcelExport<OrderVo> excelExport = initExcelExport(); final String sheetName = "收支信息汇总表"; HSSFWorkbook workbook = excelExport.toExcel(sheetName, orderVoList); excelExport.setHssfWorkbook(workbook); excelExport.setSheetName(sheetName); excelExport.setFileName(this.buildFileName()); return excelExport; } /** * 导出文件名称 * * @return */ private String buildFileName() { final String dateTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd"); return "收支信息_$DATE.xls".replace("$DATE", dateTime); } /*** * 初始化导出 Excel 的表头 * @return */ private ExcelExport<OrderVo> initExcelExport() { ExcelExport<OrderVo> excelExport = new ExcelExport<>(); excelExport.setDateFormat("yyyy-MM-dd"); excelExport.setTargetTimeZone(TimeZone.getDefault()); excelExport.setLocale(AppConstants.LOCALE); excelExport.putCreateExcelRule("时间", OrderVo::getOrdertime); excelExport.putCreateExcelRule("缴费/收款人", OrderVo::getOrderaccount); excelExport.putCreateExcelRule("项目", OrderVo::getSubjectName); excelExport.putCreateExcelRule("金额", OrderVo::getOrderprice); excelExport.putCreateExcelRule("票据", OrderVo::getTicketTypeName); excelExport.putCreateExcelRule("票据号", OrderVo::getTicketno); excelExport.putCreateExcelRule("收支方式", OrderVo::getPaytype); excelExport.putCreateExcelRule("备注", OrderVo::getOrderdes); excelExport.putCreateExcelRule("班级", OrderVo::getOrderclass); return excelExport; } /*** * Excel 表单数据上传 * 表列: 0-时间, 1-缴费/收款人, 2-项目, 3-金额, 4-票据, 5-票据号, 6-收支方式, 7-备注, 8-班级 * * @param file * @param userPo * @throws IOException */ @Override @Transactional public void upload(MultipartFile file, UserPo userPo) throws IOException, ParseException { final int columnNum = 9; final Workbook workbook = ExcelParseUtil.getWorkBook(file); final List<String[]> excelDataRowTempList = ExcelParseUtil.readExcel(workbook, columnNum); // if any excelDataRow empty, filter it. final List<String[]> excelDataRowList = excelDataRowTempList.stream() .filter(excelDataRow -> !containsEmptyElement(excelDataRow)) .collect(Collectors.toList()); log.info("excel upload api data: " + JsonUtil.toJson(excelDataRowList));
package com.github.greatwqs.app.service.impl; /** * @author greatwqs * Create on 2020/7/9 */ @Slf4j @Service public class OrderExcelServiceImpl implements OrderExcelService { @Autowired private ModelMapper modelMapper; @Autowired private OrderlistMapper orderlistMapper; @Autowired private SubjectManager subjectManager; @Autowired private TicketTypeManager ticketTypeManager; @Autowired private OrderService orderService; @Override public void download(HttpServletResponse response, OrderDownloadDto downloadDto, UserPo userPo) throws IOException { // orderVoList to ExcelExport List<OrderVo> orderVoList = orderService.queryDownload(downloadDto, userPo); ExcelExport<OrderVo> excelExport = buildExcelExport(orderVoList); // response response.setContentType("application/msexcel;charset=UTF-8"); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, this.buildFileDownloadHeader(excelExport.getFileName())); excelExport.downloadExcel(response.getOutputStream()); } /*** * http response header file name. * @param fileName * @return */ private String buildFileDownloadHeader(String fileName) { return "attachment;filename*=UTF-8''" + UrlUtil.escapeContentDisposition(fileName); } /*** * 构建 Excel 导出数据 * @param orderVoList * @return */ private ExcelExport<OrderVo> buildExcelExport(List<OrderVo> orderVoList) { ExcelExport<OrderVo> excelExport = initExcelExport(); final String sheetName = "收支信息汇总表"; HSSFWorkbook workbook = excelExport.toExcel(sheetName, orderVoList); excelExport.setHssfWorkbook(workbook); excelExport.setSheetName(sheetName); excelExport.setFileName(this.buildFileName()); return excelExport; } /** * 导出文件名称 * * @return */ private String buildFileName() { final String dateTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd"); return "收支信息_$DATE.xls".replace("$DATE", dateTime); } /*** * 初始化导出 Excel 的表头 * @return */ private ExcelExport<OrderVo> initExcelExport() { ExcelExport<OrderVo> excelExport = new ExcelExport<>(); excelExport.setDateFormat("yyyy-MM-dd"); excelExport.setTargetTimeZone(TimeZone.getDefault()); excelExport.setLocale(AppConstants.LOCALE); excelExport.putCreateExcelRule("时间", OrderVo::getOrdertime); excelExport.putCreateExcelRule("缴费/收款人", OrderVo::getOrderaccount); excelExport.putCreateExcelRule("项目", OrderVo::getSubjectName); excelExport.putCreateExcelRule("金额", OrderVo::getOrderprice); excelExport.putCreateExcelRule("票据", OrderVo::getTicketTypeName); excelExport.putCreateExcelRule("票据号", OrderVo::getTicketno); excelExport.putCreateExcelRule("收支方式", OrderVo::getPaytype); excelExport.putCreateExcelRule("备注", OrderVo::getOrderdes); excelExport.putCreateExcelRule("班级", OrderVo::getOrderclass); return excelExport; } /*** * Excel 表单数据上传 * 表列: 0-时间, 1-缴费/收款人, 2-项目, 3-金额, 4-票据, 5-票据号, 6-收支方式, 7-备注, 8-班级 * * @param file * @param userPo * @throws IOException */ @Override @Transactional public void upload(MultipartFile file, UserPo userPo) throws IOException, ParseException { final int columnNum = 9; final Workbook workbook = ExcelParseUtil.getWorkBook(file); final List<String[]> excelDataRowTempList = ExcelParseUtil.readExcel(workbook, columnNum); // if any excelDataRow empty, filter it. final List<String[]> excelDataRowList = excelDataRowTempList.stream() .filter(excelDataRow -> !containsEmptyElement(excelDataRow)) .collect(Collectors.toList()); log.info("excel upload api data: " + JsonUtil.toJson(excelDataRowList));
final List<OrderDto> orderDtoList = parseToOrderDtoList(excelDataRowList, userPo.getId());
2
2023-10-16 12:45:57+00:00
12k
Wind-Gone/Vodka
code/src/main/java/utils/load/LoadDataWorker.java
[ { "identifier": "NationData", "path": "code/src/main/java/benchmark/olap/data/NationData.java", "snippet": "public class NationData {\n public static Integer[] nationKey = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24};\n public static String[] nationNam...
import benchmark.olap.data.NationData; import benchmark.olap.data.RegionData; import utils.math.random.BasicRandom; import org.apache.log4j.Logger; import java.sql.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.io.*; import java.util.Date;
7,524
"VALUES (?, ?, ?)" ); stmtRegion = dbConn.prepareStatement( "insert into vodka_region (r_regionkey,r_name,r_comment) values (?,?,?)" ); stmtNation = dbConn.prepareStatement( "insert into vodka_nation (n_nationkey,n_name,n_regionkey,n_comment) values (?,?,?,?)" ); stmtSupplier = dbConn.prepareStatement( "insert into vodka_supplier (s_suppkey,s_nationkey,s_comment, s_name, s_address, s_acctbal, s_phone) values (?, ?, ?, ?, ?, ?, ?)" ); } /* * run() */ public void run() { int job; try { while ((job = LoadData.getNextJob()) >= 0) { if (job == 0) { fmt.format("Worker %03d: Loading Item", worker); System.out.println(sb.toString()); sb.setLength(0); loadItem(); fmt.format("Worker %03d: Loading Item done", worker); System.out.println(sb.toString()); sb.setLength(0); fmt.format("Worker %03d: Loading Nation", worker); System.out.println(sb.toString()); sb.setLength(0); loadNation(); fmt.format("Worker %03d: Loading Nation done", worker); System.out.println(sb.toString()); sb.setLength(0); fmt.format("Worker %03d: Loading Region", worker); System.out.println(sb.toString()); sb.setLength(0); loadRegion(); fmt.format("Worker %03d: Loading Region done", worker); System.out.println(sb.toString()); sb.setLength(0); fmt.format("Worker %03d: Loading Supplier", worker); System.out.println(sb.toString()); sb.setLength(0); loadSupplier(); fmt.format("Worker %03d: Loading Supplier done", worker); System.out.println(sb.toString()); sb.setLength(0); } else { fmt.format("Worker %03d: Loading Warehouse %6d", worker, job); System.out.println(sb.toString()); sb.setLength(0); loadWarehouse(job); fmt.format("Worker %03d: Loading Warehouse %6d done", worker, job); } System.out.println(sb.toString()); sb.setLength(0); } /* * Close the DB connection if in direct DB mode. */ if (!writeCSV) dbConn.close(); } catch (SQLException se) { log.info("LoadDataWorker.java: " + getSQLExceptionInfo(se)); SQLException throwables = se; while (throwables != null) { fmt.format("Worker %03d: ERROR: %s", worker, throwables.getMessage()); System.err.println(sb.toString()); sb.setLength(0); throwables = throwables.getNextException(); } } catch (Exception e) { fmt.format("Worker %03d: ERROR: %s", worker, e.getMessage()); System.err.println(sb.toString()); sb.setLength(0); e.printStackTrace(); } } // End run() private void loadRegion() { try { int arraySize = RegionData.regionKey.length; if (arraySize > 0) { for (int i = 0; i < RegionData.regionKey.length; i++) { stmtRegion.setInt(1, RegionData.regionKey[i]); stmtRegion.setString(2, RegionData.regionName[i]); stmtRegion.setString(3, rnd.getAString(31, 115)); stmtRegion.addBatch(); } } stmtRegion.executeBatch(); stmtRegion.clearBatch(); dbConn.commit(); } catch (SQLException e) { e.printStackTrace(); } } private void loadNation() { try {
package utils.load;/* * LoadDataWorker - Class to utils.load one Warehouse (or in a special case * the ITEM table). * * * */ public class LoadDataWorker implements Runnable { private static Logger log = Logger.getLogger(LoadDataWorker.class); private int worker; private Connection dbConn; private BasicRandom rnd; private StringBuffer sb; private Formatter fmt; private boolean writeCSV = false; private String csvNull = null; private PreparedStatement stmtConfig = null; private PreparedStatement stmtItem = null; private PreparedStatement stmtWarehouse = null; private PreparedStatement stmtDistrict = null; private PreparedStatement stmtStock = null; private PreparedStatement stmtCustomer = null; private PreparedStatement stmtHistory = null; private PreparedStatement stmtOrder = null; private PreparedStatement stmtOrderLine = null; private PreparedStatement stmtNewOrder = null; private PreparedStatement stmtRegion = null; private PreparedStatement stmtNation = null; private PreparedStatement stmtSupplier = null; private StringBuffer sbConfig = null; private Formatter fmtConfig = null; private StringBuffer sbItem = null; private Formatter fmtItem = null; private StringBuffer sbWarehouse = null; private Formatter fmtWarehouse = null; private StringBuffer sbDistrict = null; private Formatter fmtDistrict = null; private StringBuffer sbStock = null; private Formatter fmtStock = null; private StringBuffer sbCustomer = null; private Formatter fmtCustomer = null; private StringBuffer sbHistory = null; private Formatter fmtHistory = null; private StringBuffer sbOrder = null; private Formatter fmtOrder = null; private StringBuffer sbOrderLine = null; private Formatter fmtOrderLine = null; private StringBuffer sbNewOrder = null; private Formatter fmtNewOrder = null; LoadDataWorker(int worker, String csvNull, BasicRandom rnd) { this.worker = worker; this.csvNull = csvNull; this.rnd = rnd; this.sb = new StringBuffer(); this.fmt = new Formatter(sb); this.writeCSV = true; this.sbConfig = new StringBuffer(); this.fmtConfig = new Formatter(sbConfig); this.sbItem = new StringBuffer(); this.fmtItem = new Formatter(sbItem); this.sbWarehouse = new StringBuffer(); this.fmtWarehouse = new Formatter(sbWarehouse); this.sbDistrict = new StringBuffer(); this.fmtDistrict = new Formatter(sbDistrict); this.sbStock = new StringBuffer(); this.fmtStock = new Formatter(sbStock); this.sbCustomer = new StringBuffer(); this.fmtCustomer = new Formatter(sbCustomer); this.sbHistory = new StringBuffer(); this.fmtHistory = new Formatter(sbHistory); this.sbOrder = new StringBuffer(); this.fmtOrder = new Formatter(sbOrder); this.sbOrderLine = new StringBuffer(); this.fmtOrderLine = new Formatter(sbOrderLine); this.sbNewOrder = new StringBuffer(); this.fmtNewOrder = new Formatter(sbNewOrder); } LoadDataWorker(int worker, Connection dbConn, BasicRandom rnd) throws SQLException { this.worker = worker; this.dbConn = dbConn; this.rnd = rnd; this.sb = new StringBuffer(); this.fmt = new Formatter(sb); stmtConfig = dbConn.prepareStatement( "INSERT INTO vodka_config (" + " cfg_name, cfg_value) " + "VALUES (?, ?)" ); stmtItem = dbConn.prepareStatement( "INSERT INTO vodka_item (" + " i_id, i_im_id, i_name, i_price, i_data, i_container, i_size, i_brand, i_type, i_mfgr) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); stmtWarehouse = dbConn.prepareStatement( "INSERT INTO vodka_warehouse (" + " w_id, w_name, w_street_1, w_street_2, w_city, " + " w_state, w_zip, w_tax, w_ytd) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" ); stmtStock = dbConn.prepareStatement( "INSERT INTO vodka_stock (" + " s_i_id, s_w_id, s_quantity, s_dist_01, s_dist_02, " + " s_dist_03, s_dist_04, s_dist_05, s_dist_06, " + " s_dist_07, s_dist_08, s_dist_09, s_dist_10, " + " s_ytd, s_order_cnt, s_remote_cnt, s_data, s_supplycost,s_tocksuppkey) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); stmtDistrict = dbConn.prepareStatement( "INSERT INTO vodka_district (" + " d_id, d_w_id, d_name, d_street_1, d_street_2, " + " d_city, d_state, d_zip, d_tax, d_ytd, d_next_o_id) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); stmtCustomer = dbConn.prepareStatement( "INSERT INTO vodka_customer (" + " c_id, c_d_id, c_w_id, c_first, c_middle, c_last, " + " c_street_1, c_street_2, c_city, c_nationkey, c_zip, " + " c_phone, c_since, c_credit, c_credit_lim, c_discount, " + " c_balance, c_ytd_payment, c_payment_cnt, " + " c_delivery_cnt, c_data, c_mktsegment) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + " ?, ?, ?, ?, ?, ?, ?)" ); stmtHistory = dbConn.prepareStatement( "INSERT INTO vodka_history (" + " h_c_id, h_c_d_id, h_c_w_id, h_d_id, h_w_id, " + " h_date, h_amount, h_data) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)" ); stmtOrder = dbConn.prepareStatement( "INSERT INTO vodka_oorder (" + " o_id, o_d_id, o_w_id, o_c_id, o_entry_d, " + " o_carrier_id, o_ol_cnt, o_all_local, o_comment, o_shippriority) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); stmtOrderLine = dbConn.prepareStatement( "INSERT INTO vodka_order_line (" + " ol_o_id, ol_d_id, ol_w_id, ol_number, ol_i_id, " + " ol_supply_w_id, ol_delivery_d, ol_quantity, " + " ol_amount, ol_dist_info, ol_discount, ol_shipmode," + " ol_shipinstruct, ol_receipdate, ol_commitdate, ol_returnflag, ol_suppkey, ol_tax, access_version) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); stmtNewOrder = dbConn.prepareStatement( "INSERT INTO vodka_new_order (" + " no_o_id, no_d_id, no_w_id) " + "VALUES (?, ?, ?)" ); stmtRegion = dbConn.prepareStatement( "insert into vodka_region (r_regionkey,r_name,r_comment) values (?,?,?)" ); stmtNation = dbConn.prepareStatement( "insert into vodka_nation (n_nationkey,n_name,n_regionkey,n_comment) values (?,?,?,?)" ); stmtSupplier = dbConn.prepareStatement( "insert into vodka_supplier (s_suppkey,s_nationkey,s_comment, s_name, s_address, s_acctbal, s_phone) values (?, ?, ?, ?, ?, ?, ?)" ); } /* * run() */ public void run() { int job; try { while ((job = LoadData.getNextJob()) >= 0) { if (job == 0) { fmt.format("Worker %03d: Loading Item", worker); System.out.println(sb.toString()); sb.setLength(0); loadItem(); fmt.format("Worker %03d: Loading Item done", worker); System.out.println(sb.toString()); sb.setLength(0); fmt.format("Worker %03d: Loading Nation", worker); System.out.println(sb.toString()); sb.setLength(0); loadNation(); fmt.format("Worker %03d: Loading Nation done", worker); System.out.println(sb.toString()); sb.setLength(0); fmt.format("Worker %03d: Loading Region", worker); System.out.println(sb.toString()); sb.setLength(0); loadRegion(); fmt.format("Worker %03d: Loading Region done", worker); System.out.println(sb.toString()); sb.setLength(0); fmt.format("Worker %03d: Loading Supplier", worker); System.out.println(sb.toString()); sb.setLength(0); loadSupplier(); fmt.format("Worker %03d: Loading Supplier done", worker); System.out.println(sb.toString()); sb.setLength(0); } else { fmt.format("Worker %03d: Loading Warehouse %6d", worker, job); System.out.println(sb.toString()); sb.setLength(0); loadWarehouse(job); fmt.format("Worker %03d: Loading Warehouse %6d done", worker, job); } System.out.println(sb.toString()); sb.setLength(0); } /* * Close the DB connection if in direct DB mode. */ if (!writeCSV) dbConn.close(); } catch (SQLException se) { log.info("LoadDataWorker.java: " + getSQLExceptionInfo(se)); SQLException throwables = se; while (throwables != null) { fmt.format("Worker %03d: ERROR: %s", worker, throwables.getMessage()); System.err.println(sb.toString()); sb.setLength(0); throwables = throwables.getNextException(); } } catch (Exception e) { fmt.format("Worker %03d: ERROR: %s", worker, e.getMessage()); System.err.println(sb.toString()); sb.setLength(0); e.printStackTrace(); } } // End run() private void loadRegion() { try { int arraySize = RegionData.regionKey.length; if (arraySize > 0) { for (int i = 0; i < RegionData.regionKey.length; i++) { stmtRegion.setInt(1, RegionData.regionKey[i]); stmtRegion.setString(2, RegionData.regionName[i]); stmtRegion.setString(3, rnd.getAString(31, 115)); stmtRegion.addBatch(); } } stmtRegion.executeBatch(); stmtRegion.clearBatch(); dbConn.commit(); } catch (SQLException e) { e.printStackTrace(); } } private void loadNation() { try {
int arraySize = NationData.nationKey.length;
0
2023-10-22 11:22:32+00:00
12k
ushh789/FinancialCalculator
src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/Credit.java
[ { "identifier": "LogHelper", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/LogHelper.java", "snippet": "public class LogHelper {\n\n // Додаємо об'єкт логування\n private static final Logger logger = Logger.getLogger(LogHelper.class.getName());\n\n ...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper; import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.Savable; import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DateTimeFunctions; import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.LocalDateAdapter; import com.netrunners.financialcalculator.MenuControllers.ResultTableController; import com.netrunners.financialcalculator.StartMenu; import com.netrunners.financialcalculator.VisualInstruments.MenuActions.LanguageManager; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.time.LocalDate; import java.util.logging.Level;
10,583
package com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit; public class Credit implements Savable { protected float loan; protected String currency; protected float annualPercent; protected LocalDate startDate; protected LocalDate endDate; protected int paymentType; protected int contractDuration; public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) { this.loan = loan; this.currency = currency; this.annualPercent = annualPercent; this.startDate = startDate; this.endDate = endDate; this.paymentType = paymentType; this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate); } public float countLoan() { return loan * (1f / 365f) * (annualPercent / 100f); } public float countCreditBodyPerDay(){ return loan/contractDuration; } public void save() { Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); JsonObject jsonObject = getJsonObject(); String json = gson.toJson(jsonObject); FileChooser fileChooser = new FileChooser();
package com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit; public class Credit implements Savable { protected float loan; protected String currency; protected float annualPercent; protected LocalDate startDate; protected LocalDate endDate; protected int paymentType; protected int contractDuration; public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) { this.loan = loan; this.currency = currency; this.annualPercent = annualPercent; this.startDate = startDate; this.endDate = endDate; this.paymentType = paymentType; this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate); } public float countLoan() { return loan * (1f / 365f) * (annualPercent / 100f); } public float countCreditBodyPerDay(){ return loan/contractDuration; } public void save() { Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create(); JsonObject jsonObject = getJsonObject(); String json = gson.toJson(jsonObject); FileChooser fileChooser = new FileChooser();
fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveButton").get());
6
2023-10-18 16:03:09+00:00
12k
Kyrotechnic/KyroClient
Client/src/main/java/me/kyroclient/mixins/render/MixinItemRenderer.java
[ { "identifier": "KyroClient", "path": "Client/src/main/java/me/kyroclient/KyroClient.java", "snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public stati...
import me.kyroclient.KyroClient; import me.kyroclient.modules.combat.Aura; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.EnumAction; import net.minecraft.item.ItemMap; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import org.lwjgl.opengl.GL11; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; import org.spongepowered.asm.mixin.Shadow;
7,512
package me.kyroclient.mixins.render; @Mixin(value = { ItemRenderer.class }, priority = 1) public abstract class MixinItemRenderer { @Shadow private float prevEquippedProgress; @Shadow private float equippedProgress; @Shadow @Final private Minecraft mc; @Shadow private ItemStack itemToRender; @Shadow protected abstract void rotateArroundXAndY(final float p0, final float p1); @Shadow protected abstract void setLightMapFromPlayer(final AbstractClientPlayer p0); @Shadow protected abstract void rotateWithPlayerRotations(final EntityPlayerSP p0, final float p1); @Shadow protected abstract void renderItemMap(final AbstractClientPlayer p0, final float p1, final float p2, final float p3); @Shadow protected abstract void performDrinking(final AbstractClientPlayer p0, final float p1); @Shadow protected abstract void doItemUsedTransformations(final float p0); @Shadow public abstract void renderItem(final EntityLivingBase p0, final ItemStack p1, final ItemCameraTransforms.TransformType p2); @Shadow protected abstract void renderPlayerArm(final AbstractClientPlayer p0, final float p1, final float p2); @Shadow protected abstract void doBowTransformations(final float p0, final AbstractClientPlayer p1); /** * @author * @reason */ @Overwrite public void renderItemInFirstPerson(final float partialTicks) { final float f = 1.0f - (this.prevEquippedProgress + (this.equippedProgress - this.prevEquippedProgress) * partialTicks); final AbstractClientPlayer abstractclientplayer = (AbstractClientPlayer)this.mc.thePlayer; final float f2 = abstractclientplayer.getSwingProgress(partialTicks); final float f3 = abstractclientplayer.prevRotationPitch + (abstractclientplayer.rotationPitch - abstractclientplayer.prevRotationPitch) * partialTicks; final float f4 = abstractclientplayer.prevRotationYaw + (abstractclientplayer.rotationYaw - abstractclientplayer.prevRotationYaw) * partialTicks; this.rotateArroundXAndY(f3, f4); this.setLightMapFromPlayer(abstractclientplayer); this.rotateWithPlayerRotations((EntityPlayerSP)abstractclientplayer, partialTicks); GlStateManager.enableRescaleNormal(); GlStateManager.pushMatrix(); if (this.itemToRender != null) {
package me.kyroclient.mixins.render; @Mixin(value = { ItemRenderer.class }, priority = 1) public abstract class MixinItemRenderer { @Shadow private float prevEquippedProgress; @Shadow private float equippedProgress; @Shadow @Final private Minecraft mc; @Shadow private ItemStack itemToRender; @Shadow protected abstract void rotateArroundXAndY(final float p0, final float p1); @Shadow protected abstract void setLightMapFromPlayer(final AbstractClientPlayer p0); @Shadow protected abstract void rotateWithPlayerRotations(final EntityPlayerSP p0, final float p1); @Shadow protected abstract void renderItemMap(final AbstractClientPlayer p0, final float p1, final float p2, final float p3); @Shadow protected abstract void performDrinking(final AbstractClientPlayer p0, final float p1); @Shadow protected abstract void doItemUsedTransformations(final float p0); @Shadow public abstract void renderItem(final EntityLivingBase p0, final ItemStack p1, final ItemCameraTransforms.TransformType p2); @Shadow protected abstract void renderPlayerArm(final AbstractClientPlayer p0, final float p1, final float p2); @Shadow protected abstract void doBowTransformations(final float p0, final AbstractClientPlayer p1); /** * @author * @reason */ @Overwrite public void renderItemInFirstPerson(final float partialTicks) { final float f = 1.0f - (this.prevEquippedProgress + (this.equippedProgress - this.prevEquippedProgress) * partialTicks); final AbstractClientPlayer abstractclientplayer = (AbstractClientPlayer)this.mc.thePlayer; final float f2 = abstractclientplayer.getSwingProgress(partialTicks); final float f3 = abstractclientplayer.prevRotationPitch + (abstractclientplayer.rotationPitch - abstractclientplayer.prevRotationPitch) * partialTicks; final float f4 = abstractclientplayer.prevRotationYaw + (abstractclientplayer.rotationYaw - abstractclientplayer.prevRotationYaw) * partialTicks; this.rotateArroundXAndY(f3, f4); this.setLightMapFromPlayer(abstractclientplayer); this.rotateWithPlayerRotations((EntityPlayerSP)abstractclientplayer, partialTicks); GlStateManager.enableRescaleNormal(); GlStateManager.pushMatrix(); if (this.itemToRender != null) {
final boolean shouldSpoofBlocking = (Aura.target != null && !KyroClient.aura.blockMode.getSelected().equals("None")) || (!KyroClient.autoBlock.blockTimer.hasTimePassed((long)KyroClient.autoBlock.blockTime.getValue()) && KyroClient.autoBlock.canBlock());
0
2023-10-15 16:24:51+00:00
12k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/missions/quests/QuestTest.java
[ { "identifier": "EventHandler", "path": "source/core/src/main/com/csse3200/game/events/EventHandler.java", "snippet": "public class EventHandler {\n\tprivate static final Logger logger = LoggerFactory.getLogger(EventHandler.class);\n\tprivate final List<ScheduledEvent> scheduledEvents = new ArrayList<>(...
import com.badlogic.gdx.utils.JsonValue; import com.csse3200.game.events.EventHandler; import com.csse3200.game.missions.MissionManager; import com.csse3200.game.missions.rewards.Reward; import com.csse3200.game.services.GameTime; import com.csse3200.game.services.ServiceLocator; import com.csse3200.game.services.TimeService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*;
9,922
package com.csse3200.game.missions.quests; class QuestTest { private Reward r1, r2, r3, r4, r5; private Quest q1, q2, q3, q4, q5; @BeforeEach void preTest() {
package com.csse3200.game.missions.quests; class QuestTest { private Reward r1, r2, r3, r4, r5; private Quest q1, q2, q3, q4, q5; @BeforeEach void preTest() {
ServiceLocator.registerTimeSource(new GameTime());
3
2023-10-17 22:34:04+00:00
12k
LuckPerms/rest-api-java-client
src/test/java/me/lucko/luckperms/rest/UserServiceTest.java
[ { "identifier": "LuckPermsRestClient", "path": "src/main/java/net/luckperms/rest/LuckPermsRestClient.java", "snippet": "public interface LuckPermsRestClient extends AutoCloseable {\n\n /**\n * Creates a new client builder.\n *\n * @return the new builder\n */\n static Builder build...
import net.luckperms.rest.LuckPermsRestClient; import net.luckperms.rest.model.Context; import net.luckperms.rest.model.CreateGroupRequest; import net.luckperms.rest.model.CreateTrackRequest; import net.luckperms.rest.model.CreateUserRequest; import net.luckperms.rest.model.DemotionResult; import net.luckperms.rest.model.Group; import net.luckperms.rest.model.Metadata; import net.luckperms.rest.model.Node; import net.luckperms.rest.model.NodeType; import net.luckperms.rest.model.PermissionCheckRequest; import net.luckperms.rest.model.PermissionCheckResult; import net.luckperms.rest.model.PlayerSaveResult; import net.luckperms.rest.model.PromotionResult; import net.luckperms.rest.model.QueryOptions; import net.luckperms.rest.model.TemporaryNodeMergeStrategy; import net.luckperms.rest.model.TrackRequest; import net.luckperms.rest.model.UpdateTrackRequest; import net.luckperms.rest.model.UpdateUserRequest; import net.luckperms.rest.model.User; import net.luckperms.rest.model.UserLookupResult; import net.luckperms.rest.model.UserSearchResult; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.shaded.com.google.common.collect.ImmutableSet; import retrofit2.Response; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue;
7,340
new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime), new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null), new Node("suffix.100. test", true, Collections.emptySet(), null), new Node("meta.hello.world", true, Collections.emptySet(), null) )).execute().isSuccessful()); // searchNodesByKey Response<List<UserSearchResult>> resp1 = client.users().searchNodesByKey("test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("test.node.one", true, Collections.emptySet(), null))) ), resp1.body()); // searchNodesByKeyStartsWith Response<List<UserSearchResult>> resp2 = client.users().searchNodesByKeyStartsWith("test.node").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) )) ), resp2.body()); // searchNodesByMetaKey Response<List<UserSearchResult>> resp3 = client.users().searchNodesByMetaKey("hello").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("meta.hello.world", true, Collections.emptySet(), null))) ), resp3.body()); // searchNodesByType Response<List<UserSearchResult>> resp4 = client.users().searchNodesByType(NodeType.PREFIX).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null))) ), resp4.body()); } @Test public void testUserPermissionCheck() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null) )).execute().isSuccessful()); Response<PermissionCheckResult> resp0 = client.users().permissionCheck(uuid, "test.node.zero").execute(); assertTrue(resp0.isSuccessful()); assertNotNull(resp0.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp0.body().result()); assertNull(resp0.body().node()); Response<PermissionCheckResult> resp1 = client.users().permissionCheck(uuid, "test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp1.body().result()); assertEquals(new Node("test.node.one", true, Collections.emptySet(), null), resp1.body().node()); Response<PermissionCheckResult> resp2 = client.users().permissionCheck(uuid, "test.node.two").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(PermissionCheckResult.Tristate.FALSE, resp2.body().result()); assertEquals(new Node("test.node.two", false, Collections.emptySet(), null), resp2.body().node()); Response<PermissionCheckResult> resp3 = client.users().permissionCheck(uuid, "test.node.three").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp3.body().result()); assertNull(resp3.body().node()); Response<PermissionCheckResult> resp4 = client.users().permissionCheck(uuid, new PermissionCheckRequest( "test.node.three", new QueryOptions(null, null, ImmutableSet.of(new Context("server", "test"), new Context("world", "aaa"))) )).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp4.body().result()); assertEquals(new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), resp4.body().node()); } @Test public void testUserPromoteDemote() throws IOException { LuckPermsRestClient client = createClient(); // create a user UUID uuid = UUID.randomUUID(); String username = randomName(); assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // create a track String trackName = randomName(); assertTrue(client.tracks().create(new CreateTrackRequest(trackName)).execute().isSuccessful()); // create some groups Group group1 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group2 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group3 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); ImmutableList<String> groupNames = ImmutableList.of(group1.name(), group2.name(), group3.name()); // update the track assertTrue(client.tracks().update(trackName, new UpdateTrackRequest(groupNames)).execute().isSuccessful()); // promote the user along the track
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * 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 me.lucko.luckperms.rest; public class UserServiceTest extends AbstractIntegrationTest { @Test public void testUserCrud() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create Response<PlayerSaveResult> createResp = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp.isSuccessful()); assertEquals(201, createResp.code()); PlayerSaveResult result = createResp.body(); assertNotNull(result); // read Response<User> readResp = client.users().get(uuid).execute(); assertTrue(readResp.isSuccessful()); User user = readResp.body(); assertNotNull(user); assertEquals(uuid, user.uniqueId()); assertEquals(username, user.username()); // update Response<Void> updateResp = client.users().update(uuid, new UpdateUserRequest(randomName())).execute(); assertTrue(updateResp.isSuccessful()); // delete Response<Void> deleteResp = client.users().delete(uuid).execute(); assertTrue(deleteResp.isSuccessful()); } @Test public void testUserCreate() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create - clean insert Response<PlayerSaveResult> createResp1 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp1.isSuccessful()); assertEquals(201, createResp1.code()); PlayerSaveResult result1 = createResp1.body(); assertNotNull(result1); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT), result1.outcomes()); assertNull(result1.previousUsername()); assertNull(result1.otherUniqueIds()); // create - no change Response<PlayerSaveResult> createResp2 = client.users().create(new CreateUserRequest(uuid, username)).execute(); assertTrue(createResp2.isSuccessful()); assertEquals(200, createResp2.code()); PlayerSaveResult result2 = createResp2.body(); assertNotNull(result2); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.NO_CHANGE), result2.outcomes()); assertNull(result2.previousUsername()); assertNull(result2.otherUniqueIds()); // create - changed username String otherUsername = randomName(); Response<PlayerSaveResult> createResp3 = client.users().create(new CreateUserRequest(uuid, otherUsername)).execute(); assertTrue(createResp3.isSuccessful()); assertEquals(200, createResp3.code()); PlayerSaveResult result3 = createResp3.body(); assertNotNull(result3); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.USERNAME_UPDATED), result3.outcomes()); assertEquals(username, result3.previousUsername()); assertNull(result3.otherUniqueIds()); // create - changed uuid UUID otherUuid = UUID.randomUUID(); Response<PlayerSaveResult> createResp4 = client.users().create(new CreateUserRequest(otherUuid, otherUsername)).execute(); assertTrue(createResp4.isSuccessful()); assertEquals(201, createResp4.code()); PlayerSaveResult result4 = createResp4.body(); assertNotNull(result4); assertEquals(ImmutableSet.of(PlayerSaveResult.Outcome.CLEAN_INSERT, PlayerSaveResult.Outcome.OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME), result4.outcomes()); assertNull(result4.previousUsername()); assertEquals(ImmutableSet.of(uuid), result4.otherUniqueIds()); } @Test public void testUserList() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user & give it a permission assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); assertTrue(client.users().nodesAdd(uuid, new Node("test.node", true, Collections.emptySet(), null)).execute().isSuccessful()); Response<Set<UUID>> resp = client.users().list().execute(); assertTrue(resp.isSuccessful()); assertNotNull(resp.body()); assertTrue(resp.body().contains(uuid)); } @Test public void testUserLookup() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // uuid to username Response<UserLookupResult> uuidToUsername = client.users().lookup(uuid).execute(); assertTrue(uuidToUsername.isSuccessful()); assertNotNull(uuidToUsername.body()); assertEquals(username, uuidToUsername.body().username()); // username to uuid Response<UserLookupResult> usernameToUuid = client.users().lookup(username).execute(); assertTrue(usernameToUuid.isSuccessful()); assertNotNull(usernameToUuid.body()); assertEquals(uuid, uuidToUsername.body().uniqueId()); // not found assertEquals(404, client.users().lookup(UUID.randomUUID()).execute().code()); assertEquals(404, client.users().lookup(randomName()).execute().code()); } @Test public void testUserNodes() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // get user nodes and validate they are as expected List<Node> nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableList.of( new Node("group.default", true, Collections.emptySet(), null) ), nodes); long expiryTime = (System.currentTimeMillis() / 1000L) + 60; // add a node assertTrue(client.users().nodesAdd(uuid, new Node("test.node.one", true, Collections.emptySet(), null)).execute().isSuccessful()); // add multiple nodes assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) )).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) ), ImmutableSet.copyOf(nodes)); // delete nodes assertTrue(client.users().nodesDelete(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null) )).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) ), ImmutableSet.copyOf(nodes)); // add a duplicate node with a later expiry time long laterExpiryTime = expiryTime + 60; assertTrue(client.users().nodesAdd(uuid, new Node("test.node.four", false, Collections.emptySet(), laterExpiryTime), TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), laterExpiryTime) ), ImmutableSet.copyOf(nodes)); long evenLaterExpiryTime = expiryTime + 60; // add multiple nodes assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), evenLaterExpiryTime) ), TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), evenLaterExpiryTime) ), ImmutableSet.copyOf(nodes)); // set nodes assertTrue(client.users().nodesSet(uuid, ImmutableList.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.five", false, Collections.emptySet(), null), new Node("test.node.six", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.seven", false, Collections.emptySet(), evenLaterExpiryTime) )).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null), new Node("test.node.five", false, Collections.emptySet(), null), new Node("test.node.six", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.seven", false, Collections.emptySet(), evenLaterExpiryTime) ), ImmutableSet.copyOf(nodes)); // delete all nodes assertTrue(client.users().nodesDelete(uuid).execute().isSuccessful()); // get user nodes and validate they are as expected nodes = client.users().nodes(uuid).execute().body(); assertNotNull(nodes); assertEquals(ImmutableSet.of( new Node("group.default", true, Collections.emptySet(), null) ), ImmutableSet.copyOf(nodes)); } @Test public void testUserMetadata() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null), new Node("suffix.100. test", true, Collections.emptySet(), null), new Node("meta.hello.world", true, Collections.emptySet(), null) )).execute().isSuccessful()); // assert metadata Response<Metadata> resp = client.users().metadata(uuid).execute(); assertTrue(resp.isSuccessful()); Metadata metadata = resp.body(); assertNotNull(metadata); assertEquals("&c[Admin] ", metadata.prefix()); assertEquals(" test", metadata.suffix()); assertEquals("default", metadata.primaryGroup()); Map<String, String> metaMap = metadata.meta(); assertEquals("world", metaMap.get("hello")); } @Test public void testUserSearch() throws IOException { LuckPermsRestClient client = createClient(); // clear existing users Set<UUID> existingUsers = client.users().list().execute().body(); if (existingUsers != null) { for (UUID u : existingUsers) { client.users().delete(u).execute(); } } UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions long expiryTime = (System.currentTimeMillis() / 1000L) + 60; assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime), new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null), new Node("suffix.100. test", true, Collections.emptySet(), null), new Node("meta.hello.world", true, Collections.emptySet(), null) )).execute().isSuccessful()); // searchNodesByKey Response<List<UserSearchResult>> resp1 = client.users().searchNodesByKey("test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("test.node.one", true, Collections.emptySet(), null))) ), resp1.body()); // searchNodesByKeyStartsWith Response<List<UserSearchResult>> resp2 = client.users().searchNodesByKeyStartsWith("test.node").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), new Node("test.node.four", false, Collections.emptySet(), expiryTime) )) ), resp2.body()); // searchNodesByMetaKey Response<List<UserSearchResult>> resp3 = client.users().searchNodesByMetaKey("hello").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("meta.hello.world", true, Collections.emptySet(), null))) ), resp3.body()); // searchNodesByType Response<List<UserSearchResult>> resp4 = client.users().searchNodesByType(NodeType.PREFIX).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(ImmutableList.of( new UserSearchResult(uuid, ImmutableList.of(new Node("prefix.100.&c[Admin] ", true, Collections.emptySet(), null))) ), resp4.body()); } @Test public void testUserPermissionCheck() throws IOException { LuckPermsRestClient client = createClient(); UUID uuid = UUID.randomUUID(); String username = randomName(); // create a user assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // set some permissions assertTrue(client.users().nodesAdd(uuid, ImmutableList.of( new Node("test.node.one", true, Collections.emptySet(), null), new Node("test.node.two", false, Collections.emptySet(), null), new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null) )).execute().isSuccessful()); Response<PermissionCheckResult> resp0 = client.users().permissionCheck(uuid, "test.node.zero").execute(); assertTrue(resp0.isSuccessful()); assertNotNull(resp0.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp0.body().result()); assertNull(resp0.body().node()); Response<PermissionCheckResult> resp1 = client.users().permissionCheck(uuid, "test.node.one").execute(); assertTrue(resp1.isSuccessful()); assertNotNull(resp1.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp1.body().result()); assertEquals(new Node("test.node.one", true, Collections.emptySet(), null), resp1.body().node()); Response<PermissionCheckResult> resp2 = client.users().permissionCheck(uuid, "test.node.two").execute(); assertTrue(resp2.isSuccessful()); assertNotNull(resp2.body()); assertEquals(PermissionCheckResult.Tristate.FALSE, resp2.body().result()); assertEquals(new Node("test.node.two", false, Collections.emptySet(), null), resp2.body().node()); Response<PermissionCheckResult> resp3 = client.users().permissionCheck(uuid, "test.node.three").execute(); assertTrue(resp3.isSuccessful()); assertNotNull(resp3.body()); assertEquals(PermissionCheckResult.Tristate.UNDEFINED, resp3.body().result()); assertNull(resp3.body().node()); Response<PermissionCheckResult> resp4 = client.users().permissionCheck(uuid, new PermissionCheckRequest( "test.node.three", new QueryOptions(null, null, ImmutableSet.of(new Context("server", "test"), new Context("world", "aaa"))) )).execute(); assertTrue(resp4.isSuccessful()); assertNotNull(resp4.body()); assertEquals(PermissionCheckResult.Tristate.TRUE, resp4.body().result()); assertEquals(new Node("test.node.three", true, Collections.singleton(new Context("server", "test")), null), resp4.body().node()); } @Test public void testUserPromoteDemote() throws IOException { LuckPermsRestClient client = createClient(); // create a user UUID uuid = UUID.randomUUID(); String username = randomName(); assertTrue(client.users().create(new CreateUserRequest(uuid, username)).execute().isSuccessful()); // create a track String trackName = randomName(); assertTrue(client.tracks().create(new CreateTrackRequest(trackName)).execute().isSuccessful()); // create some groups Group group1 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group2 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); Group group3 = Objects.requireNonNull(client.groups().create(new CreateGroupRequest(randomName())).execute().body()); ImmutableList<String> groupNames = ImmutableList.of(group1.name(), group2.name(), group3.name()); // update the track assertTrue(client.tracks().update(trackName, new UpdateTrackRequest(groupNames)).execute().isSuccessful()); // promote the user along the track
Response<PromotionResult> promoteResp = client.users().promote(uuid, new TrackRequest(trackName, ImmutableSet.of())).execute();
13
2023-10-22 16:07:30+00:00
12k
RoessinghResearch/senseeact
SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/compat/UserV0.java
[ { "identifier": "MaritalStatus", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/MaritalStatus.java", "snippet": "public enum MaritalStatus {\n\tSINGLE,\n\tPARTNER,\n\tMARRIED,\n\tDIVORCED,\n\tWIDOW\n}" }, { "identifier": "Role", "path": "SenSeeActClient/src/main/java/nl...
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import nl.rrd.utils.json.SqlDateDeserializer; import nl.rrd.utils.json.SqlDateSerializer; import nl.rrd.utils.validation.ValidateEmail; import nl.rrd.utils.validation.ValidateNotNull; import nl.rrd.utils.validation.ValidateTimeZone; import nl.rrd.senseeact.client.model.MaritalStatus; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.User; import nl.rrd.senseeact.dao.AbstractDatabaseObject; import nl.rrd.senseeact.dao.DatabaseField; import nl.rrd.senseeact.dao.DatabaseObject; import nl.rrd.senseeact.dao.DatabaseType; import java.time.LocalDate; import java.util.LinkedHashSet; import java.util.Set;
9,286
package nl.rrd.senseeact.client.model.compat; /** * Model of a user in SenSeeAct. This class is used on the client side. The * server side has an extension of this class with sensitive information about * the authentication of a user. On the server it's stored in a database. * Therefore this class is a {@link DatabaseObject DatabaseObject} and it has an * ID field, but the ID field is not used on the client side. The email address * is used to identify a user. * * <p>Only two fields are always defined on the client side: email and role. * All other fields may be null.</p> * * @author Dennis Hofs (RRD) */ public class UserV0 extends AbstractDatabaseObject { @JsonIgnore private String id; @DatabaseField(value=DatabaseType.STRING, index=true) @ValidateEmail @ValidateNotNull private String email; @DatabaseField(value=DatabaseType.STRING) private Role role; @DatabaseField(value=DatabaseType.STRING) private GenderV0 gender; @DatabaseField(value=DatabaseType.STRING)
package nl.rrd.senseeact.client.model.compat; /** * Model of a user in SenSeeAct. This class is used on the client side. The * server side has an extension of this class with sensitive information about * the authentication of a user. On the server it's stored in a database. * Therefore this class is a {@link DatabaseObject DatabaseObject} and it has an * ID field, but the ID field is not used on the client side. The email address * is used to identify a user. * * <p>Only two fields are always defined on the client side: email and role. * All other fields may be null.</p> * * @author Dennis Hofs (RRD) */ public class UserV0 extends AbstractDatabaseObject { @JsonIgnore private String id; @DatabaseField(value=DatabaseType.STRING, index=true) @ValidateEmail @ValidateNotNull private String email; @DatabaseField(value=DatabaseType.STRING) private Role role; @DatabaseField(value=DatabaseType.STRING) private GenderV0 gender; @DatabaseField(value=DatabaseType.STRING)
private MaritalStatus maritalStatus;
0
2023-10-24 09:36:50+00:00
12k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/Robot.java
[ { "identifier": "Intake", "path": "src/main/java/frc/robot/intake/Intake.java", "snippet": "public class Intake extends Mechanism {\n public class IntakeConfig extends Config {\n\n public double fullSpeed = 1.0;\n public double ejectSpeed = -1.0;\n\n public IntakeConfig() {\n ...
import edu.wpi.first.wpilibj2.command.CommandScheduler; import frc.robot.intake.Intake; import frc.robot.intake.IntakeCommands; import frc.robot.leds.LEDs; import frc.robot.leds.LEDsCommands; import frc.robot.pilot.Pilot; import frc.robot.pilot.PilotCommands; import frc.robot.slide.Slide; import frc.robot.slide.SlideCommands; import frc.robot.swerve.Swerve; import frc.robot.swerve.commands.SwerveCommands; import frc.robot.training.Training; import frc.robot.training.commands.TrainingCommands; import frc.spectrumLib.util.CrashTracker; import org.littletonrobotics.junction.LoggedRobot; import org.littletonrobotics.junction.Logger; import org.littletonrobotics.junction.networktables.NT4Publisher; import org.littletonrobotics.junction.wpilog.WPILOGWriter;
9,963
package frc.robot; public class Robot extends LoggedRobot { public static RobotConfig config; public static RobotTelemetry telemetry; /** Create a single static instance of all of your subsystems */ public static Training training; public static Swerve swerve; public static Intake intake; public static Slide slide; public static LEDs leds; public static Pilot pilot; // public static Auton auton; /** * This method cancels all commands and returns subsystems to their default commands and the * gamepad configs are reset so that new bindings can be assigned based on mode This method * should be called when each mode is intialized */ public static void resetCommandsAndButtons() { CommandScheduler.getInstance().cancelAll(); // Disable any currently running commands CommandScheduler.getInstance().getActiveButtonLoop().clear(); // Reset Config for all gamepads and other button bindings pilot.resetConfig(); } /* ROBOT INIT (Initialization) */ /** This method is called once when the robot is first powered on. */ public void robotInit() { try { RobotTelemetry.print("--- Robot Init Starting ---"); /** Set up the config */ config = new RobotConfig(); /** * Intialize the Subsystems of the robot. Subsystems are how we divide up the robot * code. Anything with an output that needs to be independently controlled is a * subsystem Something that don't have an output are alos subsystems. */ training = new Training(); swerve = new Swerve(); intake = new Intake(config.intakeAttached); slide = new Slide(true); pilot = new Pilot(); leds = new LEDs(); /** Intialize Telemetry and Auton */ telemetry = new RobotTelemetry(); // auton = new Auton(); advantageKitInit(); /** * Set Default Commands this method should exist for each subsystem that has default * command these must be done after all the subsystems are intialized */ TrainingCommands.setupDefaultCommand(); SwerveCommands.setupDefaultCommand(); IntakeCommands.setupDefaultCommand(); SlideCommands.setupDefaultCommand(); LEDsCommands.setupDefaultCommand(); PilotCommands.setupDefaultCommand(); RobotTelemetry.print("--- Robot Init Complete ---"); } catch (Throwable t) { // intercept error and log it
package frc.robot; public class Robot extends LoggedRobot { public static RobotConfig config; public static RobotTelemetry telemetry; /** Create a single static instance of all of your subsystems */ public static Training training; public static Swerve swerve; public static Intake intake; public static Slide slide; public static LEDs leds; public static Pilot pilot; // public static Auton auton; /** * This method cancels all commands and returns subsystems to their default commands and the * gamepad configs are reset so that new bindings can be assigned based on mode This method * should be called when each mode is intialized */ public static void resetCommandsAndButtons() { CommandScheduler.getInstance().cancelAll(); // Disable any currently running commands CommandScheduler.getInstance().getActiveButtonLoop().clear(); // Reset Config for all gamepads and other button bindings pilot.resetConfig(); } /* ROBOT INIT (Initialization) */ /** This method is called once when the robot is first powered on. */ public void robotInit() { try { RobotTelemetry.print("--- Robot Init Starting ---"); /** Set up the config */ config = new RobotConfig(); /** * Intialize the Subsystems of the robot. Subsystems are how we divide up the robot * code. Anything with an output that needs to be independently controlled is a * subsystem Something that don't have an output are alos subsystems. */ training = new Training(); swerve = new Swerve(); intake = new Intake(config.intakeAttached); slide = new Slide(true); pilot = new Pilot(); leds = new LEDs(); /** Intialize Telemetry and Auton */ telemetry = new RobotTelemetry(); // auton = new Auton(); advantageKitInit(); /** * Set Default Commands this method should exist for each subsystem that has default * command these must be done after all the subsystems are intialized */ TrainingCommands.setupDefaultCommand(); SwerveCommands.setupDefaultCommand(); IntakeCommands.setupDefaultCommand(); SlideCommands.setupDefaultCommand(); LEDsCommands.setupDefaultCommand(); PilotCommands.setupDefaultCommand(); RobotTelemetry.print("--- Robot Init Complete ---"); } catch (Throwable t) { // intercept error and log it
CrashTracker.logThrowableCrash(t);
12
2023-10-23 17:01:53+00:00
12k
RaulGB88/MOD-034-Microservicios-con-Java
REM20231023/catalogo/src/main/java/com/example/application/resources/FilmResource.java
[ { "identifier": "DomainEventService", "path": "REM20231023/catalogo/src/main/java/com/example/DomainEventService.java", "snippet": "@Service\npublic class DomainEventService {\n\n\t@Data @AllArgsConstructor\n\tpublic class MessageDTO implements Serializable {\n\t\tprivate static final long serialVersion...
import java.net.URI; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.transaction.Transactional; import jakarta.validation.Valid; import org.springdoc.core.converters.models.PageableAsQueryParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.example.DomainEventService; import com.example.application.proxies.MeGustaProxy; import com.example.domains.contracts.services.FilmService; import com.example.domains.entities.Category; import com.example.domains.entities.Film; import com.example.domains.entities.dtos.ActorDTO; import com.example.domains.entities.dtos.FilmDetailsDTO; import com.example.domains.entities.dtos.FilmEditDTO; import com.example.domains.entities.dtos.FilmShortDTO; import com.example.exceptions.BadRequestException; import com.example.exceptions.NotFoundException; import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag;
7,785
package com.example.application.resources; //import org.springdoc.api.annotations.ParameterObject; @RestController @Tag(name = "peliculas-service", description = "Mantenimiento de peliculas") @RequestMapping(path = "/peliculas/v1") public class FilmResource { @Autowired private FilmService srv; @Autowired DomainEventService deSrv; @Hidden @GetMapping(params = "page") public Page<FilmShortDTO> getAll(Pageable pageable, @RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(pageable, FilmShortDTO.class); } @Operation( summary = "Listado de las peliculas", description = "Recupera la lista de peliculas en formato corto o detallado, se puede paginar.", parameters = { @Parameter(in = ParameterIn.QUERY, name = "mode", required = false, description = "Formato de las peliculas", schema = @Schema(type = "string", allowableValues = { "details", "short" }, defaultValue = "short")) }, responses = { @ApiResponse(responseCode = "200", description = "OK", content = @Content(mediaType = "application/json", schema = @Schema(anyOf = {FilmShortDTO.class, FilmDetailsDTO.class}) )) }) @GetMapping(params = { "page", "mode=details" }) @PageableAsQueryParam @Transactional public Page<FilmDetailsDTO> getAllDetailsPage(@Parameter(hidden = true) Pageable pageable, @RequestParam(defaultValue = "short") String mode) { var content = srv.getAll(pageable); return new PageImpl<>(content.getContent().stream().map(item -> FilmDetailsDTO.from(item)).toList(), pageable, content.getTotalElements()); } @Hidden @GetMapping public List<FilmShortDTO> getAll(@RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(FilmShortDTO.class); } @Hidden @GetMapping(params = "mode=details") public List<FilmDetailsDTO> getAllDetails( // @Parameter(allowEmptyValue = true, required = false, schema = @Schema(type = "string", allowableValues = {"details","short"}, defaultValue = "short")) @RequestParam(defaultValue = "short") String mode) { return srv.getAll().stream().map(item -> FilmDetailsDTO.from(item)).toList(); } @GetMapping(path = "/{id}", params = "mode=short") public FilmShortDTO getOneCorto( @Parameter(description = "Identificador de la pelicula", required = true) @PathVariable int id, @Parameter(required = false, allowEmptyValue = true, schema = @Schema(type = "string", allowableValues = { "details", "short", "edit" }, defaultValue = "edit")) @RequestParam(required = false, defaultValue = "edit") String mode) throws Exception {
package com.example.application.resources; //import org.springdoc.api.annotations.ParameterObject; @RestController @Tag(name = "peliculas-service", description = "Mantenimiento de peliculas") @RequestMapping(path = "/peliculas/v1") public class FilmResource { @Autowired private FilmService srv; @Autowired DomainEventService deSrv; @Hidden @GetMapping(params = "page") public Page<FilmShortDTO> getAll(Pageable pageable, @RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(pageable, FilmShortDTO.class); } @Operation( summary = "Listado de las peliculas", description = "Recupera la lista de peliculas en formato corto o detallado, se puede paginar.", parameters = { @Parameter(in = ParameterIn.QUERY, name = "mode", required = false, description = "Formato de las peliculas", schema = @Schema(type = "string", allowableValues = { "details", "short" }, defaultValue = "short")) }, responses = { @ApiResponse(responseCode = "200", description = "OK", content = @Content(mediaType = "application/json", schema = @Schema(anyOf = {FilmShortDTO.class, FilmDetailsDTO.class}) )) }) @GetMapping(params = { "page", "mode=details" }) @PageableAsQueryParam @Transactional public Page<FilmDetailsDTO> getAllDetailsPage(@Parameter(hidden = true) Pageable pageable, @RequestParam(defaultValue = "short") String mode) { var content = srv.getAll(pageable); return new PageImpl<>(content.getContent().stream().map(item -> FilmDetailsDTO.from(item)).toList(), pageable, content.getTotalElements()); } @Hidden @GetMapping public List<FilmShortDTO> getAll(@RequestParam(defaultValue = "short") String mode) { return srv.getByProjection(FilmShortDTO.class); } @Hidden @GetMapping(params = "mode=details") public List<FilmDetailsDTO> getAllDetails( // @Parameter(allowEmptyValue = true, required = false, schema = @Schema(type = "string", allowableValues = {"details","short"}, defaultValue = "short")) @RequestParam(defaultValue = "short") String mode) { return srv.getAll().stream().map(item -> FilmDetailsDTO.from(item)).toList(); } @GetMapping(path = "/{id}", params = "mode=short") public FilmShortDTO getOneCorto( @Parameter(description = "Identificador de la pelicula", required = true) @PathVariable int id, @Parameter(required = false, allowEmptyValue = true, schema = @Schema(type = "string", allowableValues = { "details", "short", "edit" }, defaultValue = "edit")) @RequestParam(required = false, defaultValue = "edit") String mode) throws Exception {
Optional<Film> rslt = srv.getOne(id);
4
2023-10-24 14:35:15+00:00
12k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/web/api/admin/CmdHistoryRepREST.java
[ { "identifier": "DateUtils", "path": "src/main/java/org/msh/etbm/commons/date/DateUtils.java", "snippet": "public class DateUtils {\n\n /**\n * Private method to avoid creation of instances of this class\n */\n private DateUtils() {\n super();\n }\n\n /**\n * Return the nu...
import org.msh.etbm.commons.date.DateUtils; import org.msh.etbm.commons.entities.query.QueryResult; import org.msh.etbm.services.admin.cmdhisotryrep.CmdHistoryRepQueryParams; import org.msh.etbm.services.admin.cmdhisotryrep.CmdHistoryRepService; import org.msh.etbm.services.security.permissions.Permissions; import org.msh.etbm.web.api.authentication.Authenticated; import org.msh.etbm.web.api.authentication.InstanceType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid;
7,621
package org.msh.etbm.web.api.admin; /** * Created by msantos on 15/3/16. */ @RestController @RequestMapping("/api/admin/rep") @Authenticated(permissions = {Permissions.ADMIN_REP_CMDHISTORY}, instanceType = InstanceType.SERVER_MODE) public class CmdHistoryRepREST { @Autowired CmdHistoryRepService service; @RequestMapping(value = "/cmdhistory", method = RequestMethod.POST) public QueryResult query(@Valid @RequestBody CmdHistoryRepQueryParams query) { return service.getResult(query); } @RequestMapping(value = "/todaycmdhistory", method = RequestMethod.POST) public QueryResult todayResult() { CmdHistoryRepQueryParams query = new CmdHistoryRepQueryParams();
package org.msh.etbm.web.api.admin; /** * Created by msantos on 15/3/16. */ @RestController @RequestMapping("/api/admin/rep") @Authenticated(permissions = {Permissions.ADMIN_REP_CMDHISTORY}, instanceType = InstanceType.SERVER_MODE) public class CmdHistoryRepREST { @Autowired CmdHistoryRepService service; @RequestMapping(value = "/cmdhistory", method = RequestMethod.POST) public QueryResult query(@Valid @RequestBody CmdHistoryRepQueryParams query) { return service.getResult(query); } @RequestMapping(value = "/todaycmdhistory", method = RequestMethod.POST) public QueryResult todayResult() { CmdHistoryRepQueryParams query = new CmdHistoryRepQueryParams();
query.setIniDate(DateUtils.getDate());
0
2023-10-23 13:47:54+00:00
12k
toel--/ocpp-backend-emulator
src/org/java_websocket/extensions/permessage_deflate/PerMessageDeflateExtension.java
[ { "identifier": "Opcode", "path": "src/org/java_websocket/enums/Opcode.java", "snippet": "public enum Opcode {\n CONTINUOUS, TEXT, BINARY, PING, PONG, CLOSING\n // more to come\n}" }, { "identifier": "InvalidDataException", "path": "src/org/java_websocket/exceptions/InvalidDataException.ja...
import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.LinkedHashMap; import java.util.Map; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; import org.java_websocket.enums.Opcode; import org.java_websocket.exceptions.InvalidDataException; import org.java_websocket.exceptions.InvalidFrameException; import org.java_websocket.extensions.CompressionExtension; import org.java_websocket.extensions.ExtensionRequestData; import org.java_websocket.extensions.IExtension; import org.java_websocket.framing.BinaryFrame; import org.java_websocket.framing.CloseFrame; import org.java_websocket.framing.ContinuousFrame; import org.java_websocket.framing.DataFrame; import org.java_websocket.framing.Framedata; import org.java_websocket.framing.FramedataImpl1; import org.java_websocket.framing.TextFrame;
10,082
package org.java_websocket.extensions.permessage_deflate; /** * PerMessage Deflate Extension (<a href="https://tools.ietf.org/html/rfc7692#section-7">7&#46; The * "permessage-deflate" Extension</a> in * <a href="https://tools.ietf.org/html/rfc7692">RFC 7692</a>). * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7">7&#46; The "permessage-deflate" * Extension in RFC 7692</a> */ public class PerMessageDeflateExtension extends CompressionExtension { // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; // Below values are defined for convenience. They are not used in the compression/decompression phase. // They may be needed during the extension-negotiation offer in the future. private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; private static final int serverMaxWindowBits = 1 << 15; private static final int clientMaxWindowBits = 1 << 15; private static final byte[] TAIL_BYTES = {(byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF}; private static final int BUFFER_SIZE = 1 << 10; private int threshold = 1024; private boolean serverNoContextTakeover = true; private boolean clientNoContextTakeover = false; // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map<String, String> requestedParameters = new LinkedHashMap<>(); private Inflater inflater = new Inflater(true); private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); public Inflater getInflater() { return inflater; } public void setInflater(Inflater inflater) { this.inflater = inflater; } public Deflater getDeflater() { return deflater; } public void setDeflater(Deflater deflater) { this.deflater = deflater; } /** * Get the size threshold for doing the compression * @return Size (in bytes) below which messages will not be compressed * @since 1.5.3 */ public int getThreshold() { return threshold; } /** * Set the size when payloads smaller than this will not be compressed. * @param threshold the size in bytes * @since 1.5.3 */ public void setThreshold(int threshold) { this.threshold = threshold; } /** * Access the "server_no_context_takeover" extension parameter * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.1">The "server_no_context_takeover" Extension Parameter</a> * @return serverNoContextTakeover is the server no context parameter active */ public boolean isServerNoContextTakeover() { return serverNoContextTakeover; } /** * Setter for the "server_no_context_takeover" extension parameter * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.1">The "server_no_context_takeover" Extension Parameter</a> * @param serverNoContextTakeover set the server no context parameter */ public void setServerNoContextTakeover(boolean serverNoContextTakeover) { this.serverNoContextTakeover = serverNoContextTakeover; } /** * Access the "client_no_context_takeover" extension parameter * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.2">The "client_no_context_takeover" Extension Parameter</a> * @return clientNoContextTakeover is the client no context parameter active */ public boolean isClientNoContextTakeover() { return clientNoContextTakeover; } /** * Setter for the "client_no_context_takeover" extension parameter * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.2">The "client_no_context_takeover" Extension Parameter</a> * @param clientNoContextTakeover set the client no context parameter */ public void setClientNoContextTakeover(boolean clientNoContextTakeover) { this.clientNoContextTakeover = clientNoContextTakeover; } /* An endpoint uses the following algorithm to decompress a message. 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the payload of the message. 2. Decompress the resulting data using DEFLATE. See, https://tools.ietf.org/html/rfc7692#section-7.2.2 */ @Override public void decodeFrame(Framedata inputFrame) throws InvalidDataException { // Only DataFrames can be decompressed. if (!(inputFrame instanceof DataFrame)) { return; } if (!inputFrame.isRSV1() && inputFrame.getOpcode() != Opcode.CONTINUOUS) { return; } // RSV1 bit must be set only for the first frame. if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); } // Decompressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); try { decompress(inputFrame.getPayloadData().array(), output); /* If a message is "first fragmented and then compressed", as this project does, then the inflater can not inflate fragments except the first one. This behavior occurs most likely because those fragments end with "final deflate blocks". We can check the getRemaining() method to see whether the data we supplied has been decompressed or not. And if not, we just reset the inflater and decompress again. Note that this behavior doesn't occur if the message is "first compressed and then fragmented". */ if (inflater.getRemaining() > 0) { inflater = new Inflater(true); decompress(inputFrame.getPayloadData().array(), output); } if (inputFrame.isFin()) { decompress(TAIL_BYTES, output); // If context takeover is disabled, inflater can be reset. if (clientNoContextTakeover) { inflater = new Inflater(true); } } } catch (DataFormatException e) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); } // Set frames payload to the new decompressed data. ((FramedataImpl1) inputFrame) .setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); } /** * @param data the bytes of data * @param outputBuffer the output stream * @throws DataFormatException */ private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException { inflater.setInput(data); byte[] buffer = new byte[BUFFER_SIZE]; int bytesInflated; while ((bytesInflated = inflater.inflate(buffer)) > 0) { outputBuffer.write(buffer, 0, bytesInflated); } } @Override public void encodeFrame(Framedata inputFrame) { // Only DataFrames can be decompressed. if (!(inputFrame instanceof DataFrame)) { return; } byte[] payloadData = inputFrame.getPayloadData().array(); if (payloadData.length < threshold) { return; } // Only the first frame's RSV1 must be set.
package org.java_websocket.extensions.permessage_deflate; /** * PerMessage Deflate Extension (<a href="https://tools.ietf.org/html/rfc7692#section-7">7&#46; The * "permessage-deflate" Extension</a> in * <a href="https://tools.ietf.org/html/rfc7692">RFC 7692</a>). * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7">7&#46; The "permessage-deflate" * Extension in RFC 7692</a> */ public class PerMessageDeflateExtension extends CompressionExtension { // Name of the extension as registered by IETF https://tools.ietf.org/html/rfc7692#section-9. private static final String EXTENSION_REGISTERED_NAME = "permessage-deflate"; // Below values are defined for convenience. They are not used in the compression/decompression phase. // They may be needed during the extension-negotiation offer in the future. private static final String SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"; private static final String CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"; private static final String SERVER_MAX_WINDOW_BITS = "server_max_window_bits"; private static final String CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"; private static final int serverMaxWindowBits = 1 << 15; private static final int clientMaxWindowBits = 1 << 15; private static final byte[] TAIL_BYTES = {(byte) 0x00, (byte) 0x00, (byte) 0xFF, (byte) 0xFF}; private static final int BUFFER_SIZE = 1 << 10; private int threshold = 1024; private boolean serverNoContextTakeover = true; private boolean clientNoContextTakeover = false; // For WebSocketServers, this variable holds the extension parameters that the peer client has requested. // For WebSocketClients, this variable holds the extension parameters that client himself has requested. private Map<String, String> requestedParameters = new LinkedHashMap<>(); private Inflater inflater = new Inflater(true); private Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); public Inflater getInflater() { return inflater; } public void setInflater(Inflater inflater) { this.inflater = inflater; } public Deflater getDeflater() { return deflater; } public void setDeflater(Deflater deflater) { this.deflater = deflater; } /** * Get the size threshold for doing the compression * @return Size (in bytes) below which messages will not be compressed * @since 1.5.3 */ public int getThreshold() { return threshold; } /** * Set the size when payloads smaller than this will not be compressed. * @param threshold the size in bytes * @since 1.5.3 */ public void setThreshold(int threshold) { this.threshold = threshold; } /** * Access the "server_no_context_takeover" extension parameter * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.1">The "server_no_context_takeover" Extension Parameter</a> * @return serverNoContextTakeover is the server no context parameter active */ public boolean isServerNoContextTakeover() { return serverNoContextTakeover; } /** * Setter for the "server_no_context_takeover" extension parameter * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.1">The "server_no_context_takeover" Extension Parameter</a> * @param serverNoContextTakeover set the server no context parameter */ public void setServerNoContextTakeover(boolean serverNoContextTakeover) { this.serverNoContextTakeover = serverNoContextTakeover; } /** * Access the "client_no_context_takeover" extension parameter * * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.2">The "client_no_context_takeover" Extension Parameter</a> * @return clientNoContextTakeover is the client no context parameter active */ public boolean isClientNoContextTakeover() { return clientNoContextTakeover; } /** * Setter for the "client_no_context_takeover" extension parameter * @see <a href="https://tools.ietf.org/html/rfc7692#section-7.1.1.2">The "client_no_context_takeover" Extension Parameter</a> * @param clientNoContextTakeover set the client no context parameter */ public void setClientNoContextTakeover(boolean clientNoContextTakeover) { this.clientNoContextTakeover = clientNoContextTakeover; } /* An endpoint uses the following algorithm to decompress a message. 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the payload of the message. 2. Decompress the resulting data using DEFLATE. See, https://tools.ietf.org/html/rfc7692#section-7.2.2 */ @Override public void decodeFrame(Framedata inputFrame) throws InvalidDataException { // Only DataFrames can be decompressed. if (!(inputFrame instanceof DataFrame)) { return; } if (!inputFrame.isRSV1() && inputFrame.getOpcode() != Opcode.CONTINUOUS) { return; } // RSV1 bit must be set only for the first frame. if (inputFrame.getOpcode() == Opcode.CONTINUOUS && inputFrame.isRSV1()) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, "RSV1 bit can only be set for the first frame."); } // Decompressed output buffer. ByteArrayOutputStream output = new ByteArrayOutputStream(); try { decompress(inputFrame.getPayloadData().array(), output); /* If a message is "first fragmented and then compressed", as this project does, then the inflater can not inflate fragments except the first one. This behavior occurs most likely because those fragments end with "final deflate blocks". We can check the getRemaining() method to see whether the data we supplied has been decompressed or not. And if not, we just reset the inflater and decompress again. Note that this behavior doesn't occur if the message is "first compressed and then fragmented". */ if (inflater.getRemaining() > 0) { inflater = new Inflater(true); decompress(inputFrame.getPayloadData().array(), output); } if (inputFrame.isFin()) { decompress(TAIL_BYTES, output); // If context takeover is disabled, inflater can be reset. if (clientNoContextTakeover) { inflater = new Inflater(true); } } } catch (DataFormatException e) { throw new InvalidDataException(CloseFrame.POLICY_VALIDATION, e.getMessage()); } // Set frames payload to the new decompressed data. ((FramedataImpl1) inputFrame) .setPayload(ByteBuffer.wrap(output.toByteArray(), 0, output.size())); } /** * @param data the bytes of data * @param outputBuffer the output stream * @throws DataFormatException */ private void decompress(byte[] data, ByteArrayOutputStream outputBuffer) throws DataFormatException { inflater.setInput(data); byte[] buffer = new byte[BUFFER_SIZE]; int bytesInflated; while ((bytesInflated = inflater.inflate(buffer)) > 0) { outputBuffer.write(buffer, 0, bytesInflated); } } @Override public void encodeFrame(Framedata inputFrame) { // Only DataFrames can be decompressed. if (!(inputFrame instanceof DataFrame)) { return; } byte[] payloadData = inputFrame.getPayloadData().array(); if (payloadData.length < threshold) { return; } // Only the first frame's RSV1 must be set.
if (!(inputFrame instanceof ContinuousFrame)) {
8
2023-10-16 23:10:55+00:00
12k
weibocom/rill-flow
rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/runners/SuspenseTaskRunner.java
[ { "identifier": "TaskInfo", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/task/TaskInfo.java", "snippet": "@Setter\n@Getter\n@JsonIdentityInfo(\n generator = ObjectIdGenerators.UUIDGenerator.class,\n property = \"@json_id\"\n)\npublic class TaskInfo {\n ...
import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.weibo.rill.flow.interfaces.model.task.TaskInfo; import com.weibo.rill.flow.interfaces.model.task.TaskInvokeMsg; import com.weibo.rill.flow.interfaces.model.task.TaskStatus; import com.weibo.rill.flow.olympicene.core.lock.LockerKey; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.task.ExecutionResult; import com.weibo.rill.flow.olympicene.core.model.task.SuspenseTask; import com.weibo.rill.flow.olympicene.core.model.task.TaskCategory; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.core.switcher.SwitcherManager; import com.weibo.rill.flow.olympicene.traversal.constant.TraversalErrorCode; import com.weibo.rill.flow.olympicene.traversal.exception.DAGTraversalException; import com.weibo.rill.flow.olympicene.traversal.helper.ContextHelper; import com.weibo.rill.flow.olympicene.traversal.mappings.InputOutputMapping; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference;
8,469
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.traversal.runners; /** * 方法加锁原因 有两个场景能触发suspense任务执行 可能产生并发 * 1. traversal遍历触发任务 * 2. wakeup调用触发任务 * <p> * Created by xilong on 2021/4/7. */ @Slf4j public class SuspenseTaskRunner extends AbstractTaskRunner { public SuspenseTaskRunner(InputOutputMapping inputOutputMapping, DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGStorageProcedure dagStorageProcedure, SwitcherManager switcherManager) { super(inputOutputMapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); } @Override protected ExecutionResult doRun(String executionId, TaskInfo taskInfo, Map<String, Object> input) { log.info("suspense task begin to run executionId:{}, taskInfoName:{}", executionId, taskInfo.getName()); ExecutionResult ret = ExecutionResult.builder().build(); dagStorageProcedure.lockAndRun(LockerKey.buildTaskInfoLockName(executionId, taskInfo.getName()), () -> { // 因为有并发可能 导致收到的input可能为wakeup更新前的值 // wakeup更新可能导致context值发生变化 因此需要取最新context Map<String, Object> context = ContextHelper.getInstance().getContext(dagContextStorage, executionId, taskInfo); Map<String, Object> inputRealTime = Maps.newHashMap(); inputMappings(context, inputRealTime, new HashMap<>(), taskInfo.getTask().getInputMappings()); taskInfo.setTaskStatus(TaskStatus.RUNNING); tryWakeup(executionId, taskInfo, inputRealTime); tryInterruptSuspense(executionId, taskInfo, inputRealTime); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); ret.setInput(inputRealTime); ret.setTaskStatus(taskInfo.getTaskStatus()); }); log.info("run suspense task completed, executionId:{}, taskInfoName:{}", executionId, taskInfo.getName()); return ret; } @Override public ExecutionResult finish(String executionId, NotifyInfo notifyInfo, Map<String, Object> output) { String taskInfoName = notifyInfo.getTaskInfoName(); log.info("suspense wakeup begin to run executionId:{}, taskInfoName:{}, output empty:{}", executionId, taskInfoName, MapUtils.isEmpty(output)); AtomicReference<TaskInfo> taskInfoRef = new AtomicReference<>(); AtomicReference<Map<String, Object>> contextRef = new AtomicReference<>(); dagStorageProcedure.lockAndRun(LockerKey.buildTaskInfoLockName(executionId, taskInfoName), () -> { validateDAGInfo(executionId); TaskInfo taskInfo = dagInfoStorage.getBasicTaskInfo(executionId, taskInfoName); taskInfoRef.set(taskInfo); // 若任务状态为已完成 则不进行进一步操作 taskInfoValid(executionId, taskInfoName, taskInfo); // 目前只有超时不为null if (notifyInfo.getTaskStatus() != null && notifyInfo.getTaskStatus().isCompleted()) { taskInfo.updateInvokeMsg(notifyInfo.getTaskInvokeMsg()); updateTaskInvokeEndTime(taskInfo); taskInfo.setTaskStatus(notifyInfo.getTaskStatus()); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); return; } // 若任务状态为非running 表示该任务尚未被调度 只更新context // 若任务状态为running 则更新context并尝试唤醒任务 log.info("suspense wakeup taskInfo current taskStatus:{}", taskInfo.getTaskStatus()); if (taskInfo.getTaskStatus() != TaskStatus.RUNNING && MapUtils.isEmpty(output)) { return; } Map<String, Object> context = ContextHelper.getInstance().getContext(dagContextStorage, executionId, taskInfo); contextRef.set(context); if (MapUtils.isNotEmpty(output) && CollectionUtils.isNotEmpty(taskInfo.getTask().getOutputMappings())) { outputMappings(context, new HashMap<>(), output, taskInfo.getTask().getOutputMappings()); saveContext(executionId, context, Sets.newHashSet(taskInfo)); } if (taskInfo.getTaskStatus() != TaskStatus.RUNNING) { return; } Map<String, Object> input = Maps.newHashMap(); inputMappings(context, input, new HashMap<>(), taskInfo.getTask().getInputMappings()); if (tryWakeup(executionId, taskInfo, input) || tryInterruptSuspense(executionId, taskInfo, input)) { dagInfoStorage.saveTaskInfos(executionId, Sets.newHashSet(taskInfo)); } }); TaskInfo taskInfo = taskInfoRef.get(); log.info("run suspense wakeup completed, executionId:{}, taskInfoName:{}, taskStatus:{}", executionId, taskInfoName, taskInfo.getTaskStatus()); return ExecutionResult.builder() .taskStatus(taskInfo.getTaskStatus()) .taskInfo(taskInfo) .context(contextRef.get()) .build(); } private boolean tryWakeup(String executionId, TaskInfo taskInfo, Map<String, Object> input) { if (taskInfo.getTaskStatus() != TaskStatus.RUNNING) { return false; } boolean needWakeup = isNeedWakeup(taskInfo, input); log.info("suspense task need wakeup value:{}, executionId:{}, taskInfoName:{}", needWakeup, executionId, taskInfo.getName()); if (needWakeup) { taskInfo.setTaskStatus(TaskStatus.SUCCEED); updateTaskInvokeEndTime(taskInfo); } return needWakeup; } private boolean tryInterruptSuspense(String executionId, TaskInfo taskInfo, Map<String, Object> input) { if (taskInfo.getTaskStatus() != TaskStatus.RUNNING) { return false; } boolean needInterrupt = isNeedInterrupt(taskInfo, input); log.info("suspense task need interrupt value:{}, executionId:{}, taskInfoName:{}", needInterrupt, executionId, taskInfo.getName()); if (needInterrupt) { taskInfo.setTaskStatus(TaskStatus.FAILED); taskInfo.updateInvokeMsg(TaskInvokeMsg.builder().msg("interruption").build()); updateTaskInvokeEndTime(taskInfo); } return needInterrupt; } private boolean isNeedWakeup(TaskInfo taskInfo, Map<String, Object> input) {
/* * Copyright 2021-2023 Weibo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.weibo.rill.flow.olympicene.traversal.runners; /** * 方法加锁原因 有两个场景能触发suspense任务执行 可能产生并发 * 1. traversal遍历触发任务 * 2. wakeup调用触发任务 * <p> * Created by xilong on 2021/4/7. */ @Slf4j public class SuspenseTaskRunner extends AbstractTaskRunner { public SuspenseTaskRunner(InputOutputMapping inputOutputMapping, DAGInfoStorage dagInfoStorage, DAGContextStorage dagContextStorage, DAGStorageProcedure dagStorageProcedure, SwitcherManager switcherManager) { super(inputOutputMapping, dagInfoStorage, dagContextStorage, dagStorageProcedure, switcherManager); } @Override protected ExecutionResult doRun(String executionId, TaskInfo taskInfo, Map<String, Object> input) { log.info("suspense task begin to run executionId:{}, taskInfoName:{}", executionId, taskInfo.getName()); ExecutionResult ret = ExecutionResult.builder().build(); dagStorageProcedure.lockAndRun(LockerKey.buildTaskInfoLockName(executionId, taskInfo.getName()), () -> { // 因为有并发可能 导致收到的input可能为wakeup更新前的值 // wakeup更新可能导致context值发生变化 因此需要取最新context Map<String, Object> context = ContextHelper.getInstance().getContext(dagContextStorage, executionId, taskInfo); Map<String, Object> inputRealTime = Maps.newHashMap(); inputMappings(context, inputRealTime, new HashMap<>(), taskInfo.getTask().getInputMappings()); taskInfo.setTaskStatus(TaskStatus.RUNNING); tryWakeup(executionId, taskInfo, inputRealTime); tryInterruptSuspense(executionId, taskInfo, inputRealTime); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); ret.setInput(inputRealTime); ret.setTaskStatus(taskInfo.getTaskStatus()); }); log.info("run suspense task completed, executionId:{}, taskInfoName:{}", executionId, taskInfo.getName()); return ret; } @Override public ExecutionResult finish(String executionId, NotifyInfo notifyInfo, Map<String, Object> output) { String taskInfoName = notifyInfo.getTaskInfoName(); log.info("suspense wakeup begin to run executionId:{}, taskInfoName:{}, output empty:{}", executionId, taskInfoName, MapUtils.isEmpty(output)); AtomicReference<TaskInfo> taskInfoRef = new AtomicReference<>(); AtomicReference<Map<String, Object>> contextRef = new AtomicReference<>(); dagStorageProcedure.lockAndRun(LockerKey.buildTaskInfoLockName(executionId, taskInfoName), () -> { validateDAGInfo(executionId); TaskInfo taskInfo = dagInfoStorage.getBasicTaskInfo(executionId, taskInfoName); taskInfoRef.set(taskInfo); // 若任务状态为已完成 则不进行进一步操作 taskInfoValid(executionId, taskInfoName, taskInfo); // 目前只有超时不为null if (notifyInfo.getTaskStatus() != null && notifyInfo.getTaskStatus().isCompleted()) { taskInfo.updateInvokeMsg(notifyInfo.getTaskInvokeMsg()); updateTaskInvokeEndTime(taskInfo); taskInfo.setTaskStatus(notifyInfo.getTaskStatus()); dagInfoStorage.saveTaskInfos(executionId, ImmutableSet.of(taskInfo)); return; } // 若任务状态为非running 表示该任务尚未被调度 只更新context // 若任务状态为running 则更新context并尝试唤醒任务 log.info("suspense wakeup taskInfo current taskStatus:{}", taskInfo.getTaskStatus()); if (taskInfo.getTaskStatus() != TaskStatus.RUNNING && MapUtils.isEmpty(output)) { return; } Map<String, Object> context = ContextHelper.getInstance().getContext(dagContextStorage, executionId, taskInfo); contextRef.set(context); if (MapUtils.isNotEmpty(output) && CollectionUtils.isNotEmpty(taskInfo.getTask().getOutputMappings())) { outputMappings(context, new HashMap<>(), output, taskInfo.getTask().getOutputMappings()); saveContext(executionId, context, Sets.newHashSet(taskInfo)); } if (taskInfo.getTaskStatus() != TaskStatus.RUNNING) { return; } Map<String, Object> input = Maps.newHashMap(); inputMappings(context, input, new HashMap<>(), taskInfo.getTask().getInputMappings()); if (tryWakeup(executionId, taskInfo, input) || tryInterruptSuspense(executionId, taskInfo, input)) { dagInfoStorage.saveTaskInfos(executionId, Sets.newHashSet(taskInfo)); } }); TaskInfo taskInfo = taskInfoRef.get(); log.info("run suspense wakeup completed, executionId:{}, taskInfoName:{}, taskStatus:{}", executionId, taskInfoName, taskInfo.getTaskStatus()); return ExecutionResult.builder() .taskStatus(taskInfo.getTaskStatus()) .taskInfo(taskInfo) .context(contextRef.get()) .build(); } private boolean tryWakeup(String executionId, TaskInfo taskInfo, Map<String, Object> input) { if (taskInfo.getTaskStatus() != TaskStatus.RUNNING) { return false; } boolean needWakeup = isNeedWakeup(taskInfo, input); log.info("suspense task need wakeup value:{}, executionId:{}, taskInfoName:{}", needWakeup, executionId, taskInfo.getName()); if (needWakeup) { taskInfo.setTaskStatus(TaskStatus.SUCCEED); updateTaskInvokeEndTime(taskInfo); } return needWakeup; } private boolean tryInterruptSuspense(String executionId, TaskInfo taskInfo, Map<String, Object> input) { if (taskInfo.getTaskStatus() != TaskStatus.RUNNING) { return false; } boolean needInterrupt = isNeedInterrupt(taskInfo, input); log.info("suspense task need interrupt value:{}, executionId:{}, taskInfoName:{}", needInterrupt, executionId, taskInfo.getName()); if (needInterrupt) { taskInfo.setTaskStatus(TaskStatus.FAILED); taskInfo.updateInvokeMsg(TaskInvokeMsg.builder().msg("interruption").build()); updateTaskInvokeEndTime(taskInfo); } return needInterrupt; } private boolean isNeedWakeup(TaskInfo taskInfo, Map<String, Object> input) {
SuspenseTask suspenseTask = (SuspenseTask) taskInfo.getTask();
6
2023-11-03 03:46:01+00:00
12k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/test/java/org/example/service/impl/OrderServiceImplTest.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S...
import com.alipay.api.AlipayApiException; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.constant.PaymentType; import org.example.common.constant.ProductName; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.helper.OrderOtsHelper; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.helper.WalletHelper; import org.example.common.model.UserInfoModel; import org.example.common.param.CreateOrderParam; import org.example.common.param.GetOrderParam; import org.example.common.param.GetServiceCostParam; import org.example.common.param.ListOrdersParam; import org.example.common.param.RefundOrderParam; import org.example.service.AlipayService; import org.example.service.ServiceInstanceLifecycleService; import org.example.service.ServiceManager; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.slf4j.Logger; import org.springframework.http.HttpStatus; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyDouble; import static org.mockito.Mockito.anyLong; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.when;
8,162
/* *Copyright (c) Alibaba Group; *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.example.service.impl; class OrderServiceImplTest { @Mock AlipayService alipayService; @Mock OrderOtsHelper orderOtsHelper; @Mock WalletHelper walletHelper; @Mock ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Mock Logger log; @Mock private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; @Mock private ServiceManager serviceManager; @InjectMocks OrderServiceImpl orderServiceImpl; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void testCreateOrder() throws AlipayApiException { when(alipayService.createTransaction(anyDouble(), anyString(), anyString())).thenReturn("createTransactionResponse"); CreateServiceInstanceResponse response = new CreateServiceInstanceResponse(); response.setStatusCode(HttpStatus.OK.value()); when(serviceInstanceLifecycleService.createServiceInstance(any(), any(), anyBoolean(), any())).thenReturn(response); when(serviceManager.getServiceCost(any(), any(GetServiceCostParam.class))).thenReturn(new BaseResult<Double>("code", "message", Double.valueOf(0), "requestId")); List<OrderDTO> orderList = new ArrayList<>(); orderList.add(new OrderDTO()); ListResult<OrderDTO> orderDtoListResult = ListResult.genSuccessListResult(orderList, 1); when(orderOtsHelper.listOrders(anyList(), anyList(), anyList(), anyString(), anyList())).thenReturn(orderDtoListResult); CreateOrderParam createOrderParam = new CreateOrderParam(); createOrderParam.setType(PaymentType.ALIPAY); createOrderParam.setProductComponents("{\n" + " \"RegionId\":\"cn-hangzhou\",\n" + " \"SpecificationName\":\"低配版(Entry Level Package)\",\n" + " \"PayPeriod\":1,\n \"PayPeriodUnit\":\"Month\"\n" + "}"); createOrderParam.setProductName(ProductName.SERVICE_INSTANCE); BaseResult<String> result = orderServiceImpl.createOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), createOrderParam); Assertions.assertTrue(result.getData().equals("createTransactionResponse")); } @Test void testCreateOrderWithExistedServiceInstance() throws AlipayApiException { when(alipayService.createTransaction(anyDouble(), anyString(), anyString())).thenReturn("createTransactionResponse"); CreateServiceInstanceResponse response = new CreateServiceInstanceResponse(); response.setStatusCode(HttpStatus.OK.value()); when(serviceInstanceLifecycleService.createServiceInstance(any(), any(), anyBoolean(), any())).thenReturn(response); when(serviceManager.getServiceCost(any(), any(GetServiceCostParam.class))).thenReturn(new BaseResult<Double>("code", "message", Double.valueOf(0), "requestId")); List<OrderDTO> orderList = new ArrayList<>(); orderList.add(new OrderDTO()); ListResult<OrderDTO> orderDtoListResult = ListResult.genSuccessListResult(orderList, 1); when(orderOtsHelper.listOrders(anyList(), any(), anyList(), any(), anyList())).thenReturn(orderDtoListResult); CreateOrderParam createOrderParam = new CreateOrderParam(); createOrderParam.setType(PaymentType.ALIPAY); createOrderParam.setProductComponents("{\n" + " \"RegionId\":\"cn-hangzhou\",\n" + " \"SpecificationName\":\"低配版(Entry Level Package)\",\n" + " \"PayPeriod\":1,\n \"PayPeriodUnit\":\"Month\",\n" + " \"ServiceInstanceId\":\"si-123\"\n" + "}"); createOrderParam.setProductName(ProductName.SERVICE_INSTANCE); BaseResult<String> result = orderServiceImpl.createOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), createOrderParam); Assertions.assertTrue(result.getData().equals("createTransactionResponse")); } @Test void testGetOrder() { when(orderOtsHelper.getOrder(anyString(), anyLong())).thenReturn(new OrderDTO()); BaseResult<OrderDTO> result = orderServiceImpl.getOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), new GetOrderParam("orderId")); Assertions.assertTrue(result.getCode().equals("200")); } @Test void testListOrders() { when(orderOtsHelper.listOrders(any(), any(),anyList(), anyString(), anyList())).thenReturn(ListResult.genSuccessListResult(Arrays.asList(new OrderDTO()), 1, "requestId"));
/* *Copyright (c) Alibaba Group; *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.example.service.impl; class OrderServiceImplTest { @Mock AlipayService alipayService; @Mock OrderOtsHelper orderOtsHelper; @Mock WalletHelper walletHelper; @Mock ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Mock Logger log; @Mock private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; @Mock private ServiceManager serviceManager; @InjectMocks OrderServiceImpl orderServiceImpl; @BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } @Test void testCreateOrder() throws AlipayApiException { when(alipayService.createTransaction(anyDouble(), anyString(), anyString())).thenReturn("createTransactionResponse"); CreateServiceInstanceResponse response = new CreateServiceInstanceResponse(); response.setStatusCode(HttpStatus.OK.value()); when(serviceInstanceLifecycleService.createServiceInstance(any(), any(), anyBoolean(), any())).thenReturn(response); when(serviceManager.getServiceCost(any(), any(GetServiceCostParam.class))).thenReturn(new BaseResult<Double>("code", "message", Double.valueOf(0), "requestId")); List<OrderDTO> orderList = new ArrayList<>(); orderList.add(new OrderDTO()); ListResult<OrderDTO> orderDtoListResult = ListResult.genSuccessListResult(orderList, 1); when(orderOtsHelper.listOrders(anyList(), anyList(), anyList(), anyString(), anyList())).thenReturn(orderDtoListResult); CreateOrderParam createOrderParam = new CreateOrderParam(); createOrderParam.setType(PaymentType.ALIPAY); createOrderParam.setProductComponents("{\n" + " \"RegionId\":\"cn-hangzhou\",\n" + " \"SpecificationName\":\"低配版(Entry Level Package)\",\n" + " \"PayPeriod\":1,\n \"PayPeriodUnit\":\"Month\"\n" + "}"); createOrderParam.setProductName(ProductName.SERVICE_INSTANCE); BaseResult<String> result = orderServiceImpl.createOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), createOrderParam); Assertions.assertTrue(result.getData().equals("createTransactionResponse")); } @Test void testCreateOrderWithExistedServiceInstance() throws AlipayApiException { when(alipayService.createTransaction(anyDouble(), anyString(), anyString())).thenReturn("createTransactionResponse"); CreateServiceInstanceResponse response = new CreateServiceInstanceResponse(); response.setStatusCode(HttpStatus.OK.value()); when(serviceInstanceLifecycleService.createServiceInstance(any(), any(), anyBoolean(), any())).thenReturn(response); when(serviceManager.getServiceCost(any(), any(GetServiceCostParam.class))).thenReturn(new BaseResult<Double>("code", "message", Double.valueOf(0), "requestId")); List<OrderDTO> orderList = new ArrayList<>(); orderList.add(new OrderDTO()); ListResult<OrderDTO> orderDtoListResult = ListResult.genSuccessListResult(orderList, 1); when(orderOtsHelper.listOrders(anyList(), any(), anyList(), any(), anyList())).thenReturn(orderDtoListResult); CreateOrderParam createOrderParam = new CreateOrderParam(); createOrderParam.setType(PaymentType.ALIPAY); createOrderParam.setProductComponents("{\n" + " \"RegionId\":\"cn-hangzhou\",\n" + " \"SpecificationName\":\"低配版(Entry Level Package)\",\n" + " \"PayPeriod\":1,\n \"PayPeriodUnit\":\"Month\",\n" + " \"ServiceInstanceId\":\"si-123\"\n" + "}"); createOrderParam.setProductName(ProductName.SERVICE_INSTANCE); BaseResult<String> result = orderServiceImpl.createOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), createOrderParam); Assertions.assertTrue(result.getData().equals("createTransactionResponse")); } @Test void testGetOrder() { when(orderOtsHelper.getOrder(anyString(), anyLong())).thenReturn(new OrderDTO()); BaseResult<OrderDTO> result = orderServiceImpl.getOrder(new UserInfoModel("sub", "name", "loginName", "123", "123"), new GetOrderParam("orderId")); Assertions.assertTrue(result.getCode().equals("200")); } @Test void testListOrders() { when(orderOtsHelper.listOrders(any(), any(),anyList(), anyString(), anyList())).thenReturn(ListResult.genSuccessListResult(Arrays.asList(new OrderDTO()), 1, "requestId"));
ListOrdersParam listOrdersParam = new ListOrdersParam();
14
2023-11-01 08:19:34+00:00
12k
mioclient/oyvey-ported
src/main/java/me/alpha432/oyvey/features/gui/items/buttons/Slider.java
[ { "identifier": "OyVey", "path": "src/main/java/me/alpha432/oyvey/OyVey.java", "snippet": "public class OyVey implements ModInitializer, ClientModInitializer {\n public static final String NAME = \"OyVey\";\n public static final String VERSION = \"0.0.3 - 1.20.1\";\n\n public static float TIMER...
import me.alpha432.oyvey.OyVey; import me.alpha432.oyvey.features.gui.Component; import me.alpha432.oyvey.features.gui.OyVeyGui; import me.alpha432.oyvey.features.modules.client.ClickGui; import me.alpha432.oyvey.features.settings.Setting; import me.alpha432.oyvey.util.RenderUtil; import net.minecraft.client.gui.DrawContext; import net.minecraft.util.Formatting; import org.lwjgl.glfw.GLFW;
8,958
package me.alpha432.oyvey.features.gui.items.buttons; public class Slider extends Button { private final Number min; private final Number max; private final int difference; public Setting<Number> setting; public Slider(Setting<Number> setting) { super(setting.getName()); this.setting = setting; this.min = setting.getMin(); this.max = setting.getMax(); this.difference = this.max.intValue() - this.min.intValue(); this.width = 15; } @Override public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) { this.dragSetting(mouseX, mouseY); RenderUtil.rect(context.getMatrices(), this.x, this.y, this.x + (float) this.width + 7.4f, this.y + (float) this.height - 0.5f, !this.isHovering(mouseX, mouseY) ? 0x11555555 : -2007673515); RenderUtil.rect(context.getMatrices(), this.x, this.y, (this.setting.getValue()).floatValue() <= this.min.floatValue() ? this.x : this.x + ((float) this.width + 7.4f) * this.partialMultiplier(), this.y + (float) this.height - 0.5f, !this.isHovering(mouseX, mouseY) ? OyVey.colorManager.getColorWithAlpha(OyVey.moduleManager.getModuleByClass(ClickGui.class).hoverAlpha.getValue()) : OyVey.colorManager.getColorWithAlpha(OyVey.moduleManager.getModuleByClass(ClickGui.class).alpha.getValue())); drawString(this.getName() + " " + Formatting.GRAY + (this.setting.getValue() instanceof Float ? this.setting.getValue() : Double.valueOf((this.setting.getValue()).doubleValue())), this.x + 2.3f, this.y - 1.7f - (float) OyVeyGui.getClickGui().getTextOffset(), -1); } @Override public void mouseClicked(int mouseX, int mouseY, int mouseButton) { super.mouseClicked(mouseX, mouseY, mouseButton); if (this.isHovering(mouseX, mouseY)) { this.setSettingFromX(mouseX); } } @Override public boolean isHovering(int mouseX, int mouseY) {
package me.alpha432.oyvey.features.gui.items.buttons; public class Slider extends Button { private final Number min; private final Number max; private final int difference; public Setting<Number> setting; public Slider(Setting<Number> setting) { super(setting.getName()); this.setting = setting; this.min = setting.getMin(); this.max = setting.getMax(); this.difference = this.max.intValue() - this.min.intValue(); this.width = 15; } @Override public void drawScreen(DrawContext context, int mouseX, int mouseY, float partialTicks) { this.dragSetting(mouseX, mouseY); RenderUtil.rect(context.getMatrices(), this.x, this.y, this.x + (float) this.width + 7.4f, this.y + (float) this.height - 0.5f, !this.isHovering(mouseX, mouseY) ? 0x11555555 : -2007673515); RenderUtil.rect(context.getMatrices(), this.x, this.y, (this.setting.getValue()).floatValue() <= this.min.floatValue() ? this.x : this.x + ((float) this.width + 7.4f) * this.partialMultiplier(), this.y + (float) this.height - 0.5f, !this.isHovering(mouseX, mouseY) ? OyVey.colorManager.getColorWithAlpha(OyVey.moduleManager.getModuleByClass(ClickGui.class).hoverAlpha.getValue()) : OyVey.colorManager.getColorWithAlpha(OyVey.moduleManager.getModuleByClass(ClickGui.class).alpha.getValue())); drawString(this.getName() + " " + Formatting.GRAY + (this.setting.getValue() instanceof Float ? this.setting.getValue() : Double.valueOf((this.setting.getValue()).doubleValue())), this.x + 2.3f, this.y - 1.7f - (float) OyVeyGui.getClickGui().getTextOffset(), -1); } @Override public void mouseClicked(int mouseX, int mouseY, int mouseButton) { super.mouseClicked(mouseX, mouseY, mouseButton); if (this.isHovering(mouseX, mouseY)) { this.setSettingFromX(mouseX); } } @Override public boolean isHovering(int mouseX, int mouseY) {
for (Component component : OyVeyGui.getClickGui().getComponents()) {
1
2023-11-05 18:10:28+00:00
12k
EB-wilson/TooManyItems
src/main/java/tmi/ui/SchematicDesignerDialog.java
[ { "identifier": "TooManyItems", "path": "src/main/java/tmi/TooManyItems.java", "snippet": "public class TooManyItems extends Mod {\n public static RecipesManager recipesManager;\n public static RecipeItemManager itemsManager;\n public static ModAPI api;\n\n public static RecipesDialog recipesDialog;...
import arc.Core; import arc.Graphics; import arc.func.Boolc; import arc.func.Cons; import arc.func.Func; import arc.graphics.*; import arc.graphics.g2d.*; import arc.graphics.gl.FrameBuffer; import arc.input.KeyCode; import arc.math.Angles; import arc.math.Interp; import arc.math.Mathf; import arc.math.Rand; import arc.math.geom.Geometry; import arc.math.geom.Point2; import arc.math.geom.Rect; import arc.math.geom.Vec2; import arc.scene.Element; import arc.scene.Group; import arc.scene.actions.Actions; import arc.scene.event.*; import arc.scene.style.TextureRegionDrawable; import arc.scene.ui.CheckBox; import arc.scene.ui.Dialog; import arc.scene.ui.Image; import arc.scene.ui.TextField; import arc.scene.ui.layout.Cell; import arc.scene.ui.layout.Scl; import arc.scene.ui.layout.Table; import arc.scene.utils.Elem; import arc.struct.*; import arc.util.*; import arc.util.io.Reads; import arc.util.io.Writes; import mindustry.core.UI; import mindustry.gen.Icon; import mindustry.gen.Tex; import mindustry.graphics.Pal; import mindustry.type.Item; import mindustry.ui.Styles; import mindustry.ui.dialogs.BaseDialog; import mindustry.world.Block; import mindustry.world.meta.StatUnit; import tmi.TooManyItems; import tmi.recipe.EnvParameter; import tmi.recipe.Recipe; import tmi.recipe.RecipeItemStack; import tmi.recipe.RecipeType; import tmi.recipe.types.GeneratorRecipe; import tmi.recipe.types.RecipeItem; import tmi.util.Consts; import java.io.IOException; import java.util.Comparator; import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; import static arc.util.Align.*; import static mindustry.Vars.*; import static mindustry.Vars.ui;
10,625
buttons.button(Core.bundle.get("misc.ensure"), Styles.cleart, () -> { currCard.mul = balanceAmount; currCard.rebuildConfig.run(); rebuild.run(); }).disabled(b -> !balanceValid); }).growX(); }).grow().margin(8); resized(() -> { cell.maxSize(Core.scene.getWidth()/Scl.scl(), Core.scene.getHeight()/Scl.scl()); cell.get().invalidateHierarchy(); }); } }; protected OrderedSet<Card> selects = new OrderedSet<>(); protected Table removeArea, sideTools; protected boolean editLock, removeMode, selectMode; public SchematicDesignerDialog() { super(""); titleTable.clear(); cont.table().grow().get().add(view = new View()).grow(); addChild(menuTable); hidden(() -> { removeMode = false; removeArea.setHeight(0); removeArea.color.a = 0; selectMode = false; selects.clear(); editLock = false; hideMenu(); }); fill(t -> { t.table(c -> { Runnable re = () -> { c.clear(); if (Core.graphics.isPortrait()) c.center().bottom().button("@back", Icon.left, SchematicDesignerDialog.this::hide).size(210, 64f); else c.top().right().button(Icon.cancel, Styles.flati, 32, this::hide).margin(5); }; resized(re); re.run(); }).grow(); }); fill(t -> { t.bottom().table(Consts.darkGrayUI, area -> { removeArea = area; area.color.a = 0; area.add(Core.bundle.get("dialog.calculator.removeArea")); }).bottom().growX().height(0); }); fill(t -> { t.top().table(zoom -> { zoom.add("25%").color(Color.gray); zoom.table(Consts.darkGrayUIAlpha).fill().get().slider(0.25f, 1f, 0.01f, f -> { view.zoom.setScale(f); view.zoom.setOrigin(Align.center); view.zoom.setTransform(true); }).update(s -> s.setValue(view.zoom.scaleX)).width(400); zoom.add("100%").color(Color.gray); }).growX().top(); t.row(); t.add(Core.bundle.get("dialog.calculator.editLock"), Styles.outlineLabel).padTop(60).visible(() -> editLock); }); fill(t -> { AtomicBoolean fold = new AtomicBoolean(false); t.right().stack(new Table(){ Table main; { table(Tex.buttonSideLeft, but -> { but.touchable = Touchable.enabled; Image img = but.image(Icon.rightOpen).size(36).get(); but.clicked(() -> { if (fold.get()) { clearActions(); actions(Actions.moveTo(0, 0, 0.3f, Interp.pow2Out), Actions.run(() -> fold.set(false))); img.setOrigin(center); img.actions(Actions.rotateBy(180, 0.3f), Actions.rotateTo(0)); } else { clearActions(); actions(Actions.moveTo(main.getWidth(), 0, 0.3f, Interp.pow2Out), Actions.run(() -> fold.set(true))); img.setOrigin(center); img.actions(Actions.rotateBy(180, 0.3f), Actions.rotateTo(180)); } }); but.actions(Actions.run(() -> { img.setOrigin(center); img.setRotation(180); setPosition(main.getWidth(), 0); fold.set(true); })); but.hovered(() -> { img.setColor(Pal.accent); Core.graphics.cursor(Graphics.Cursor.SystemCursor.hand); }); but.exited(() -> { img.setColor(Color.white); Core.graphics.restoreCursor(); }); }).size(36, 122).padRight(-5); table(Tex.buttonSideLeft, main -> { this.main = main; }).growY().width(320); } }).fillX().growY().padTop(60).padBottom(60); }); fill(t -> { t.left().table(Consts.darkGrayUI, sideBar -> { sideBar.top().pane(Styles.noBarPane, list -> { sideTools = list; list.top().defaults().size(40).padBottom(8); list.button(Icon.add, Styles.clearNonei, 32, () -> {
package tmi.ui; public class SchematicDesignerDialog extends BaseDialog { public static final int FI_HEAD = 0xceadbf01; private static final Seq<ItemLinker> seq = new Seq<>(); private static final Vec2 tmp = new Vec2(); private static final Rect rect = new Rect(); protected final View view; protected final Table menuTable = new Table(){{ visible = false; }}; protected final Dialog export = new Dialog("", Consts.transparentBack){{ titleTable.clear(); cont.table(Consts.darkGrayUIAlpha, t -> { t.table(Consts.darkGrayUI, top -> { top.left().add(Core.bundle.get("dialog.calculator.export")).pad(8); }).grow().padBottom(12); t.row(); t.table(Consts.darkGrayUI, inner -> { }).size(640, 720); t.row(); t.table(buttons -> { buttons.right().defaults().size(92, 36).pad(6); buttons.button(Core.bundle.get("misc.cancel"), Styles.cleart, this::hide); buttons.button(Core.bundle.get("misc.export"), Styles.cleart, () -> {}); }).growX(); }).fill().margin(8); }}; protected final Dialog balance = new Dialog("", Consts.transparentBack){ RecipeCard currCard; int balanceAmount; boolean balanceValid; Runnable rebuild; { titleTable.clear(); Cell<Table> cell = cont.table(Consts.darkGrayUIAlpha, t -> { t.table(Consts.darkGrayUI, top -> { top.left().add(Core.bundle.get("dialog.calculator.balance")).pad(8); }).grow().padBottom(12); t.row(); t.table(Consts.darkGrayUI).grow().margin(12).get().top().pane(Styles.smallPane, inner -> { shown(rebuild = () -> { inner.clearChildren(); inner.defaults().left().growX().fillY().pad(5); currCard = selects.size == 1 && selects.first() instanceof RecipeCard c? c: null; inner.add(Core.bundle.get("dialog.calculator.targetRec")).color(Pal.accent); if (currCard != null){ currCard.calculateEfficiency(); inner.row(); inner.table(Tex.pane, ls -> { ls.pane(Styles.noBarPane, p -> { p.top().left().defaults().growX().height(45).minWidth(160).left().padLeft(4).padRight(4); p.add(Core.bundle.get("dialog.calculator.materials")).labelAlign(center).color(Color.lightGray); p.table(Consts.grayUIAlpha).margin(6).get().add(Core.bundle.get("dialog.calculator.expectAmount")).labelAlign(center).color(Color.lightGray); p.add(Core.bundle.get("dialog.calculator.configured")).labelAlign(center).color(Color.lightGray); p.row(); for (RecipeItemStack stack : currCard.recipe.materials.values()) { if (((GeneratorRecipe) RecipeType.generator).isPower(stack.item)) continue; p.table(left -> { left.left(); left.image(stack.item.icon()).size(36).scaling(Scaling.fit); left.table(num -> { num.left().defaults().fill().left(); num.add(stack.item.localizedName()); num.row(); num.table(amo -> { amo.left().defaults().left(); String amount = stack.isAttribute? stack.amount > 1000? UI.formatAmount((long) stack.amount): Integer.toString(Mathf.round(stack.amount)): (stack.amount*60 > 1000? UI.formatAmount((long) (stack.amount*60)): Strings.autoFixed(stack.amount*60, 1)) + "/s"; amo.add(amount).color(Color.gray); if (currCard.multiplier != 1 && !stack.isAttribute && !stack.isBooster) amo.add(Mathf.round(currCard.multiplier*100) + "%").padLeft(5).color(currCard.multiplier > 1? Pal.heal: Color.red); amo.add("x" + currCard.mul).color(Pal.gray); }); }).padLeft(5); }); float amount = stack.isAttribute? stack.amount*currCard.mul: stack.isBooster? stack.amount*currCard.mul*currCard.scale*60: stack.amount*currCard.mul*currCard.multiplier*60; p.table(Consts.grayUIAlpha).get().left().marginLeft(6).marginRight(6).add((amount > 1000? UI.formatAmount((long) amount): Strings.autoFixed(amount, 1)) + (stack.isAttribute? "": "/s")); p.table(stat -> { stat.left().defaults().left(); ItemLinker input = currCard.in.find(e -> e.item == stack.item); if (!stack.isAttribute && input == null){ stat.add(Core.bundle.get("misc.noInput")); } else { if (stack.isAttribute){ if (currCard.environments.getAttribute(stack.item) <= 0) stat.add(Core.bundle.get("misc.unset")); else stat.add(currCard.environments.getAttribute(stack.item) + ""); } else if (stack.optionalCons){ stat.table(assign -> { assign.left().defaults().left(); if (input.isNormalized()){ float a = input.links.size == 1? input.links.orderedKeys().first().expectAmount: -1; assign.add(Core.bundle.get("misc.provided") + (a <= 0? "": " [lightgray]" + (a*60 > 1000? UI.formatAmount((long) (a*60)): Strings.autoFixed(a*60, 1)) + "/s")).growX(); assign.check("", currCard.optionalSelected.contains(stack.item), b -> { if (b) currCard.optionalSelected.add(stack.item); else currCard.optionalSelected.remove(stack.item); currCard.rebuildConfig.run(); rebuild.run(); }).margin(4).fill(); } else { assign.add(Core.bundle.get("misc.assignInvalid")).growX(); } }).growX(); } else { if (input.isNormalized()){ float a = input.links.size == 1? input.links.orderedKeys().first().expectAmount: -1; stat.add(Core.bundle.get("misc.provided") + (a <= 0? "": " [lightgray]" + (a*60 > 1000? UI.formatAmount((long) (a*60)): Strings.autoFixed(a*60, 1)) + "/s")); } else { stat.add(Core.bundle.get("misc.assignInvalid")); } } } }); p.row(); } }).maxHeight(240).scrollX(false).growX().fillY(); }); inner.row(); inner.image(Icon.down).scaling(Scaling.fit).pad(12); inner.row(); inner.table(Tex.pane, ls -> { ls.pane(Styles.noBarPane, p -> { p.top().left().defaults().growX().height(45).minWidth(160).left().padLeft(4).padRight(4); p.add(Core.bundle.get("dialog.calculator.productions")).labelAlign(center).color(Color.lightGray); p.table(Consts.grayUIAlpha).margin(6).get().add(Core.bundle.get("dialog.calculator.actualAmount")).labelAlign(center).color(Color.lightGray); p.add(Core.bundle.get("dialog.calculator.expectAmount")).labelAlign(center).color(Color.lightGray); p.row(); balanceValid = false; balanceAmount = 0; for (RecipeItemStack stack : currCard.recipe.productions.values()) { if (((GeneratorRecipe) RecipeType.generator).isPower(stack.item)) continue; p.table(left -> { left.left(); left.image(stack.item.icon()).size(36).scaling(Scaling.fit); left.table(num -> { num.left().defaults().fill().left(); num.add(stack.item.localizedName()); num.row(); num.table(amo -> { amo.left().defaults().left(); amo.add((stack.amount*60 > 1000? UI.formatAmount((long) (stack.amount*60)): Strings.autoFixed(stack.amount*60, 1)) + "/s").color(Color.gray); if (currCard.efficiency != 1) amo.add(Mathf.round(currCard.efficiency*100) + "%").padLeft(5).color(currCard.efficiency > 1? Pal.heal: Color.red); amo.add("x" + currCard.mul).color(Pal.gray); }); }).padLeft(5); }); float[] expected = new float[1]; float amount = stack.amount*currCard.mul*currCard.efficiency; p.table(Consts.grayUIAlpha, actual -> { actual.defaults().growX().left(); actual.add((amount*60 > 1000? UI.formatAmount((long) (amount*60)): Strings.autoFixed(amount*60, 1)) + "/s"); actual.add("").update(l -> { float diff = amount - expected[0]; if (balanceValid){ if (Mathf.zero(diff)){ l.setText(Core.bundle.get("misc.balanced")); l.setColor(Color.lightGray); } else { l.setText((diff > 0? "+": "") + (diff*60 > 1000? UI.formatAmount((long) (diff*60)): Strings.autoFixed(diff*60, 1)) + "/s"); l.setColor(diff > 0? Pal.accent: Color.red); } } else { l.setText(""); } }); }).left().marginLeft(6).marginRight(6); ItemLinker linker = currCard.out.find(e -> e.item == stack.item); if (linker != null) { p.table(tab -> { tab.defaults().growX().fillY(); if (linker.links.size == 1){ ItemLinker other = linker.links.orderedKeys().first(); tab.add(Core.bundle.format("dialog.calculator.assigned", (other.expectAmount*60 > 1000? UI.formatAmount((long) (other.expectAmount*60)): Strings.autoFixed(other.expectAmount*60, 1)) + "/s")); expected[0] = other.expectAmount; balanceValid = true; balanceAmount = Mathf.ceil(Math.max(other.expectAmount/(stack.amount*currCard.efficiency), balanceAmount)); } else if (linker.links.isEmpty()){ tab.add(Core.bundle.get("misc.unset")); } else { boolean anyUnset = false; float amo = 0; for (ItemLinker other : linker.links.keys()) { float rate = other.links.get(linker)[0]; if (!other.isNormalized()){ anyUnset = true; break; } else if (rate < 0) rate = 1; amo += rate*other.expectAmount; } expected[0] = amo; if (!anyUnset) { tab.add(Core.bundle.format("dialog.calculator.assigned", (amo*60 > 1000? UI.formatAmount((long) (amo*60)): Strings.autoFixed(amo*60, 1)) + "/s")); balanceValid = true; balanceAmount = Mathf.ceil(Math.max(amo/(stack.amount*currCard.efficiency), balanceAmount)); } else tab.add(Core.bundle.get("misc.assignInvalid")).color(Color.red); } }); } else p.add("<error>"); p.row(); } }).maxHeight(240).scrollX(false).growX().fillY(); }).grow(); inner.row(); inner.table(scl -> { scl.left(); AtomicBoolean fold = new AtomicBoolean(false); float[] scale = new float[]{currCard.scale}; Table tab = scl.table().growX().get(); tab.left().defaults().left().padRight(8); Runnable doFold = () -> { tab.clearChildren(); if (fold.get()) { tab.add(Core.bundle.get("dialog.calculator.effScale")); tab.field(Strings.autoFixed(scale[0]*100, 1), TextField.TextFieldFilter.digitsOnly, i -> { try { scale[0] = i.isEmpty()? 0: Float.parseFloat(i)/100; } catch (Throwable ignored){} }).growX().get().setAlignment(right); tab.add("%").color(Color.gray); fold.set(false); } else { tab.add(Core.bundle.get("dialog.calculator.effScale") + Strings.autoFixed(currCard.scale*100, 1) + "%"); fold.set(true); } }; doFold.run(); scl.button(Icon.pencilSmall, Styles.clearNonei, 24, () -> { if (fold.get()){ doFold.run(); } else { currCard.scale = scale[0]; currCard.rebuildConfig.run(); rebuild.run(); } }).update(i -> i.getStyle().imageUp = fold.get()? Icon.pencilSmall: Icon.okSmall).fill().margin(5); }); inner.row(); inner.add(Core.bundle.format("dialog.calculator.expectedMultiple", balanceValid? balanceAmount + "x": Core.bundle.get("misc.invalid"))); inner.row(); inner.add(Core.bundle.format("dialog.calculator.currentMul", currCard.mul, balanceValid? (currCard.mul == balanceAmount? "[gray]" + Core.bundle.get("misc.balanced"): (currCard.mul > balanceAmount? "[accent]+": "[red]") + (currCard.mul - balanceAmount)): "")); } else { inner.add("misc.unset"); } }); }).grow(); t.row(); t.table(buttons -> { buttons.right().defaults().size(92, 36).pad(6); buttons.button(Core.bundle.get("misc.cancel"), Styles.cleart, this::hide); buttons.button(Core.bundle.get("misc.ensure"), Styles.cleart, () -> { currCard.mul = balanceAmount; currCard.rebuildConfig.run(); rebuild.run(); }).disabled(b -> !balanceValid); }).growX(); }).grow().margin(8); resized(() -> { cell.maxSize(Core.scene.getWidth()/Scl.scl(), Core.scene.getHeight()/Scl.scl()); cell.get().invalidateHierarchy(); }); } }; protected OrderedSet<Card> selects = new OrderedSet<>(); protected Table removeArea, sideTools; protected boolean editLock, removeMode, selectMode; public SchematicDesignerDialog() { super(""); titleTable.clear(); cont.table().grow().get().add(view = new View()).grow(); addChild(menuTable); hidden(() -> { removeMode = false; removeArea.setHeight(0); removeArea.color.a = 0; selectMode = false; selects.clear(); editLock = false; hideMenu(); }); fill(t -> { t.table(c -> { Runnable re = () -> { c.clear(); if (Core.graphics.isPortrait()) c.center().bottom().button("@back", Icon.left, SchematicDesignerDialog.this::hide).size(210, 64f); else c.top().right().button(Icon.cancel, Styles.flati, 32, this::hide).margin(5); }; resized(re); re.run(); }).grow(); }); fill(t -> { t.bottom().table(Consts.darkGrayUI, area -> { removeArea = area; area.color.a = 0; area.add(Core.bundle.get("dialog.calculator.removeArea")); }).bottom().growX().height(0); }); fill(t -> { t.top().table(zoom -> { zoom.add("25%").color(Color.gray); zoom.table(Consts.darkGrayUIAlpha).fill().get().slider(0.25f, 1f, 0.01f, f -> { view.zoom.setScale(f); view.zoom.setOrigin(Align.center); view.zoom.setTransform(true); }).update(s -> s.setValue(view.zoom.scaleX)).width(400); zoom.add("100%").color(Color.gray); }).growX().top(); t.row(); t.add(Core.bundle.get("dialog.calculator.editLock"), Styles.outlineLabel).padTop(60).visible(() -> editLock); }); fill(t -> { AtomicBoolean fold = new AtomicBoolean(false); t.right().stack(new Table(){ Table main; { table(Tex.buttonSideLeft, but -> { but.touchable = Touchable.enabled; Image img = but.image(Icon.rightOpen).size(36).get(); but.clicked(() -> { if (fold.get()) { clearActions(); actions(Actions.moveTo(0, 0, 0.3f, Interp.pow2Out), Actions.run(() -> fold.set(false))); img.setOrigin(center); img.actions(Actions.rotateBy(180, 0.3f), Actions.rotateTo(0)); } else { clearActions(); actions(Actions.moveTo(main.getWidth(), 0, 0.3f, Interp.pow2Out), Actions.run(() -> fold.set(true))); img.setOrigin(center); img.actions(Actions.rotateBy(180, 0.3f), Actions.rotateTo(180)); } }); but.actions(Actions.run(() -> { img.setOrigin(center); img.setRotation(180); setPosition(main.getWidth(), 0); fold.set(true); })); but.hovered(() -> { img.setColor(Pal.accent); Core.graphics.cursor(Graphics.Cursor.SystemCursor.hand); }); but.exited(() -> { img.setColor(Color.white); Core.graphics.restoreCursor(); }); }).size(36, 122).padRight(-5); table(Tex.buttonSideLeft, main -> { this.main = main; }).growY().width(320); } }).fillX().growY().padTop(60).padBottom(60); }); fill(t -> { t.left().table(Consts.darkGrayUI, sideBar -> { sideBar.top().pane(Styles.noBarPane, list -> { sideTools = list; list.top().defaults().size(40).padBottom(8); list.button(Icon.add, Styles.clearNonei, 32, () -> {
TooManyItems.recipesDialog.toggle = r -> {
0
2023-11-05 11:39:21+00:00
12k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/LibraryFragment.java
[ { "identifier": "MyViewPagerAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/viewpager/MyViewPagerAdapter.java", "snippet": "public class MyViewPagerAdapter extends FragmentStatePagerAdapter {\n public MyViewPagerAdapter(@NonNull FragmentManager fm, int behavior) {\n super(fm,...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentStatePagerAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.daominh.quickmem.adapter.viewpager.MyViewPagerAdapter; import com.daominh.quickmem.data.dao.UserDAO; import com.daominh.quickmem.data.model.User; import com.daominh.quickmem.databinding.FragmentLibraryBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateClassActivity; import com.daominh.quickmem.ui.activities.create.CreateFolderActivity; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.google.android.material.tabs.TabLayout; import org.jetbrains.annotations.NotNull;
9,343
package com.daominh.quickmem.ui.fragments.home; public class LibraryFragment extends Fragment { private FragmentLibraryBinding binding;
package com.daominh.quickmem.ui.fragments.home; public class LibraryFragment extends Fragment { private FragmentLibraryBinding binding;
private UserSharePreferences userSharePreferences;
3
2023-11-07 16:56:39+00:00
12k
FRCTeam2910/2023CompetitionRobot-Public
src/main/java/org/frcteam2910/c2023/commands/ArmToPoseCommand.java
[ { "identifier": "ArmSubsystem", "path": "src/main/java/org/frcteam2910/c2023/subsystems/arm/ArmSubsystem.java", "snippet": "public class ArmSubsystem extends SubsystemBase {\n // Distance from pivot point to arm base\n public static final double ARM_PIVOT_OFFSET = Units.inchesToMeters(6.75 - 0.125...
import java.util.function.BooleanSupplier; import java.util.function.Supplier; import edu.wpi.first.math.util.Units; import edu.wpi.first.wpilibj2.command.CommandBase; import org.frcteam2910.c2023.subsystems.arm.ArmSubsystem; import org.frcteam2910.c2023.subsystems.intake.IntakeSubsystem; import org.frcteam2910.c2023.util.ArmPositions; import org.frcteam2910.c2023.util.GamePiece; import org.frcteam2910.c2023.util.GridLevel; import org.frcteam2910.c2023.util.OperatorDashboard;
10,413
package org.frcteam2910.c2023.commands; public class ArmToPoseCommand extends CommandBase { private static final double HIGH_SHOULDER_OFFSET = Units.degreesToRadians(1.0); private static final double MID_SHOULDER_OFFSET = Units.degreesToRadians(1.5); private static final double HIGH_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double MID_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double HIGH_WRIST_OFFSET = Units.degreesToRadians(0.0); private static final double MID_WRIST_OFFSET = Units.degreesToRadians(0.0); private final ArmSubsystem arm; private Supplier<ArmPositions> targetPoseSupplier; private final boolean perpetual; private final BooleanSupplier aButton; private final OperatorDashboard dashboard;
package org.frcteam2910.c2023.commands; public class ArmToPoseCommand extends CommandBase { private static final double HIGH_SHOULDER_OFFSET = Units.degreesToRadians(1.0); private static final double MID_SHOULDER_OFFSET = Units.degreesToRadians(1.5); private static final double HIGH_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double MID_EXTENSION_OFFSET = Units.inchesToMeters(0.0); private static final double HIGH_WRIST_OFFSET = Units.degreesToRadians(0.0); private static final double MID_WRIST_OFFSET = Units.degreesToRadians(0.0); private final ArmSubsystem arm; private Supplier<ArmPositions> targetPoseSupplier; private final boolean perpetual; private final BooleanSupplier aButton; private final OperatorDashboard dashboard;
private final IntakeSubsystem intake;
1
2023-11-03 02:12:12+00:00
12k
YunaBraska/type-map
src/main/java/berlin/yuna/typemap/model/TypeList.java
[ { "identifier": "JsonDecoder", "path": "src/main/java/berlin/yuna/typemap/logic/JsonDecoder.java", "snippet": "public class JsonDecoder {\n\n /**\n * Converts a JSON string to a LinkedTypeMap.\n * This method first converts the JSON string into an appropriate Java object (Map, List, or other ...
import berlin.yuna.typemap.logic.JsonDecoder; import berlin.yuna.typemap.logic.JsonEncoder; import java.util.*; import java.util.function.IntFunction; import java.util.function.Supplier; import static berlin.yuna.typemap.logic.TypeConverter.collectionOf; import static berlin.yuna.typemap.logic.TypeConverter.convertObj; import static berlin.yuna.typemap.model.TypeMap.convertAndMap; import static berlin.yuna.typemap.model.TypeMap.treeGet; import static java.util.Optional.ofNullable;
7,250
package berlin.yuna.typemap.model; /** * {@link TypeList} is a specialized implementation of {@link ArrayList} that offers enhanced * functionality for type-safe data retrieval and manipulation. It is designed for * high-performance type conversion while being native-ready for GraalVM. The {@link TypeList} * class provides methods to retrieve data in various forms (single objects, collections, * arrays, or maps) while ensuring type safety without the need for reflection. */ public class TypeList extends ArrayList<Object> implements TypeListI<TypeList> { /** * Default constructor for creating an empty {@link TypeList}. */ public TypeList() { this((Collection<?>) null); } /** * Constructs a new {@link TypeList} of the specified json. */ public TypeList(final String json) { this(JsonDecoder.jsonListOf(json)); } /** * Constructs a new {@link TypeList} with the same mappings as the specified map. * * @param map The initial map to copy mappings from, can be null. */ public TypeList(final Collection<?> map) { ofNullable(map).ifPresent(super::addAll); } /** * Adds the specified value * * @param value the value to be added * @return the updated TypeList instance for chaining. */ @Override public TypeList addd(final Object value) { super.add(value); return this; } /** * Adds the specified value * * @param index the index whose associated value is to be returned. * @param value the value to be added * @return the updated {@link TypeList} instance for chaining. */ @Override public TypeList addd(final int index, final Object value) { if (index >= 0 && index < this.size()) { super.add(index, value); } else { super.add(value); } return this; } /** * Adds the specified value * * @param index the index whose associated value is to be returned. * @param value the value to be added * @return the updated {@link TypeList} instance for chaining. */ public TypeList addd(final Object index, final Object value) { if (index == null) { super.add(value); } else if (index instanceof Number) { this.addd(((Number) index).intValue(), value); } return this; } /** * Adds all entries to this specified List * * @param collection which provides all entries to add * @return the updated {@link TypeList} instance for chaining. */ @Override public TypeList adddAll(final Collection<?> collection) { super.addAll(collection); return this; } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list */ @Override public Object get(final int index) { return index >= 0 && index < this.size() ? super.get(index) : null; } /** * Retrieves the value to which the specified index, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param index the index whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return value if present and convertible, else null. */ public <T> T get(final int index, final Class<T> type) { return gett(index, type).orElse(null); } /** * Retrieves the value to which the specified index, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param index the index whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ @Override public <T> Optional<T> gett(final int index, final Class<T> type) { return ofNullable(treeGet(this, index)).map(object -> convertObj(object, type)); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param path the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ @Override public <T> Optional<T> gett(final Class<T> type, final Object... path) { return ofNullable(treeGet(this, path)).map(object -> convertObj(object, type)); } /** * This method converts the retrieved map to a list of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a {@link TypeList} of the specified key and value types. */ public TypeList getList(final Object... path) { return getList(TypeList::new, Object.class, path); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param index The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final int index, final Class<E> itemType) { return getList(ArrayList::new, itemType, index); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param path The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final Class<E> itemType, final Object... path) { return getList(ArrayList::new, itemType, path); } /** * Retrieves a collection associated at the specified index and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param index The index whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ @Override public <T extends Collection<E>, E> T getList(final int index, final Supplier<? extends T> output, final Class<E> itemType) { return collectionOf(super.get(index), output, itemType); } /** * Retrieves a collection associated with the specified key and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param path The key whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ @Override public <T extends Collection<E>, E> T getList(final Supplier<? extends T> output, final Class<E> itemType, final Object... path) { return collectionOf(treeGet(this, path), output, itemType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a map of the specified key and value types. */ @Override public LinkedTypeMap getMap(final Object... path) { return getMap(LinkedTypeMap::new, Object.class, Object.class, path); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param index The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final int index, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(treeGet(this, index), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param path The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param index The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ @Override public <K, V, M extends Map<K, V>> M getMap(final int index, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(treeGet(this, index), output, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param path The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ @Override public <K, V, M extends Map<K, V>> M getMap(final Supplier<M> output, final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), output, keyType, valueType); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param index The index whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final int index, final E[] typeIndicator, final Class<E> componentType) { final ArrayList<E> result = getList(index, ArrayList::new, componentType); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ @Override public <E> E[] getArray(final E[] typeIndicator, final Class<E> componentType, final Object... path) { final ArrayList<E> result = getList(ArrayList::new, componentType, path); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param index The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ @Override public <E> E[] getArray(final int index, final IntFunction<E[]> generator, final Class<E> componentType) { return getList(index, ArrayList::new, componentType).stream().toArray(generator); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ @Override public <E> E[] getArray(final IntFunction<E[]> generator, final Class<E> componentType, final Object... path) { return getList(ArrayList::new, componentType, path).stream().toArray(generator); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeMapI} * * @return {@link Optional#empty()} if current object is not a {@link TypeMapI}, else returns self. */ @SuppressWarnings("java:S1452") public Optional<TypeMapI<?>> typeMap() { return Optional.empty(); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeListI} * * @return {@link Optional#empty()} if current object is not a {@link TypeListI}, else returns self. */ @SuppressWarnings("java:S1452") public Optional<TypeListI<?>> typeList() { return Optional.of(this); } /** * Converts any object to its JSON representation. * This method intelligently dispatches the conversion task based on the type of the object, * handling Maps, Collections, Arrays (both primitive and object types), and other objects. * * @param path The key whose associated value is to be returned. * @return A JSON representation of the key value as a String. */ @Override public String toJson(final Object... path) {
package berlin.yuna.typemap.model; /** * {@link TypeList} is a specialized implementation of {@link ArrayList} that offers enhanced * functionality for type-safe data retrieval and manipulation. It is designed for * high-performance type conversion while being native-ready for GraalVM. The {@link TypeList} * class provides methods to retrieve data in various forms (single objects, collections, * arrays, or maps) while ensuring type safety without the need for reflection. */ public class TypeList extends ArrayList<Object> implements TypeListI<TypeList> { /** * Default constructor for creating an empty {@link TypeList}. */ public TypeList() { this((Collection<?>) null); } /** * Constructs a new {@link TypeList} of the specified json. */ public TypeList(final String json) { this(JsonDecoder.jsonListOf(json)); } /** * Constructs a new {@link TypeList} with the same mappings as the specified map. * * @param map The initial map to copy mappings from, can be null. */ public TypeList(final Collection<?> map) { ofNullable(map).ifPresent(super::addAll); } /** * Adds the specified value * * @param value the value to be added * @return the updated TypeList instance for chaining. */ @Override public TypeList addd(final Object value) { super.add(value); return this; } /** * Adds the specified value * * @param index the index whose associated value is to be returned. * @param value the value to be added * @return the updated {@link TypeList} instance for chaining. */ @Override public TypeList addd(final int index, final Object value) { if (index >= 0 && index < this.size()) { super.add(index, value); } else { super.add(value); } return this; } /** * Adds the specified value * * @param index the index whose associated value is to be returned. * @param value the value to be added * @return the updated {@link TypeList} instance for chaining. */ public TypeList addd(final Object index, final Object value) { if (index == null) { super.add(value); } else if (index instanceof Number) { this.addd(((Number) index).intValue(), value); } return this; } /** * Adds all entries to this specified List * * @param collection which provides all entries to add * @return the updated {@link TypeList} instance for chaining. */ @Override public TypeList adddAll(final Collection<?> collection) { super.addAll(collection); return this; } /** * Returns the element at the specified position in this list. * * @param index index of the element to return * @return the element at the specified position in this list */ @Override public Object get(final int index) { return index >= 0 && index < this.size() ? super.get(index) : null; } /** * Retrieves the value to which the specified index, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param index the index whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return value if present and convertible, else null. */ public <T> T get(final int index, final Class<T> type) { return gett(index, type).orElse(null); } /** * Retrieves the value to which the specified index, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param index the index whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ @Override public <T> Optional<T> gett(final int index, final Class<T> type) { return ofNullable(treeGet(this, index)).map(object -> convertObj(object, type)); } /** * Retrieves the value to which the specified key is mapped, and attempts to * convert it to the specified type. * * @param <T> The target type for conversion. * @param path the key whose associated value is to be returned. * @param type the Class object of the type to convert to. * @return an Optional containing the value if present and convertible, else empty. */ @Override public <T> Optional<T> gett(final Class<T> type, final Object... path) { return ofNullable(treeGet(this, path)).map(object -> convertObj(object, type)); } /** * This method converts the retrieved map to a list of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a {@link TypeList} of the specified key and value types. */ public TypeList getList(final Object... path) { return getList(TypeList::new, Object.class, path); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param index The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final int index, final Class<E> itemType) { return getList(ArrayList::new, itemType, index); } /** * Retrieves a collection associated at the specified index and converts it to * the specified element type. * * @param <E> The type of elements in the collection. * @param path The index whose associated value is to be returned. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ public <E> List<E> getList(final Class<E> itemType, final Object... path) { return getList(ArrayList::new, itemType, path); } /** * Retrieves a collection associated at the specified index and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param index The index whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ @Override public <T extends Collection<E>, E> T getList(final int index, final Supplier<? extends T> output, final Class<E> itemType) { return collectionOf(super.get(index), output, itemType); } /** * Retrieves a collection associated with the specified key and converts it to * the specified collection type and element type. * * @param <T> The type of the collection to be returned. * @param <E> The type of elements in the collection. * @param path The key whose associated value is to be returned. * @param output The supplier providing a new collection instance. * @param itemType The class of the items in the collection. * @return a collection of the specified type and element type. */ @Override public <T extends Collection<E>, E> T getList(final Supplier<? extends T> output, final Class<E> itemType, final Object... path) { return collectionOf(treeGet(this, path), output, itemType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param path The key whose associated value is to be returned. * @return a map of the specified key and value types. */ @Override public LinkedTypeMap getMap(final Object... path) { return getMap(LinkedTypeMap::new, Object.class, Object.class, path); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param index The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final int index, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(treeGet(this, index), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param path The key whose associated value is to be returned. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ public <K, V> Map<K, V> getMap(final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), LinkedHashMap::new, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param index The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ @Override public <K, V, M extends Map<K, V>> M getMap(final int index, final Supplier<M> output, final Class<K> keyType, final Class<V> valueType) { return convertAndMap(treeGet(this, index), output, keyType, valueType); } /** * Retrieves a map of a specific type associated with the specified key. * This method converts the retrieved map to a map of the specified key and value types. * * @param <K> The type of keys in the returned map. * @param <V> The type of values in the returned map. * @param <M> The type of the map to be returned. * @param path The key whose associated value is to be returned. * @param output A supplier providing a new map instance. * @param keyType The class of the map's key type. * @param valueType The class of the map's value type. * @return a map of the specified key and value types. */ @Override public <K, V, M extends Map<K, V>> M getMap(final Supplier<M> output, final Class<K> keyType, final Class<V> valueType, final Object... path) { return convertAndMap(treeGet(this, path), output, keyType, valueType); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param index The index whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ public <E> E[] getArray(final int index, final E[] typeIndicator, final Class<E> componentType) { final ArrayList<E> result = getList(index, ArrayList::new, componentType); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method is useful for cases where the type indicator is an array instance. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param typeIndicator An array instance indicating the type of array to return. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ @Override public <E> E[] getArray(final E[] typeIndicator, final Class<E> componentType, final Object... path) { final ArrayList<E> result = getList(ArrayList::new, componentType, path); return result.toArray(Arrays.copyOf(typeIndicator, result.size())); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param index The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ @Override public <E> E[] getArray(final int index, final IntFunction<E[]> generator, final Class<E> componentType) { return getList(index, ArrayList::new, componentType).stream().toArray(generator); } /** * Retrieves an array of a specific type associated with the specified key. * This method allows for custom array generation using a generator function. * * @param <E> The component type of the array. * @param path The key whose associated value is to be returned. * @param generator A function to generate the array of the required size. * @param componentType The class of the array's component type. * @return an array of the specified component type. */ @Override public <E> E[] getArray(final IntFunction<E[]> generator, final Class<E> componentType, final Object... path) { return getList(ArrayList::new, componentType, path).stream().toArray(generator); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeMapI} * * @return {@link Optional#empty()} if current object is not a {@link TypeMapI}, else returns self. */ @SuppressWarnings("java:S1452") public Optional<TypeMapI<?>> typeMap() { return Optional.empty(); } /** * Fluent typecheck if the current {@link TypeContainer} is a {@link TypeListI} * * @return {@link Optional#empty()} if current object is not a {@link TypeListI}, else returns self. */ @SuppressWarnings("java:S1452") public Optional<TypeListI<?>> typeList() { return Optional.of(this); } /** * Converts any object to its JSON representation. * This method intelligently dispatches the conversion task based on the type of the object, * handling Maps, Collections, Arrays (both primitive and object types), and other objects. * * @param path The key whose associated value is to be returned. * @return A JSON representation of the key value as a String. */ @Override public String toJson(final Object... path) {
return JsonEncoder.toJson(treeGet(this, path));
1
2023-11-09 14:40:13+00:00
12k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCore.java
[ { "identifier": "ActivationCode", "path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/ActivationCode.java", "snippet": "public class ActivationCode implements Parcelable {\n private String activationCode;\n\n private final Boolean isValid;\n private String acFormat;\n private String ...
import com.infineon.esim.lpa.core.dtos.result.local.SetNicknameResult; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult; import com.infineon.esim.lpa.core.dtos.result.remote.RemoteError; import java.util.List; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.local.ClearNotificationsResult; import com.infineon.esim.lpa.core.dtos.result.local.DeleteResult; import com.infineon.esim.lpa.core.dtos.result.local.DisableResult; import com.infineon.esim.lpa.core.dtos.result.local.EnableResult;
7,460
/* * 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; public interface LocalProfileAssistantCore { // Profile management String getEID() throws Exception; EuiccInfo getEuiccInfo2() throws Exception; List<ProfileMetadata> getProfiles() throws Exception; // Profile operations EnableResult enableProfile(String iccid, boolean refreshFlag) throws Exception; DisableResult disableProfile(String iccid) throws Exception; DeleteResult deleteProfile(String iccid) throws Exception; SetNicknameResult setNickname(String iccid, String nickname) throws Exception; // Profile download AuthenticateResult authenticate(ActivationCode activationCode) throws Exception; DownloadResult downloadProfile(String confirmationCode) throws Exception; CancelSessionResult cancelSession(long cancelSessionReasonValue) throws Exception; // Notification management
/* * 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; public interface LocalProfileAssistantCore { // Profile management String getEID() throws Exception; EuiccInfo getEuiccInfo2() throws Exception; List<ProfileMetadata> getProfiles() throws Exception; // Profile operations EnableResult enableProfile(String iccid, boolean refreshFlag) throws Exception; DisableResult disableProfile(String iccid) throws Exception; DeleteResult deleteProfile(String iccid) throws Exception; SetNicknameResult setNickname(String iccid, String nickname) throws Exception; // Profile download AuthenticateResult authenticate(ActivationCode activationCode) throws Exception; DownloadResult downloadProfile(String confirmationCode) throws Exception; CancelSessionResult cancelSession(long cancelSessionReasonValue) throws Exception; // Notification management
HandleNotificationsResult handleNotifications() throws Exception;
11
2023-11-06 02:41:13+00:00
12k
viego1999/xuecheng-plus-project
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,948
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(); // 课程基本信息和营销信息 CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.queryCourseBaseById(courseId); BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre); // 课程营销信息
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(); // 课程基本信息和营销信息 CourseBaseInfoDto courseBaseInfoDto = courseBaseInfoService.queryCourseBaseById(courseId); BeanUtils.copyProperties(courseBaseInfoDto, coursePublishPre); // 课程营销信息
CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
13
2023-11-04 07:15:26+00:00
12k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \...
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
10,618
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired
UserDao uDao;
5
2023-11-03 02:29:57+00:00
12k
ballerina-platform/module-ballerina-data-xmldata
native/src/main/java/io/ballerina/stdlib/data/xmldata/xml/XmlTraversal.java
[ { "identifier": "Constants", "path": "native/src/main/java/io/ballerina/stdlib/data/xmldata/utils/Constants.java", "snippet": "public class Constants {\n\n private Constants() {}\n\n public static final String UNDERSCORE = \"_\";\n public static final String COLON = \":\";\n public static fi...
import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.TypeTags; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.flags.SymbolFlags; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.Field; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.RecordType; import io.ballerina.runtime.api.types.Type; import io.ballerina.runtime.api.types.XmlNodeType; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.utils.TypeUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.api.values.BXml; import io.ballerina.runtime.api.values.BXmlItem; import io.ballerina.runtime.api.values.BXmlSequence; import io.ballerina.stdlib.data.xmldata.utils.Constants; import io.ballerina.stdlib.data.xmldata.utils.DataUtils; import io.ballerina.stdlib.data.xmldata.utils.DataUtils.XmlAnalyzerData; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticErrorCode; import io.ballerina.stdlib.data.xmldata.utils.DiagnosticLog; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.xml.namespace.QName;
9,209
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. 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 io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml value to a ballerina record. * * @since 0.1.0 */ public class XmlTraversal { private static final ThreadLocal<XmlTree> tlXmlTree = ThreadLocal.withInitial(XmlTree::new); public static Object traverse(BXml xml, Type type) { XmlTree xmlTree = tlXmlTree.get(); return xmlTree.traverseXml(xml, type); } static class XmlTree { private Object currentNode; @SuppressWarnings("unchecked") public Object traverseXml(BXml xml, Type type) { Type referredType = TypeUtils.getReferredType(type); switch (referredType.getTag()) { case TypeTags.RECORD_TYPE_TAG -> { XmlAnalyzerData analyzerData = new XmlAnalyzerData(); RecordType recordType = (RecordType) referredType; currentNode = ValueCreator.createRecordValue(recordType); BXml nextXml = validateRootElement(xml, recordType, analyzerData); Object resultRecordValue = traverseXml(nextXml, recordType, analyzerData);
/* * Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com). * * WSO2 LLC. 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 io.ballerina.stdlib.data.xmldata.xml; /** * Convert Xml value to a ballerina record. * * @since 0.1.0 */ public class XmlTraversal { private static final ThreadLocal<XmlTree> tlXmlTree = ThreadLocal.withInitial(XmlTree::new); public static Object traverse(BXml xml, Type type) { XmlTree xmlTree = tlXmlTree.get(); return xmlTree.traverseXml(xml, type); } static class XmlTree { private Object currentNode; @SuppressWarnings("unchecked") public Object traverseXml(BXml xml, Type type) { Type referredType = TypeUtils.getReferredType(type); switch (referredType.getTag()) { case TypeTags.RECORD_TYPE_TAG -> { XmlAnalyzerData analyzerData = new XmlAnalyzerData(); RecordType recordType = (RecordType) referredType; currentNode = ValueCreator.createRecordValue(recordType); BXml nextXml = validateRootElement(xml, recordType, analyzerData); Object resultRecordValue = traverseXml(nextXml, recordType, analyzerData);
DataUtils.validateRequiredFields((BMap<BString, Object>) resultRecordValue, analyzerData);
1
2023-11-08 04:13:52+00:00
12k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/SampleTankDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 30;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/d...
import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.TankDrive; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.roadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
10,764
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1;
package org.firstinspires.ftc.teamcode.roadRunner.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1;
private TrajectorySequenceRunner trajectorySequenceRunner;
13
2023-11-06 21:25:54+00:00
12k
celedev97/asa-server-manager
src/main/java/dev/cele/asa_sm/ui/components/ServerTab.java
[ { "identifier": "Const", "path": "src/main/java/dev/cele/asa_sm/Const.java", "snippet": "public final class Const {\n public final static String ASA_STEAM_GAME_NUMBER = \"2430930\";\n\n public final static Path DATA_DIR = Path.of(\"data\");\n public final static Path PROFILES_DIR = DATA_DIR.res...
import com.fasterxml.jackson.databind.ObjectMapper; import com.formdev.flatlaf.FlatClientProperties; import dev.cele.asa_sm.Const; import dev.cele.asa_sm.config.SpringApplicationContext; import dev.cele.asa_sm.dto.AsaServerConfigDto; import dev.cele.asa_sm.services.CommandRunnerService; import dev.cele.asa_sm.services.IniSerializerService; import dev.cele.asa_sm.services.SteamCMDService; import dev.cele.asa_sm.ui.components.forms.SliderWithText; import dev.cele.asa_sm.ui.components.server_tab_accordions.*; import dev.cele.asa_sm.ui.frames.ProcessDialog; import dev.cele.asa_sm.ui.listeners.SimpleDocumentListener; import lombok.Getter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import javax.swing.*; import javax.swing.text.JTextComponent; import java.awt.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.function.Consumer; import static java.util.stream.Collectors.toMap;
9,748
package dev.cele.asa_sm.ui.components; public class ServerTab extends JPanel { //region Autowired stuff from spring private final SteamCMDService steamCMDService = SpringApplicationContext.autoWire(SteamCMDService.class); private final CommandRunnerService commandRunnerService = SpringApplicationContext.autoWire(CommandRunnerService.class); private final ObjectMapper objectMapper = SpringApplicationContext.autoWire(ObjectMapper.class); private final IniSerializerService iniSerializerService = SpringApplicationContext.autoWire(IniSerializerService.class); private Logger log = LoggerFactory.getLogger(ServerTab.class); private final Environment environment = SpringApplicationContext.autoWire(Environment.class); private final boolean isDev = Arrays.asList(environment.getActiveProfiles()).contains("dev"); //endregion //region UI components private final JPanel scrollPaneContent; private final TopPanel topPanel; //endregion private Thread serverThread = null; @Getter private AsaServerConfigDto configDto; public ServerTab(AsaServerConfigDto configDto) { this.configDto = configDto; //region setup UI components //region initial setup, var scrollPaneContent = JPanel() setLayout(new BorderLayout()); GridBagConstraints globalVerticalGBC = new GridBagConstraints(); globalVerticalGBC.fill = GridBagConstraints.HORIZONTAL; globalVerticalGBC.anchor = GridBagConstraints.BASELINE; globalVerticalGBC.gridwidth = GridBagConstraints.REMAINDER; globalVerticalGBC.weightx = 1.0; globalVerticalGBC.insets = new Insets(5, 5, 5, 0); //create a JScrollPane and a content panel scrollPaneContent = new JPanel(); scrollPaneContent.setLayout(new GridBagLayout()); JScrollPane scrollPane = new JScrollPane(scrollPaneContent); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); add(scrollPane, BorderLayout.CENTER); //endregion //top panel topPanel = new TopPanel(configDto); scrollPaneContent.add(topPanel.$$$getRootComponent$$$(), globalVerticalGBC); //create a group named "Administration" var administrationAccordion = new AdministrationAccordion(configDto); scrollPaneContent.add(administrationAccordion.$$$getRootComponent$$$(), globalVerticalGBC); //... other accordion groups ... if(isDev){ var rulesAccordion = new RulesAccordion(configDto); scrollPaneContent.add(rulesAccordion.$$$getRootComponent$$$(), globalVerticalGBC); } var chatAndNotificationsAccordion = new ChatAndNotificationsAccordion(configDto); scrollPaneContent.add(chatAndNotificationsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); var hudAndVisualsAccordion = new HUDAndVisuals(configDto); scrollPaneContent.add(hudAndVisualsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); if(isDev){ var playerSettingsAccordion = new PlayerSettingsAccordion(configDto); scrollPaneContent.add(playerSettingsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); } //create an empty filler panel that will fill the remaining space if there's any JPanel fillerPanel = new JPanel(); fillerPanel.setPreferredSize(new Dimension(0, 0)); scrollPaneContent.add(fillerPanel, gbcClone(globalVerticalGBC, gbc -> gbc.weighty = 1.0)); //endregion if(detectInstalled()){ //if the server is already installed read the ini files and populate the configDto, //the ini files have priority so if you create a profile for an already existing server //the interface will be populated with the values from your existing server readAllIniFiles(); if(configDto.getJustImported()){ //import extra settings from INI Files that are both on INI files and on the configDto configDto.setServerPassword(configDto.getGameUserSettingsINI().getServerSettings().getServerPassword()); configDto.setServerAdminPassword(configDto.getGameUserSettingsINI().getServerSettings().getServerAdminPassword()); configDto.setServerSpectatorPassword(configDto.getGameUserSettingsINI().getServerSettings().getSpectatorPassword()); configDto.setServerName(configDto.getGameUserSettingsINI().getSessionSettings().getSessionName()); configDto.setModIds(configDto.getGameUserSettingsINI().getServerSettings().getActiveMods()); configDto.setRconEnabled(configDto.getGameUserSettingsINI().getServerSettings().getRconEnabled()); configDto.setRconPort(configDto.getGameUserSettingsINI().getServerSettings().getRconPort()); configDto.setRconServerLogBuffer(configDto.getGameUserSettingsINI().getServerSettings().getRconServerGameLogBuffer()); } } configDto.addUnsavedChangeListener((unsaved) -> { //get tabbed pane and set title with a star if unsaved JTabbedPane tabbedPane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, this); if(tabbedPane != null){ int index = tabbedPane.indexOfComponent(this); if(index != -1){ tabbedPane.setTitleAt(index, configDto.getProfileName() + (unsaved ? " *" : "")); } } //set the save button outline to red if unsaved if(unsaved){ topPanel.saveButton.putClientProperty(FlatClientProperties.OUTLINE, FlatClientProperties.OUTLINE_ERROR); } else { topPanel.saveButton.putClientProperty(FlatClientProperties.OUTLINE, null); } }); SwingUtilities.invokeLater(() -> { setupListenersForUnsaved(this); setupAccordionsExpansion(); }); } void setupAccordionsExpansion(){ var accordions = new ArrayList<AccordionTopBar>(); //loop over all the children of the container for (Component component : scrollPaneContent.getComponents()) { //if the component is a container, has a borderlayout, and his top component is a AccordionTopBar if(component instanceof Container && ((Container) component).getLayout() instanceof BorderLayout ){ var topComponent = ((BorderLayout) ((Container) component).getLayout()).getLayoutComponent(BorderLayout.NORTH); if(topComponent instanceof AccordionTopBar){ accordions.add((AccordionTopBar) topComponent); } } } new Thread(() -> { try { Thread.sleep(1500); SwingUtilities.invokeLater(() -> { for (var accordion : accordions) { //TODO: use the text from the accordion to check if it's expanded or not and save it to a json or something? accordion.setExpanded(false); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } }).start(); } void setupListenersForUnsaved(Container container){ //loop over all the children of the container for (Component component : container.getComponents()) { //if the component is a container, call this function recursively
package dev.cele.asa_sm.ui.components; public class ServerTab extends JPanel { //region Autowired stuff from spring private final SteamCMDService steamCMDService = SpringApplicationContext.autoWire(SteamCMDService.class); private final CommandRunnerService commandRunnerService = SpringApplicationContext.autoWire(CommandRunnerService.class); private final ObjectMapper objectMapper = SpringApplicationContext.autoWire(ObjectMapper.class); private final IniSerializerService iniSerializerService = SpringApplicationContext.autoWire(IniSerializerService.class); private Logger log = LoggerFactory.getLogger(ServerTab.class); private final Environment environment = SpringApplicationContext.autoWire(Environment.class); private final boolean isDev = Arrays.asList(environment.getActiveProfiles()).contains("dev"); //endregion //region UI components private final JPanel scrollPaneContent; private final TopPanel topPanel; //endregion private Thread serverThread = null; @Getter private AsaServerConfigDto configDto; public ServerTab(AsaServerConfigDto configDto) { this.configDto = configDto; //region setup UI components //region initial setup, var scrollPaneContent = JPanel() setLayout(new BorderLayout()); GridBagConstraints globalVerticalGBC = new GridBagConstraints(); globalVerticalGBC.fill = GridBagConstraints.HORIZONTAL; globalVerticalGBC.anchor = GridBagConstraints.BASELINE; globalVerticalGBC.gridwidth = GridBagConstraints.REMAINDER; globalVerticalGBC.weightx = 1.0; globalVerticalGBC.insets = new Insets(5, 5, 5, 0); //create a JScrollPane and a content panel scrollPaneContent = new JPanel(); scrollPaneContent.setLayout(new GridBagLayout()); JScrollPane scrollPane = new JScrollPane(scrollPaneContent); scrollPane.getVerticalScrollBar().setUnitIncrement(10); scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); add(scrollPane, BorderLayout.CENTER); //endregion //top panel topPanel = new TopPanel(configDto); scrollPaneContent.add(topPanel.$$$getRootComponent$$$(), globalVerticalGBC); //create a group named "Administration" var administrationAccordion = new AdministrationAccordion(configDto); scrollPaneContent.add(administrationAccordion.$$$getRootComponent$$$(), globalVerticalGBC); //... other accordion groups ... if(isDev){ var rulesAccordion = new RulesAccordion(configDto); scrollPaneContent.add(rulesAccordion.$$$getRootComponent$$$(), globalVerticalGBC); } var chatAndNotificationsAccordion = new ChatAndNotificationsAccordion(configDto); scrollPaneContent.add(chatAndNotificationsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); var hudAndVisualsAccordion = new HUDAndVisuals(configDto); scrollPaneContent.add(hudAndVisualsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); if(isDev){ var playerSettingsAccordion = new PlayerSettingsAccordion(configDto); scrollPaneContent.add(playerSettingsAccordion.$$$getRootComponent$$$(), globalVerticalGBC); } //create an empty filler panel that will fill the remaining space if there's any JPanel fillerPanel = new JPanel(); fillerPanel.setPreferredSize(new Dimension(0, 0)); scrollPaneContent.add(fillerPanel, gbcClone(globalVerticalGBC, gbc -> gbc.weighty = 1.0)); //endregion if(detectInstalled()){ //if the server is already installed read the ini files and populate the configDto, //the ini files have priority so if you create a profile for an already existing server //the interface will be populated with the values from your existing server readAllIniFiles(); if(configDto.getJustImported()){ //import extra settings from INI Files that are both on INI files and on the configDto configDto.setServerPassword(configDto.getGameUserSettingsINI().getServerSettings().getServerPassword()); configDto.setServerAdminPassword(configDto.getGameUserSettingsINI().getServerSettings().getServerAdminPassword()); configDto.setServerSpectatorPassword(configDto.getGameUserSettingsINI().getServerSettings().getSpectatorPassword()); configDto.setServerName(configDto.getGameUserSettingsINI().getSessionSettings().getSessionName()); configDto.setModIds(configDto.getGameUserSettingsINI().getServerSettings().getActiveMods()); configDto.setRconEnabled(configDto.getGameUserSettingsINI().getServerSettings().getRconEnabled()); configDto.setRconPort(configDto.getGameUserSettingsINI().getServerSettings().getRconPort()); configDto.setRconServerLogBuffer(configDto.getGameUserSettingsINI().getServerSettings().getRconServerGameLogBuffer()); } } configDto.addUnsavedChangeListener((unsaved) -> { //get tabbed pane and set title with a star if unsaved JTabbedPane tabbedPane = (JTabbedPane) SwingUtilities.getAncestorOfClass(JTabbedPane.class, this); if(tabbedPane != null){ int index = tabbedPane.indexOfComponent(this); if(index != -1){ tabbedPane.setTitleAt(index, configDto.getProfileName() + (unsaved ? " *" : "")); } } //set the save button outline to red if unsaved if(unsaved){ topPanel.saveButton.putClientProperty(FlatClientProperties.OUTLINE, FlatClientProperties.OUTLINE_ERROR); } else { topPanel.saveButton.putClientProperty(FlatClientProperties.OUTLINE, null); } }); SwingUtilities.invokeLater(() -> { setupListenersForUnsaved(this); setupAccordionsExpansion(); }); } void setupAccordionsExpansion(){ var accordions = new ArrayList<AccordionTopBar>(); //loop over all the children of the container for (Component component : scrollPaneContent.getComponents()) { //if the component is a container, has a borderlayout, and his top component is a AccordionTopBar if(component instanceof Container && ((Container) component).getLayout() instanceof BorderLayout ){ var topComponent = ((BorderLayout) ((Container) component).getLayout()).getLayoutComponent(BorderLayout.NORTH); if(topComponent instanceof AccordionTopBar){ accordions.add((AccordionTopBar) topComponent); } } } new Thread(() -> { try { Thread.sleep(1500); SwingUtilities.invokeLater(() -> { for (var accordion : accordions) { //TODO: use the text from the accordion to check if it's expanded or not and save it to a json or something? accordion.setExpanded(false); } }); } catch (InterruptedException e) { throw new RuntimeException(e); } }).start(); } void setupListenersForUnsaved(Container container){ //loop over all the children of the container for (Component component : container.getComponents()) { //if the component is a container, call this function recursively
if(component instanceof SliderWithText){
6
2023-11-07 19:36:49+00:00
12k
1341191074/aibote4j
sdk-core/src/main/java/net/aibote/sdk/WinBot.java
[ { "identifier": "OCRResult", "path": "sdk-core/src/main/java/net/aibote/sdk/dto/OCRResult.java", "snippet": "public class OCRResult {\n public Point lt;\n public Point rt;\n public Point ld;\n public Point rd;\n public String word;\n public double rate;\n}" }, { "identifier": "...
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; import lombok.Data; import lombok.EqualsAndHashCode; import net.aibote.sdk.dto.OCRResult; import net.aibote.sdk.dto.Point; import net.aibote.sdk.options.Mode; import net.aibote.sdk.options.Region; import net.aibote.sdk.options.SubColor; import net.aibote.utils.HttpClientUtils; import net.aibote.utils.ImageBase64Converter; import org.apache.commons.lang3.StringUtils; import java.util.*;
7,567
* @return String 成功返回 x|y 失败返回null */ public String findColor(String hwnd, String strMainColor, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.strDelayCmd("findColor", hwnd, strMainColor, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 比较指定坐标点的颜色值 * * @param hwnd 窗口句柄 * @param mainX 主颜色所在的X坐标 * @param mainY 主颜色所在的Y坐标 * @param mainColorStr 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 截图区域 默认全屏 * @param sim 相似度,0-1 的浮点数 * @param mode 操作模式,后台 true,前台 false, * @return boolean */ public boolean compareColor(String hwnd, int mainX, int mainY, String mainColorStr, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.boolDelayCmd("compareColor", hwnd, Integer.toString(mainX), Integer.toString(mainY), mainColorStr, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 提取视频帧 * * @param videoPath 视频路径 * @param saveFolder 提取的图片保存的文件夹目录 * @param jumpFrame 跳帧,默认为1 不跳帧 * @return boolean 成功返回true,失败返回false */ public boolean extractImageByVideo(String videoPath, String saveFolder, int jumpFrame) { return this.boolCmd("extractImageByVideo", videoPath, saveFolder, Integer.toString(jumpFrame)); } /** * 裁剪图片 * * @param imagePath 图片路径 * @param saveFolder 裁剪后保存的图片路径 * @param region 区域 * @return boolean 成功返回true,失败返回false */ public boolean cropImage(String imagePath, String saveFolder, Region region) { return this.boolCmd("cropImage", imagePath, saveFolder, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom)); } /** * 初始化ocr服务 * * @param ocrServerIp ocr服务器IP * @param ocrServerPort ocr服务器端口,固定端口9527。 注意,如果传入的值<=0 ,则都会当默认端口处理。 * @param useAngleModel 支持图像旋转。 默认false。仅内置ocr有效。内置OCR需要安装 * @param enableGPU 启动GPU 模式。默认false 。GPU模式需要电脑安装NVIDIA驱动,并且到群文件下载对应cuda版本 * @param enableTensorrt 启动加速,仅 enableGPU = true 时有效,默认false 。图片太大可能会导致GPU内存不足 * @return boolean 总是返回true */ public boolean initOcr(String ocrServerIp, int ocrServerPort, boolean useAngleModel, boolean enableGPU, boolean enableTensorrt) { //if (ocrServerPort <= 0) { ocrServerPort = 9527; //} return this.boolCmd("initOcr", ocrServerIp, Integer.toString(ocrServerPort), Boolean.toString(useAngleModel), Boolean.toString(enableGPU), Boolean.toString(enableTensorrt)); } /** * ocr识别 * * @param hwnd 窗口句柄 * @param region 区域 * @param thresholdType 二值化算法类型 * @param thresh 阈值 * @param maxval 最大值 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return String jsonstr */ public List<OCRResult> ocrByHwnd(String hwnd, Region region, int thresholdType, int thresh, int maxval, Mode mode) { if (null == region) { region = new Region(); } if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } String strRet = this.strCmd("ocrByHwnd", hwnd, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), mode.boolValueStr()); if (null == strRet || strRet == "" || strRet == "null" || strRet == "[]") { return null; } else { List<OCRResult> list = new ArrayList<>(); JSONArray jsonArray = JSONArray.parseArray(strRet); jsonArray.forEach((ary) -> { if (ary instanceof JSONArray) { JSONArray a = (JSONArray) ary; OCRResult ocrResult = new OCRResult();
package net.aibote.sdk; @EqualsAndHashCode(callSuper = true) @Data public abstract class WinBot extends Aibote { /** * 查找窗口句柄 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindow(String className, String windowName) { return strCmd("findWindow", className, windowName); } /** * 查找窗口句柄数组, 以 “|” 分割 * * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findWindows(String className, String windowName) { return strCmd("findWindows", className, windowName); } /** * 查找窗口句柄 * * @param curHwnd 当前窗口句柄 * @param className 窗口类名 * @param windowName 窗口名 * @return String 成功返回窗口句柄,失败返回null */ public String findSubWindow(String curHwnd, String className, String windowName) { return strCmd("findSubWindow", curHwnd, className, windowName); } /** * 查找父窗口句柄 * * @param curHwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String findParentWindow(String curHwnd) { return strCmd("findParentWindow", curHwnd); } /** * 查找桌面窗口句柄 * * @return 成功返回窗口句柄,失败返回null */ public String findDesktopWindow() { return strCmd("findDesktopWindow"); } /** * 获取窗口名称 * * @param hwnd 当前窗口句柄 * @return String 成功返回窗口句柄,失败返回null */ public String getWindowName(String hwnd) { return strCmd("getWindowName", hwnd); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isShow 是否显示 * @return boolean 成功返回true,失败返回false */ public boolean showWindow(String hwnd, boolean isShow) { return boolCmd("showWindow", hwnd, String.valueOf(isShow)); } /** * 显示/隐藏窗口 * * @param hwnd 当前窗口句柄 * @param isTop 是否置顶 * @return boolean 成功返回true,失败返回false */ public boolean setWindowTop(String hwnd, boolean isTop) { return boolCmd("setWindowTop", hwnd, String.valueOf(isTop)); } /** * 获取窗口位置。 用“|”分割 * * @param hwnd 当前窗口句柄 * @return 0|0|0|0 */ public String getWindowPos(String hwnd) { return strCmd("getWindowPos", hwnd); } /** * 设置窗口位置 * * @param hwnd 当前窗口句柄 * @param left 左上角横坐标 * @param top 左上角纵坐标 * @param width width 窗口宽度 * @param height height 窗口高度 * @return boolean 成功返回true 失败返回 false */ public boolean setWindowPos(String hwnd, int left, int top, int width, int height) { return boolCmd("setWindowPos", hwnd, Integer.toString(left), Integer.toString(top), Integer.toString(width), Integer.toString(height)); } /** * 移动鼠标 <br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true */ public boolean moveMouse(String hwnd, int x, int y, Mode mode, String elementHwnd) { return boolCmd("moveMouse", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr(), elementHwnd); } /** * 移动鼠标(相对坐标) * * @param hwnd 窗口句柄 * @param x 相对横坐标 * @param y 相对纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean moveMouseRelative(String hwnd, int x, int y, Mode mode) { return boolCmd("moveMouseRelative", hwnd, Integer.toString(x), Integer.toString(y), mode.boolValueStr()); } /** * 滚动鼠标 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param dwData 鼠标滚动次数,负数下滚鼠标,正数上滚鼠标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return boolean 总是返回true */ public boolean rollMouse(String hwnd, int x, int y, int dwData, Mode mode) { return boolCmd("rollMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(dwData), mode.boolValueStr()); } /** * 鼠标点击<br /> * 如果mode值为true且目标控件有单独的句柄,则需要通过getElementWindow获得元素句柄,指定elementHwnd的值(极少应用窗口由父窗口响应消息,则无需指定) * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mouseType 单击左键:1 单击右键:2 按下左键:3 弹起左键:4 按下右键:5 弹起右键:6 双击左键:7 双击右键:8 * @param mode 操作模式,后台 true,前台 false。默认前台操作。 * @param elementHwnd 元素句柄 * @return boolean 总是返回true。 */ public boolean clickMouse(String hwnd, int x, int y, int mouseType, Mode mode, String elementHwnd) { return boolCmd("clickMouse", hwnd, Integer.toString(x), Integer.toString(y), Integer.toString(mouseType), mode.boolValueStr(), elementHwnd); } /** * 输入文本 * * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeys(String txt) { return boolCmd("sendKeys", txt); } /** * 后台输入文本 * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param txt 输入的文本 * @return boolean 总是返回true */ public boolean sendKeysByHwnd(String hwnd, String txt) { return boolCmd("sendKeysByHwnd", hwnd, txt); } /** * 输入虚拟键值(VK) * * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVk(int vk, int keyState) { return boolCmd("sendVk", Integer.toString(vk), Integer.toString(keyState)); } /** * 后台输入虚拟键值(VK) * * @param hwnd 窗口句柄,如果目标控件有单独的句柄,需要通过getElementWindow获得句柄 * @param vk VK键值,例如:回车对应 VK键值 13 * @param keyState 按下弹起:1 按下:2 弹起:3 * @return boolean 总是返回true */ public boolean sendVkByHwnd(String hwnd, int vk, int keyState) { return boolCmd("sendVkByHwnd", hwnd, Integer.toString(vk), Integer.toString(keyState)); } /** * 截图保存。threshold默认保存原图。 * * @param hwnd 窗口句柄 * @param savePath 保存的位置 * @param region 区域 * @param thresholdType hresholdType算法类型。<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。 thresh和maxval同为255时灰度处理 * @param maxval 最大值。 thresh和maxval同为255时灰度处理 * @return boolean */ public boolean saveScreenshot(String hwnd, String savePath, Region region, int thresholdType, int thresh, int maxval) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } return boolCmd("saveScreenshot", hwnd, savePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval)); } /** * 获取指定坐标点的色值 * * @param hwnd 窗口句柄 * @param x 横坐标 * @param y 纵坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回#开头的颜色值,失败返回null */ public String getColor(String hwnd, int x, int y, boolean mode) { return strCmd("getColor", hwnd, Integer.toString(x), Integer.toString(y), Boolean.toString(mode)); } /** * @param hwndOrBigImagePath 窗口句柄或者图片路径 * @param smallImagePath 小图片路径,多张小图查找应当用"|"分开小图路径 * @param region 区域 * @param sim 图片相似度 0.0-1.0,sim默认0.95 * @param thresholdType thresholdType算法类型:<br /> * 0 THRESH_BINARY算法,当前点值大于阈值thresh时,取最大值maxva,否则设置为0 * 1 THRESH_BINARY_INV算法,当前点值大于阈值thresh时,设置为0,否则设置为最大值maxva * 2 THRESH_TOZERO算法,当前点值大于阈值thresh时,不改变,否则设置为0 * 3 THRESH_TOZERO_INV算法,当前点值大于阈值thresh时,设置为0,否则不改变 * 4 THRESH_TRUNC算法,当前点值大于阈值thresh时,设置为阈值thresh,否则不改变 * 5 ADAPTIVE_THRESH_MEAN_C算法,自适应阈值 * 6 ADAPTIVE_THRESH_GAUSSIAN_C算法,自适应阈值 * @param thresh 阈值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param maxval 最大值。threshold默认保存原图。thresh和maxval同为255时灰度处理 * @param multi 找图数量,默认为1 找单个图片坐标 * @param mode 操作模式,后台 true,前台 false。默认前台操作。hwndOrBigImagePath为图片文件,此参数无效 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findImages(String hwndOrBigImagePath, String smallImagePath, Region region, float sim, int thresholdType, int thresh, int maxval, int multi, Mode mode) { if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } String strData = null; if (hwndOrBigImagePath.toString().indexOf(".") == -1) {//在窗口上找图 return strDelayCmd("findImage", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } else {//在文件上找图 return this.strDelayCmd("findImageByFile", hwndOrBigImagePath, smallImagePath, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), Integer.toString(multi), mode.boolValueStr()); } } /** * 找动态图 * * @param hwnd 窗口句柄 * @param frameRate 前后两张图相隔的时间,单位毫秒 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return 成功返回 单坐标点[{x:number, y:number}],多坐标点[{x1:number, y1:number}, {x2:number, y2:number}...] 失败返回null */ public String findAnimation(String hwnd, int frameRate, Region region, Mode mode) { return strDelayCmd("findAnimation", hwnd, Integer.toString(frameRate), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), mode.boolValueStr()); } /** * 查找指定色值的坐标点 * * @param hwnd 窗口句柄 * @param strMainColor 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 在指定区域内找色,默认全屏; * @param sim 相似度。0.0-1.0,sim默认为1 * @param mode 后台 true,前台 false。默认前台操作。 * @return String 成功返回 x|y 失败返回null */ public String findColor(String hwnd, String strMainColor, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.strDelayCmd("findColor", hwnd, strMainColor, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 比较指定坐标点的颜色值 * * @param hwnd 窗口句柄 * @param mainX 主颜色所在的X坐标 * @param mainY 主颜色所在的Y坐标 * @param mainColorStr 颜色字符串,必须以 # 开头,例如:#008577; * @param subColors 辅助定位的其他颜色; * @param region 截图区域 默认全屏 * @param sim 相似度,0-1 的浮点数 * @param mode 操作模式,后台 true,前台 false, * @return boolean */ public boolean compareColor(String hwnd, int mainX, int mainY, String mainColorStr, SubColor[] subColors, Region region, float sim, Mode mode) { StringBuilder subColorsStr = new StringBuilder(); if (null != subColors) { SubColor subColor; for (int i = 0; i < subColors.length; i++) { subColor = subColors[i]; subColorsStr.append(subColor.offsetX).append("/"); subColorsStr.append(subColor.offsetY).append("/"); subColorsStr.append(subColor.colorStr); if (i < subColors.length - 1) { //最后不需要\n subColorsStr.append("\n"); } } } return this.boolDelayCmd("compareColor", hwnd, Integer.toString(mainX), Integer.toString(mainY), mainColorStr, subColorsStr.toString(), Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Float.toString(sim), mode.boolValueStr()); } /** * 提取视频帧 * * @param videoPath 视频路径 * @param saveFolder 提取的图片保存的文件夹目录 * @param jumpFrame 跳帧,默认为1 不跳帧 * @return boolean 成功返回true,失败返回false */ public boolean extractImageByVideo(String videoPath, String saveFolder, int jumpFrame) { return this.boolCmd("extractImageByVideo", videoPath, saveFolder, Integer.toString(jumpFrame)); } /** * 裁剪图片 * * @param imagePath 图片路径 * @param saveFolder 裁剪后保存的图片路径 * @param region 区域 * @return boolean 成功返回true,失败返回false */ public boolean cropImage(String imagePath, String saveFolder, Region region) { return this.boolCmd("cropImage", imagePath, saveFolder, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom)); } /** * 初始化ocr服务 * * @param ocrServerIp ocr服务器IP * @param ocrServerPort ocr服务器端口,固定端口9527。 注意,如果传入的值<=0 ,则都会当默认端口处理。 * @param useAngleModel 支持图像旋转。 默认false。仅内置ocr有效。内置OCR需要安装 * @param enableGPU 启动GPU 模式。默认false 。GPU模式需要电脑安装NVIDIA驱动,并且到群文件下载对应cuda版本 * @param enableTensorrt 启动加速,仅 enableGPU = true 时有效,默认false 。图片太大可能会导致GPU内存不足 * @return boolean 总是返回true */ public boolean initOcr(String ocrServerIp, int ocrServerPort, boolean useAngleModel, boolean enableGPU, boolean enableTensorrt) { //if (ocrServerPort <= 0) { ocrServerPort = 9527; //} return this.boolCmd("initOcr", ocrServerIp, Integer.toString(ocrServerPort), Boolean.toString(useAngleModel), Boolean.toString(enableGPU), Boolean.toString(enableTensorrt)); } /** * ocr识别 * * @param hwnd 窗口句柄 * @param region 区域 * @param thresholdType 二值化算法类型 * @param thresh 阈值 * @param maxval 最大值 * @param mode 操作模式,后台 true,前台 false。默认前台操作 * @return String jsonstr */ public List<OCRResult> ocrByHwnd(String hwnd, Region region, int thresholdType, int thresh, int maxval, Mode mode) { if (null == region) { region = new Region(); } if (thresholdType == 5 || thresholdType == 6) { thresh = 127; maxval = 255; } String strRet = this.strCmd("ocrByHwnd", hwnd, Integer.toString(region.left), Integer.toString(region.top), Integer.toString(region.right), Integer.toString(region.bottom), Integer.toString(thresholdType), Integer.toString(thresh), Integer.toString(maxval), mode.boolValueStr()); if (null == strRet || strRet == "" || strRet == "null" || strRet == "[]") { return null; } else { List<OCRResult> list = new ArrayList<>(); JSONArray jsonArray = JSONArray.parseArray(strRet); jsonArray.forEach((ary) -> { if (ary instanceof JSONArray) { JSONArray a = (JSONArray) ary; OCRResult ocrResult = new OCRResult();
ocrResult.lt = new Point(a.getJSONArray(0).getJSONArray(0).getIntValue(0), a.getJSONArray(0).getJSONArray(0).getIntValue(1));
1
2023-11-08 14:31:58+00:00
12k
SeanPesce/AWS-IoT-Recon
src/main/java/com/seanpesce/aws/iot/AwsIotRecon.java
[ { "identifier": "AwsIotConstants", "path": "src/main/java/com/seanpesce/aws/iot/AwsIotConstants.java", "snippet": "public class AwsIotConstants {\n\n public static final String PROJECT_TITLE = \"[AWS IoT Core Enumeration Tool by Sean Pesce]\";\n\n public static final String ACTION_MQTT_DUMP = \"mq...
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.security.cert.CertificateException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.ArrayList; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Consumer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import com.seanpesce.aws.iot.AwsIotConstants; import com.seanpesce.http.MtlsHttpClient; import com.seanpesce.mqtt.MqttScript; import com.seanpesce.regex.PatternWithNamedGroups; import com.seanpesce.Util; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import software.amazon.awssdk.crt.auth.credentials.Credentials; import software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider; import software.amazon.awssdk.crt.CRT; import software.amazon.awssdk.crt.io.ClientTlsContext; import software.amazon.awssdk.crt.io.TlsContextOptions; import software.amazon.awssdk.crt.mqtt.MqttClientConnection; import software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents; import software.amazon.awssdk.crt.mqtt.MqttMessage; import software.amazon.awssdk.crt.mqtt.QualityOfService; import software.amazon.awssdk.crt.mqtt5.Mqtt5Client; import software.amazon.awssdk.iot.AwsIotMqttConnectionBuilder;
9,859
X509CredentialsProvider credsProvider = x509CredsBuilder.build(); CompletableFuture<Credentials> credsFuture = credsProvider.getCredentials(); try { credentials = credsFuture.get(); String credsStr = "{\"credentials\":{\"accessKeyId\":\"" + new String(credentials.getAccessKeyId(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"secretAccessKey\":\"" + new String(credentials.getSecretAccessKey(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"sessionToken\":\"" + new String(credentials.getSessionToken(), StandardCharsets.UTF_8) + "\"}}"; System.out.println(credsStr); discoveredCreds.add(credentials); } catch (ExecutionException | InterruptedException ex) { System.err.println("[ERROR] Failed to obtain credentials from X509 (role=\"" + roleAlias + "\"; thingName=\"" + thingName + "\"): " + ex.getMessage()); } credsProvider.close(); } return discoveredCreds; } public static void getDeviceShadow(String thingName, String shadowName) { // https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-rest-api.html#API_GetThingShadow // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP request (mTLS required): // // GET /things/<thingName>/shadow?name=<shadowName> HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 // // Note: Shadow name is optional (null name = classic device shadow) String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/things/" + thingName + "/shadow" + (shadowName == null ? "" : "?name="+shadowName); String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); System.out.println(data); } public static void getNamedShadows(String thingName) { // @TODO // https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-rest-api.html#API_ListNamedShadowsForThing // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP request (mTLS required): // // GET /api/things/shadow/ListNamedShadowsForThing/<thingName>?maxResults=200&nextToken= HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/api/things/shadow/ListNamedShadowsForThing/" + thingName + "?maxResults=200"; //+"&nextToken="; String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // @TODO: Iterate through all pages of named shadows System.out.println(data); } public static void getRetainedMqttMessages() { // @TODO // https://docs.aws.amazon.com/iot/latest/apireference/API_iotdata_ListRetainedMessages.html // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP requests (mTLS required): // // GET /retainedMessage?maxResults=200&nextToken= HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 // // GET /retainedMessage/<topic> HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/retainedMessage?maxResults=200"; //+"&nextToken="; String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // @TODO: Iterate through all pages of retained messages // @TODO: Get message bodies for all retained message topics System.out.println(data); } // https://docs.aws.amazon.com/iot/latest/developerguide/jobs-mqtt-api.html public static void getPendingJobs() throws InterruptedException, ExecutionException { final String thingName = cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId; final String topic = "$aws/things/" + thingName + "/jobs/get"; final String topicAccepted = topic + "/accepted"; final String topicRejected = topic + "/rejected"; final String message = "{}"; CompletableFuture<Integer> subAccept = clientConnection.subscribe(topicAccepted, QualityOfService.AT_LEAST_ONCE, genericMqttMsgConsumer); subAccept.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topicAccepted + ": " + throwable.toString()); return -1; }); subAccept.get(); CompletableFuture<Integer> subReject = clientConnection.subscribe(topicRejected, QualityOfService.AT_LEAST_ONCE, genericMqttMsgConsumer); subReject.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topicRejected + ": " + throwable.toString()); return -1; }); subReject.get(); MqttMessage msg = new MqttMessage(topic, message.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_LEAST_ONCE); CompletableFuture<Integer> publication = clientConnection.publish(msg); publication.get(); // Sleep 3 seconds to see if we receive our payload try { Thread.sleep(3000); } catch (InterruptedException ex) { System.err.println("[WARNING] Get pending jobs sleep operation was interrupted: " + ex.getMessage()); } // Unsubscribe from the accept/reject topic(s) CompletableFuture<Integer> unsubAccept = clientConnection.unsubscribe(topicAccepted); unsubAccept.get(); CompletableFuture<Integer> unsubReject = clientConnection.unsubscribe(topicRejected); unsubReject.get(); } public static void runMqttScript(String scriptFilePath) throws IOException, InterruptedException, ExecutionException { final String tag = "[MQTT Script] "; final int maxLogMsgSize = 80; System.err.println(tag + "Executing script: " + scriptFilePath);
// Author: Sean Pesce // // References: // https://aws.github.io/aws-iot-device-sdk-java-v2/ // https://docs.aws.amazon.com/iot/latest/developerguide // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/ // https://explore.skillbuilder.aws/learn/course/external/view/elearning/5667/deep-dive-into-aws-iot-authentication-and-authorization // // @TODO: // - Re-architect this tool to be more object-oriented (e.g., fewer static/global variables) // - Use CountDownLatch(count) in subscription message handlers for improved reliability package com.seanpesce.aws.iot; // import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient; public class AwsIotRecon { // MQTT topics to subscribe to (if empty, defaults to "#" - all topics) public static ArrayList<String> topicSubcriptions = new ArrayList<String>(); // Regular expressions with named capture groups for harvesting fields from MQTT topics public static ArrayList<PatternWithNamedGroups> topicsRegex = new ArrayList<PatternWithNamedGroups>(Arrays.asList(AwsIotConstants.RESERVED_TOPICS_REGEX)); public static String jarName = AwsIotRecon.class.getSimpleName() + ".jar"; // Run-time resources public static CommandLine cmd = null; public static String clientId = null; public static MqttClientConnection clientConnection = null; public static Mqtt5Client mqtt5ClientConnection = null; public static ClientTlsContext tlsContext = null; // For assuming IAM roles public static final MqttClientConnectionEvents connectionCallbacks = new MqttClientConnectionEvents() { @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionInterrupted(int errorCode) { System.err.println("[WARNING] Connection interrupted: (" + errorCode + ") " + CRT.awsErrorName(errorCode) + ": " + CRT.awsErrorString(errorCode)); } @Override // software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents public void onConnectionResumed(boolean sessionPresent) { System.err.println("[INFO] Connection resumed (" + (sessionPresent ? "existing" : "new") + " session)"); } }; public static final Consumer<MqttMessage> genericMqttMsgConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { String msg = "\n[MQTT Message] " + message.getTopic() + "\t" + new String(message.getPayload(), StandardCharsets.UTF_8); System.out.println(msg); } }; public static final Consumer<MqttMessage> topicFieldHarvester = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { Map<String, String> m = extractFieldsFromTopic(message.getTopic()); if (m != null) { String msg = "[MQTT Topic Field Harvester] " + message.getTopic() + "\t" + m; System.out.println(msg); } } }; public static void main(String[] args) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, org.apache.commons.cli.ParseException, InterruptedException, ExecutionException { cmd = parseCommandLineArguments(args); buildConnection(cmd); String action = cmd.getOptionValue("a"); if (action.equals(AwsIotConstants.ACTION_MQTT_DUMP)) { mqttConnect(); beginMqttDump(); } else if (action.equals(AwsIotConstants.ACTION_MQTT_TOPIC_FIELD_HARVEST)) { mqttConnect(); beginMqttTopicFieldHarvesting(); } else if (action.equals(AwsIotConstants.ACTION_IAM_CREDS)) { getIamCredentialsFromDeviceX509(cmd.hasOption("R") ? Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("R")).split("\n") : new String[] {"admin"}, cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId); } else if (action.equals(AwsIotConstants.ACTION_MQTT_SCRIPT)) { mqttConnect(); runMqttScript(cmd.getOptionValue("f")); } else if (action.equals(AwsIotConstants.ACTION_MQTT_DATA_EXFIL)) { mqttConnect(); testDataExfilChannel(); } else if (action.equals(AwsIotConstants.ACTION_GET_JOBS)) { mqttConnect(); getPendingJobs(); } else if (action.equals(AwsIotConstants.ACTION_GET_SHADOW)) { getDeviceShadow(cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId, cmd.hasOption("s") ? cmd.getOptionValue("s") : null); } else if (action.equals(AwsIotConstants.ACTION_LIST_NAMED_SHADOWS)) { getNamedShadows(cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId); } else if (action.equals(AwsIotConstants.ACTION_LIST_RETAINED_MQTT_MESSAGES)) { getRetainedMqttMessages(); } // System.exit(0); } public static CommandLine parseCommandLineArguments(String[] args) throws IOException { // Get JAR name for help output try { jarName = AwsIotRecon.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); jarName = jarName.substring(jarName.lastIndexOf(FileSystems.getDefault().getSeparator()) + 1); } catch (URISyntaxException ex) { // Do nothing } // Parse command-line arguments Options opts = new Options(); Option optHelp = new Option("h", "help", false, "Print usage and exit"); opts.addOption(optHelp); Option optAwsHost = Option.builder("H").longOpt("host").argName("host").hasArg(true).required(true).desc("(Required) AWS IoT instance hostname").type(String.class).build(); opts.addOption(optAwsHost); Option optOperation = Option.builder("a").longOpt("action").argName("action").hasArg(true).required(true).desc("(Required) The enumeration task to carry out. Options: " + AwsIotConstants.CLI_ACTIONS).type(String.class).build(); opts.addOption(optOperation); Option optMqttUser = Option.builder("u").longOpt("user").argName("username").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Username for connection").type(String.class).build(); opts.addOption(optMqttUser); Option optMqttPw = Option.builder("p").longOpt("pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Password for connection").type(String.class).build(); opts.addOption(optMqttPw); Option optMtlsCert = Option.builder("c").longOpt("mtls-cert").argName("cert").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Client mTLS certificate (file path or string data)").type(String.class).build(); opts.addOption(optMtlsCert); Option optMtlsPrivKey = Option.builder("k").longOpt("mtls-priv-key").argName("key").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Client mTLS private key (file path or string data)").type(String.class).build(); opts.addOption(optMtlsPrivKey); Option optMtlsKeystore = Option.builder("K").longOpt("mtls-keystore").argName("keystore").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Path to keystore file (PKCS12/P12 or Java Keystore/JKS) containing client mTLS key pair. If keystore alias and/or certificate password is specified, the keystore is assumed to be a JKS file. Otherwise, the keystore is assumed to be P12").type(String.class).build(); opts.addOption(optMtlsKeystore); Option optMtlsKeystorePw = Option.builder("q").longOpt("keystore-pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Password for mTLS keystore (JKS or P12). Required if a keystore is specified").type(String.class).build(); opts.addOption(optMtlsKeystorePw); Option optMtlsKeystoreAlias = Option.builder("N").longOpt("keystore-alias").argName("alias").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Alias for mTLS keystore (JKS)").type(String.class).build(); opts.addOption(optMtlsKeystoreAlias); Option optMtlsKeystoreCertPw = Option.builder("Q").longOpt("keystore-cert-pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Certificate password for mTLS keystore (JKS)").type(String.class).build(); opts.addOption(optMtlsKeystoreCertPw); Option optMtlsWindowsCertPath = Option.builder(null).longOpt("windows-cert-store").argName("path").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Path to mTLS certificate in a Windows certificate store").type(String.class).build(); opts.addOption(optMtlsWindowsCertPath); Option optCertificateAuthority = Option.builder("A").longOpt("cert-authority").argName("cert").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Certificate authority (CA) to use for verifying the server TLS certificate (file path or string data)").type(String.class).build(); opts.addOption(optCertificateAuthority); Option optUseMqtt5 = new Option("5", "mqtt5", false, "Use MQTT 5"); opts.addOption(optUseMqtt5); Option optClientId = Option.builder("C").longOpt("client-id").argName("ID").hasArg(true).required(false).desc("Client ID to use for connections. If no client ID is provided, a unique ID will be generated every time this program runs.").type(String.class).build(); opts.addOption(optClientId); Option optPortNum = Option.builder("P").longOpt("port").argName("port").hasArg(true).required(false).desc("AWS server port number (1-65535)").type(Number.class).build(); opts.addOption(optPortNum); Option optTopicRegex = Option.builder("X").longOpt("topic-regex").argName("regex").hasArg(true).required(false).desc("Regular expression(s) with named capture groups for harvesting metadata from MQTT topics. This argument can be a file path or regex string data. To provide multiple regexes, separate each expression with a newline character. For more information on Java regular expressions with named capture groups, see here: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#special").type(String.class).build(); opts.addOption(optTopicRegex); Option optNoVerifyTls = new Option("U", "unsafe-tls", false, "Disable TLS certificate validation when possible"); // @TODO: Disable TLS validation for MQTT too? opts.addOption(optNoVerifyTls); Option optRoleAlias = Option.builder("R").longOpt("role-alias").argName("role").hasArg(true).required(false).desc("IAM role alias to obtain credentials for. Accepts a single alias string, or a path to a file containing a list of aliases.").type(String.class).build(); opts.addOption(optRoleAlias); Option optSubToTopics = Option.builder("T").longOpt("topics").argName("topics").hasArg(true).required(false).desc("MQTT topics to subscribe to (file path or string data). To provide multiple topics, separate each topic with a newline character").type(String.class).build(); opts.addOption(optSubToTopics); Option optThingName = Option.builder("t").longOpt("thing-name").argName("name").hasArg(true).required(false).desc("Unique \"thingName\" (device ID). If this argument is not provided, client ID will be used").type(String.class).build(); opts.addOption(optThingName); Option optShadowName = Option.builder("s").longOpt("shadow-name").argName("name").hasArg(true).required(false).desc("Shadow name (required for fetching named shadows with " + AwsIotConstants.ACTION_GET_SHADOW + ")").type(String.class).build(); opts.addOption(optShadowName); Option optCustomAuthUser = Option.builder(null).longOpt("custom-auth-user").argName("user").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer username").type(String.class).build(); opts.addOption(optCustomAuthUser); Option optCustomAuthName = Option.builder(null).longOpt("custom-auth-name").argName("name").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer name").type(String.class).build(); opts.addOption(optCustomAuthName); Option optCustomAuthSig = Option.builder(null).longOpt("custom-auth-sig").argName("signature").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer signature").type(String.class).build(); opts.addOption(optCustomAuthSig); Option optCustomAuthPass = Option.builder(null).longOpt("custom-auth-pass").argName("password").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer password").type(String.class).build(); opts.addOption(optCustomAuthPass); Option optCustomAuthTokKey = Option.builder(null).longOpt("custom-auth-tok-name").argName("name").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer token key name").type(String.class).build(); opts.addOption(optCustomAuthTokKey); Option optCustomAuthTokVal = Option.builder(null).longOpt("custom-auth-tok-val").argName("value").hasArg(true).required(false).desc(AwsIotConstants.CLI_AUTH_ARG + "Custom authorizer token value").type(String.class).build(); opts.addOption(optCustomAuthTokVal); Option optMqttScript = Option.builder("f").longOpt("script").argName("file").hasArg(true).required(false).desc("MQTT script file (required for " + AwsIotConstants.ACTION_MQTT_SCRIPT + " action)").type(String.class).build(); opts.addOption(optMqttScript); // Option optAwsRegion = Option.builder("r").longOpt("region").argName("region").hasArg(true).required(false).desc("AWS instance region (e.g., \"us-west-2\")").type(String.class).build(); // opts.addOption(optAwsRegion); // @TODO: Add support for these: // Connection options: // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withCustomAuthorizer(java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang.String) // See also: https://github.com/aws/aws-iot-device-sdk-java-v2/blob/main/samples/CustomAuthorizerConnect/src/main/java/customauthorizerconnect/CustomAuthorizerConnect.java#L70 // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withHttpProxyOptions(software.amazon.awssdk.crt.http.HttpProxyOptions) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqtt5ClientBuilder.html // // Timeout options: // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withKeepAliveSecs(int) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withPingTimeoutMs(int) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withProtocolOperationTimeoutMs(int) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withReconnectTimeoutSecs(long,long) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withTimeoutMs(int) // // Websocket options: // Option optUseWebsocket = new Option("w", "websocket", false, "Use Websockets"); // opts.addOption(optUseWebsocket); // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWebsocketCredentialsProvider(software.amazon.awssdk.crt.auth.credentials.CredentialsProvider) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWebsocketSigningRegion(java.lang.String) // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWebsocketProxyOptions(software.amazon.awssdk.crt.http.HttpProxyOptions) // // Other miscellaneous options: // https://aws.github.io/aws-iot-device-sdk-java-v2/software/amazon/awssdk/iot/AwsIotMqttConnectionBuilder.html#withWill(software.amazon.awssdk.crt.mqtt.MqttMessage) CommandLine cmd = null; CommandLineParser cmdParser = new BasicParser(); final String usagePrefix = "java -jar " + jarName + " -H <host> -a <action> [options]";//+ "\n\n" + AwsIotConstants.PROJECT_TITLE + "\n\n"; HelpFormatter helpFmt = new HelpFormatter(); // Determine the width of the terminal environment String columnsEnv = System.getenv("COLUMNS"); // Not exported by default. @TODO: Do something better to determine console width? int terminalWidth = 120; if (columnsEnv != null) { try { terminalWidth = Integer.parseInt(columnsEnv); } catch (NumberFormatException ex) { // Do nothing here; use default width } } helpFmt.setWidth(terminalWidth); // Check if "help" argument was passed in if (Arrays.stream(args).anyMatch(arg -> arg.equals("--help") || arg.equals("-h"))) { helpFmt.printHelp(usagePrefix, "\n", opts, "\n\n"+AwsIotConstants.PROJECT_TITLE); System.exit(0); } try { cmd = cmdParser.parse(opts, args); // Check for valid action String action = cmd.getOptionValue("a"); if (!AwsIotConstants.CLI_ACTIONS.contains(action)) { throw new org.apache.commons.cli.ParseException("Invalid action: \"" + action + "\""); } } catch (org.apache.commons.cli.ParseException ex) { System.err.println("[ERROR] " + ex.getMessage() + "\n"); helpFmt.printHelp(usagePrefix, "\n", opts, "\n\n"+AwsIotConstants.PROJECT_TITLE); System.exit(154); } // Add any manually-specified topic subscriptions if (cmd.hasOption("T")) { String topicStr = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("T")); String[] topicStrs = topicStr.split("\n"); for (String t : topicStrs) { System.err.println("[INFO] Adding custom MQTT topic subscription: " + t); topicSubcriptions.add(t); } System.err.println("[INFO] Added " + topicStrs.length + " custom MQTT topic subscription" + (topicStrs.length == 1 ? "" : "s")); } // Add any manually-specified topic regexes if (cmd.hasOption("X")) { String topicRegexStr = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("X")); String[] topicRegexStrs = topicRegexStr.split("\n"); for (String r : topicRegexStrs) { System.err.println("[INFO] Adding custom MQTT topic regex: " + r); topicsRegex.add(PatternWithNamedGroups.compile(r)); } System.err.println("[INFO] Added " + topicRegexStrs.length + " custom MQTT topic regular expression" + (topicRegexStrs.length == 1 ? "" : "s")); } return cmd; } public static void buildConnection(CommandLine cmd) throws CertificateException, FileNotFoundException, IOException, KeyStoreException, NoSuchAlgorithmException, org.apache.commons.cli.ParseException { // Determine how to initialize the connection builder AwsIotMqttConnectionBuilder connBuilder = null; TlsContextOptions tlsCtxOpts = null; String action = cmd.getOptionValue("a"); // Check for arguments required for specific actions if (action.equals(AwsIotConstants.ACTION_MQTT_DUMP)) { // Nothing required except auth data } else if (action.equals(AwsIotConstants.ACTION_MQTT_TOPIC_FIELD_HARVEST)) { // Nothing required except auth data } else if (action.equals(AwsIotConstants.ACTION_IAM_CREDS)) { if (!cmd.hasOption("R")) { throw new IllegalArgumentException("Operation " + action + " requires role(s) to be specified with \"-R\""); } } else if (action.equals(AwsIotConstants.ACTION_MQTT_SCRIPT)) { if (!cmd.hasOption("f")) { System.err.println("[ERROR] \"" + action + "\" action requires an MQTT script file (\"-f\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_MQTT_DATA_EXFIL)) { // Nothing required except auth data } else if (action.equals(AwsIotConstants.ACTION_GET_JOBS)) { if (!(cmd.hasOption("t") || cmd.hasOption("C"))) { System.err.println("[ERROR] \"" + action + "\" action requires thing name (\"-t\") or client ID (\"-C\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_GET_SHADOW)) { // @TODO: Improve implementation to support this action in more ways if (!(cmd.hasOption("c") && cmd.hasOption("k") && cmd.hasOption("A"))) { System.err.println("[ERROR] \"" + action + "\" action currently requires file paths for client certificate (\"-c\"), client private key (\"-k\"), and certificate authority (\"-A\")"); System.exit(3); } if (!(cmd.hasOption("t") || cmd.hasOption("C"))) { System.err.println("[ERROR] \"" + action + "\" action requires thing name (\"-t\") or client ID (\"-C\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_LIST_NAMED_SHADOWS)) { // @TODO: Improve implementation to support this action in more ways if (!(cmd.hasOption("c") && cmd.hasOption("k") && cmd.hasOption("A"))) { System.err.println("[ERROR] \"" + action + "\" action currently requires file paths for client certificate (\"-c\"), client private key (\"-k\"), and certificate authority (\"-A\")"); System.exit(3); } if (!(cmd.hasOption("t") || cmd.hasOption("C"))) { System.err.println("[ERROR] \"" + action + "\" action requires thing name (\"-t\") or client ID (\"-C\")"); System.exit(3); } } else if (action.equals(AwsIotConstants.ACTION_LIST_RETAINED_MQTT_MESSAGES)) { // @TODO: Improve implementation to support this action in more ways if (!(cmd.hasOption("c") && cmd.hasOption("k") && cmd.hasOption("A"))) { System.err.println("[ERROR] \"" + action + "\" action currently requires file paths for client certificate (\"-c\"), client private key (\"-k\"), and certificate authority (\"-A\")"); System.exit(3); } } // Determine authentication mechanism if (cmd.hasOption("c") && cmd.hasOption("k")) { // mTLS using specified client certificate and private key String cert = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("c")); String privKey = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("k")); connBuilder = AwsIotMqttConnectionBuilder.newMtlsBuilder(cert, privKey); tlsCtxOpts = TlsContextOptions.createWithMtls(cert, privKey); } else if (cmd.hasOption("K")) { // mTLS using keystore file String ksPath = cmd.getOptionValue("K"); if (!cmd.hasOption("q")) { System.err.println("[ERROR] Provide a keystore password with \"-q\""); System.exit(1); } String ksPw = cmd.getOptionValue("q"); if (cmd.hasOption("N") || cmd.hasOption("Q")) { // JKS keystore if (!cmd.hasOption("N")) { System.err.println("[ERROR] JKS keystore requires a keystore alias. Provide an alias with \"-A\""); System.exit(1); } else if (!cmd.hasOption("Q")) { System.err.println("[ERROR] JKS keystore requires a certificate password. Provide a password with \"-Q\""); System.exit(1); } KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(ksPath), ksPw.toCharArray()); String ksAlias = cmd.getOptionValue("N"); String certPw = cmd.getOptionValue("Q"); connBuilder = AwsIotMqttConnectionBuilder.newJavaKeystoreBuilder(ks, ksAlias, certPw); tlsCtxOpts = TlsContextOptions.createWithMtlsJavaKeystore​(ks, ksAlias, certPw); } else { // P12 keystore connBuilder = AwsIotMqttConnectionBuilder.newMtlsPkcs12Builder(ksPath, ksPw); tlsCtxOpts = TlsContextOptions.createWithMtlsPkcs12​(ksPath, ksPw); } } else if (cmd.hasOption("windows-cert-store")) { // mTLS using Windows certificate store String winStorePath = cmd.getOptionValue("W"); connBuilder = AwsIotMqttConnectionBuilder.newMtlsWindowsCertStorePathBuilder(winStorePath); tlsCtxOpts = TlsContextOptions.createWithMtlsWindowsCertStorePath​(winStorePath); } else if (cmd.hasOption("custom-auth-name") || cmd.hasOption("custom-auth-sig") || cmd.hasOption("custom-auth-tok-name") || cmd.hasOption("custom-auth-tok-val") || cmd.hasOption("custom-auth-user") || cmd.hasOption("custom-auth-pass")) { // Custom authentication connBuilder = AwsIotMqttConnectionBuilder.newDefaultBuilder(); connBuilder = connBuilder.withCustomAuthorizer( cmd.getOptionValue("custom-auth-user"), cmd.getOptionValue("custom-auth-name"), cmd.getOptionValue("custom-auth-sig"), // @TODO: "It is strongly suggested to URL-encode this value; the SDK will not do so for you." cmd.getOptionValue("custom-auth-pass"), cmd.getOptionValue("custom-auth-tok-name"), // @TODO: "It is strongly suggested to URL-encode this value; the SDK will not do so for you." cmd.getOptionValue("custom-auth-tok-val") ); tlsCtxOpts = TlsContextOptions.createDefaultClient(); } else { System.err.println("[ERROR] Missing connection properties (must provide some combination of \"-c\", \"-k\", \"-K\", \"-q\", \"-A\", \"-Q\", \"--custom-auth-*\", etc.)"); System.exit(1); } if (cmd.hasOption("C")) { clientId = cmd.getOptionValue("C"); } else { // Generate a unique client ID clientId = "DEVICE_" + System.currentTimeMillis(); } System.err.println("[INFO] Using client ID: " + clientId); // Configure the connection connBuilder = connBuilder.withConnectionEventCallbacks(connectionCallbacks); connBuilder = connBuilder.withClientId(clientId); connBuilder = connBuilder.withEndpoint(cmd.getOptionValue("H")); if (cmd.hasOption("A")) { String certAuthority = Util.getTextFileDataFromOptionalPath(cmd.getOptionValue("A")); connBuilder = connBuilder.withCertificateAuthority(certAuthority); tlsCtxOpts = tlsCtxOpts.withCertificateAuthority(certAuthority); } if (cmd.hasOption("u")) { connBuilder = connBuilder.withUsername(cmd.getOptionValue("u")); } if (cmd.hasOption("p")) { connBuilder = connBuilder.withPassword(cmd.getOptionValue("p")); } int portNum = -1; if (cmd.hasOption("P")) { portNum = ((Number)cmd.getParsedOptionValue("P")).intValue(); if (portNum < 1 || portNum > 65535) { System.err.println("[ERROR] Port number must be in the range 1-65535 (inclusive)"); System.exit(1); } connBuilder = connBuilder.withPort((short)portNum); } if (cmd.hasOption("U")) { tlsCtxOpts = tlsCtxOpts.withVerifyPeer​(false); } // if (cmd.hasOption("w")) { // connBuilder = connBuilder.withWebsockets(true); // } // Build tlsContext = new ClientTlsContext(tlsCtxOpts); if (cmd.hasOption("5")) { // @TODO throw new UnsupportedOperationException("MQTT5 connections not supported yet"); //mqtt5ClientConnection = connBuilder.toAwsIotMqtt5ClientBuilder().build(); } else { clientConnection = connBuilder.build(); } connBuilder.close(); } public static void mqttConnect() { System.err.println("[INFO] Connecting to " + cmd.getOptionValue("H")); if (mqtt5ClientConnection != null) { mqtt5ClientConnection.start(); } else { CompletableFuture<Boolean> isCleanConnFuture = clientConnection.connect(); try { Boolean isCleanSession = isCleanConnFuture.get(); // System.err.println("[INFO] Clean session? " + isCleanSession.toString()); } catch (ExecutionException | InterruptedException e) { System.err.println("[ERROR] Exception connecting: " + e.toString()); System.exit(2); } } } // Extracts known data fields from MQTT topic strings. Note that this method is NOT meant for extracting data from MQTT message payloads. public static Map<String, String> extractFieldsFromTopic(String topic) { if (topic.equals(AwsIotConstants.MQTT_PING_TOPIC)) { return null; } for (PatternWithNamedGroups p : topicsRegex) { Matcher matcher = p.getPattern().matcher(topic); boolean matchFound = matcher.find(); if (matchFound) { List<String> groupNames = p.getGroupNames(); if (groupNames.size() != matcher.groupCount()) { System.err.println("[WARNING] Mismatch between number of capture group names (" + groupNames.size() + ") and matched group count (" + matcher.groupCount() + ")"); continue; } HashMap<String, String> captures = new HashMap<String, String>(); for (int i = 1; i <= matcher.groupCount(); i++) { captures.put(groupNames.get(i-1), matcher.group(i)); } return captures; } } if (topic.startsWith(AwsIotConstants.MQTT_RESERVED_TOPIC_PREFIX)) { // All AWS-reserved MQTT topics should be matched... System.err.println("[WARNING] Failed to extract fields from reserved MQTT topic: " + topic); } return null; } // Returns the list of user-specified MQTT topics, or a wildcard topic representing all topics ("#") public static List<String> buildMqttTopicList() { ArrayList<String> topics = new ArrayList<String>(); if (topicSubcriptions.isEmpty()) { // Use wildcard to subscribe to all topics topics.add(AwsIotConstants.MQTT_ALL_TOPICS); } else { // Subscribe to user-specified topics only topics.addAll(topicSubcriptions); } return topics; } // Dump all MQTT messages received via subscribed MQTT topics. Runs forever (or until cancelled by the user with Ctrl+C) public static void beginMqttDump() throws InterruptedException, ExecutionException { final List<String> topics = buildMqttTopicList(); for (final String topic : topics) { System.err.println("[INFO] Subscribing to topic for MQTT dump (\"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, genericMqttMsgConsumer); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); } Util.sleepForever(); } // Extract known data fields from subscribed MQTT topics. Runs forever (or until cancelled by the user with Ctrl+C). // Note that this only extracts data from the topic itself, and ignores MQTT message payloads. public static void beginMqttTopicFieldHarvesting() throws InterruptedException, ExecutionException { final List<String> topics = buildMqttTopicList(); for (final String topic : topics) { System.err.println("[INFO] Subscribing to topic for topic field harvesting (\"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, topicFieldHarvester); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); } Util.sleepForever(); } // Test whether the AWS IoT service can be used for data exfiltration via arbitrary topics public static void testDataExfilChannel() throws InterruptedException, ExecutionException { final String timestamp = "" + System.currentTimeMillis(); ArrayList<String> topics = new ArrayList<String>(); if (topicSubcriptions.isEmpty()) { // By default, use the current epoch timestamp for a unique MQTT topic topics.add(timestamp); } else { topics.addAll(topicSubcriptions); } final Consumer<MqttMessage> dataExfilConsumer = new Consumer<MqttMessage>() { @Override public void accept(MqttMessage message) { final String payloadStr = new String(message.getPayload(), StandardCharsets.UTF_8).trim(); String msg = null; if (payloadStr.equals(timestamp)) { System.out.println("\n[Data exfiltration] Confirmed data exfiltration channel via topic: " + message.getTopic()); } else { System.err.println("[WARNING] Unknown data received via data exfiltration channel (topic: " + message.getTopic() + "): " + payloadStr); } } }; // Subscribe to the data exfiltration topic(s) for (final String topic : topics) { System.err.println("[INFO] Testing data exfiltration via arbitrary topics (using topic: \"" + topic + "\")"); CompletableFuture<Integer> subscription = clientConnection.subscribe(topic, QualityOfService.AT_LEAST_ONCE, dataExfilConsumer); subscription.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topic + ": " + throwable.toString()); return -1; }); subscription.get(); // Publish data to the data exfiltration topic MqttMessage msg = new MqttMessage(topic, timestamp.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_LEAST_ONCE); CompletableFuture<Integer> publication = clientConnection.publish(msg); publication.get(); } // Sleep 3 seconds to see if we receive our payload try { Thread.sleep(3000); } catch (InterruptedException ex) { System.err.println("[WARNING] Data exfiltration sleep operation was interrupted: " + ex.getMessage()); } // Unsubscribe from the data exfiltration topic(s) for (final String topic : topics) { CompletableFuture<Integer> unsub = clientConnection.unsubscribe(topic); unsub.get(); } } // Attempts to obtain IAM credentials for the specified role using the client mTLS key pair from an IoT "Thing" (device) // // Note that the iot:CredentialProvider is a different host/endpoint than the base IoT endpoint; it should have the format: // ${random_id}.credentials.iot.${region}.amazonaws.com // // (The random_id will also be different from the one in the base IoT Core endpoint) public static List<Credentials> getIamCredentialsFromDeviceX509(String[] roleAliases, String thingName) { // See also: // https://github.com/aws/aws-iot-device-sdk-java-v2/blob/de4e5f3be56c325975674d4e3c0a801392edad96/samples/X509CredentialsProviderConnect/src/main/java/x509credentialsproviderconnect/X509CredentialsProviderConnect.java#L99 // https://awslabs.github.io/aws-crt-java/software/amazon/awssdk/crt/auth/credentials/X509CredentialsProvider.html // https://aws.amazon.com/blogs/security/how-to-eliminate-the-need-for-hardcoded-aws-credentials-in-devices-by-using-the-aws-iot-credentials-provider/ final String endpoint = cmd.getOptionValue("H"); if (!endpoint.contains("credentials.iot")) { System.err.println("[WARNING] Endpoint \"" + endpoint + "\" might not be an AWS IoT credentials provider; are you sure you have the right hostname? (Expected format: \"${random_id}.credentials.iot.${region}.amazonaws.com\")"); } ArrayList<Credentials> discoveredCreds = new ArrayList<Credentials>(); for (String roleAlias : roleAliases) { // // mTLS HTTP client method: // String url = "https://" + endpoint + "/role-aliases/" + roleAlias + "/credentials"; // String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // // Need to add header "x-amzn-iot-thingname: " + thingName // System.out.println(data); // return null; Credentials credentials = null; X509CredentialsProvider.X509CredentialsProviderBuilder x509CredsBuilder = new X509CredentialsProvider.X509CredentialsProviderBuilder(); x509CredsBuilder = x509CredsBuilder.withTlsContext(tlsContext); x509CredsBuilder = x509CredsBuilder.withEndpoint​(endpoint); x509CredsBuilder = x509CredsBuilder.withRoleAlias(roleAlias); x509CredsBuilder = x509CredsBuilder.withThingName(thingName); X509CredentialsProvider credsProvider = x509CredsBuilder.build(); CompletableFuture<Credentials> credsFuture = credsProvider.getCredentials(); try { credentials = credsFuture.get(); String credsStr = "{\"credentials\":{\"accessKeyId\":\"" + new String(credentials.getAccessKeyId(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"secretAccessKey\":\"" + new String(credentials.getSecretAccessKey(), StandardCharsets.UTF_8) + "\""; credsStr += ",\"sessionToken\":\"" + new String(credentials.getSessionToken(), StandardCharsets.UTF_8) + "\"}}"; System.out.println(credsStr); discoveredCreds.add(credentials); } catch (ExecutionException | InterruptedException ex) { System.err.println("[ERROR] Failed to obtain credentials from X509 (role=\"" + roleAlias + "\"; thingName=\"" + thingName + "\"): " + ex.getMessage()); } credsProvider.close(); } return discoveredCreds; } public static void getDeviceShadow(String thingName, String shadowName) { // https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-rest-api.html#API_GetThingShadow // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP request (mTLS required): // // GET /things/<thingName>/shadow?name=<shadowName> HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 // // Note: Shadow name is optional (null name = classic device shadow) String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/things/" + thingName + "/shadow" + (shadowName == null ? "" : "?name="+shadowName); String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); System.out.println(data); } public static void getNamedShadows(String thingName) { // @TODO // https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-rest-api.html#API_ListNamedShadowsForThing // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP request (mTLS required): // // GET /api/things/shadow/ListNamedShadowsForThing/<thingName>?maxResults=200&nextToken= HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/api/things/shadow/ListNamedShadowsForThing/" + thingName + "?maxResults=200"; //+"&nextToken="; String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // @TODO: Iterate through all pages of named shadows System.out.println(data); } public static void getRetainedMqttMessages() { // @TODO // https://docs.aws.amazon.com/iot/latest/apireference/API_iotdata_ListRetainedMessages.html // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/iotdataplane/IotDataPlaneClient.html // https://dzone.com/articles/execute-mtls-calls-using-java // // Example HTTP requests (mTLS required): // // GET /retainedMessage?maxResults=200&nextToken= HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 // // GET /retainedMessage/<topic> HTTP/1.1 // Host: <instance>.iot.<region>.amazonaws.com:8443 String url = "https://" + cmd.getOptionValue("H") + ":" + AwsIotConstants.AWS_IOT_REST_API_PORT + "/retainedMessage?maxResults=200"; //+"&nextToken="; String data = MtlsHttpClient.mtlsHttpGet(url, cmd.getOptionValue("c"), cmd.getOptionValue("k"), cmd.getOptionValue("A"), true); // @TODO: Iterate through all pages of retained messages // @TODO: Get message bodies for all retained message topics System.out.println(data); } // https://docs.aws.amazon.com/iot/latest/developerguide/jobs-mqtt-api.html public static void getPendingJobs() throws InterruptedException, ExecutionException { final String thingName = cmd.hasOption("t") ? cmd.getOptionValue("t") : clientId; final String topic = "$aws/things/" + thingName + "/jobs/get"; final String topicAccepted = topic + "/accepted"; final String topicRejected = topic + "/rejected"; final String message = "{}"; CompletableFuture<Integer> subAccept = clientConnection.subscribe(topicAccepted, QualityOfService.AT_LEAST_ONCE, genericMqttMsgConsumer); subAccept.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topicAccepted + ": " + throwable.toString()); return -1; }); subAccept.get(); CompletableFuture<Integer> subReject = clientConnection.subscribe(topicRejected, QualityOfService.AT_LEAST_ONCE, genericMqttMsgConsumer); subReject.exceptionally((Throwable throwable) -> { System.err.println("[ERROR] Failed to process message for " + topicRejected + ": " + throwable.toString()); return -1; }); subReject.get(); MqttMessage msg = new MqttMessage(topic, message.getBytes(StandardCharsets.UTF_8), QualityOfService.AT_LEAST_ONCE); CompletableFuture<Integer> publication = clientConnection.publish(msg); publication.get(); // Sleep 3 seconds to see if we receive our payload try { Thread.sleep(3000); } catch (InterruptedException ex) { System.err.println("[WARNING] Get pending jobs sleep operation was interrupted: " + ex.getMessage()); } // Unsubscribe from the accept/reject topic(s) CompletableFuture<Integer> unsubAccept = clientConnection.unsubscribe(topicAccepted); unsubAccept.get(); CompletableFuture<Integer> unsubReject = clientConnection.unsubscribe(topicRejected); unsubReject.get(); } public static void runMqttScript(String scriptFilePath) throws IOException, InterruptedException, ExecutionException { final String tag = "[MQTT Script] "; final int maxLogMsgSize = 80; System.err.println(tag + "Executing script: " + scriptFilePath);
List<MqttScript.Instruction> instructions = MqttScript.parseFromFile(scriptFilePath);
2
2023-11-06 23:10:21+00:00
12k
baguchan/BetterWithAquatic
src/main/java/baguchan/better_with_aquatic/BetterWithAquatic.java
[ { "identifier": "ModBlocks", "path": "src/main/java/baguchan/better_with_aquatic/block/ModBlocks.java", "snippet": "public class ModBlocks {\n\n\n\tpublic static final Block sea_grass = new BlockBuilder(BetterWithAquatic.MOD_ID)\n\t\t.setHardness(0.0f)\n\t\t.setResistance(100F)\n\t\t.setLightOpacity(1)\...
import baguchan.better_with_aquatic.block.ModBlocks; import baguchan.better_with_aquatic.entity.EntityAnglerFish; import baguchan.better_with_aquatic.entity.EntityDrowned; import baguchan.better_with_aquatic.entity.EntityFish; import baguchan.better_with_aquatic.entity.EntityFrog; import baguchan.better_with_aquatic.item.ModItems; import baguchan.better_with_aquatic.packet.SwimPacket; import net.fabricmc.api.ModInitializer; import net.minecraft.client.gui.guidebook.mobs.MobInfoRegistry; import net.minecraft.core.achievement.stat.StatList; import net.minecraft.core.achievement.stat.StatMob; import net.minecraft.core.block.Block; import net.minecraft.core.entity.EntityDispatcher; import net.minecraft.core.item.Item; import turniplabs.halplibe.helper.EntityHelper; import turniplabs.halplibe.helper.NetworkHelper; import turniplabs.halplibe.util.ConfigHandler; import turniplabs.halplibe.util.GameStartEntrypoint; import java.util.Properties;
9,480
package baguchan.better_with_aquatic; public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer { public static final String MOD_ID = "better_with_aquatic"; private static final boolean enable_drowned; private static final boolean enable_swim; public static ConfigHandler config; static { Properties prop = new Properties(); prop.setProperty("starting_block_id", "3200"); prop.setProperty("starting_item_id", "26000"); prop.setProperty("starting_entity_id", "600"); prop.setProperty("enable_swim", "true"); prop.setProperty("enable_drowned", "true"); config = new ConfigHandler(BetterWithAquatic.MOD_ID, prop); entityID = config.getInt("starting_entity_id"); enable_swim = config.getBoolean("enable_swim"); enable_drowned = config.getBoolean("enable_drowned"); config.updateConfig(); } public static int entityID; @Override public void onInitialize() { NetworkHelper.register(SwimPacket.class, true, false); } @Override public void beforeGameStart() { Block.lightBlock[Block.fluidWaterFlowing.id] = 1; Block.lightBlock[Block.fluidWaterStill.id] = 1; ModBlocks.createBlocks();
package baguchan.better_with_aquatic; public class BetterWithAquatic implements GameStartEntrypoint, ModInitializer { public static final String MOD_ID = "better_with_aquatic"; private static final boolean enable_drowned; private static final boolean enable_swim; public static ConfigHandler config; static { Properties prop = new Properties(); prop.setProperty("starting_block_id", "3200"); prop.setProperty("starting_item_id", "26000"); prop.setProperty("starting_entity_id", "600"); prop.setProperty("enable_swim", "true"); prop.setProperty("enable_drowned", "true"); config = new ConfigHandler(BetterWithAquatic.MOD_ID, prop); entityID = config.getInt("starting_entity_id"); enable_swim = config.getBoolean("enable_swim"); enable_drowned = config.getBoolean("enable_drowned"); config.updateConfig(); } public static int entityID; @Override public void onInitialize() { NetworkHelper.register(SwimPacket.class, true, false); } @Override public void beforeGameStart() { Block.lightBlock[Block.fluidWaterFlowing.id] = 1; Block.lightBlock[Block.fluidWaterStill.id] = 1; ModBlocks.createBlocks();
ModItems.onInitialize();
5
2023-11-08 23:02:14+00:00
12k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/db/kernel/FileDataBase.java
[ { "identifier": "SyncDetectorManager", "path": "util/src/main/java/org/by1337/bauc/util/SyncDetectorManager.java", "snippet": "public class SyncDetectorManager {\n private final static SyncDetector syncDetector;\n\n static {\n syncDetector = switch (Version.VERSION) {\n case V1_1...
import org.bukkit.Bukkit; import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitTask; import org.by1337.api.util.NameKey; import org.by1337.bauc.util.SyncDetectorManager; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.auc.UnsoldItem; import org.by1337.bauction.auc.User; import org.by1337.bauction.db.event.*; import org.by1337.bauction.event.*; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.serialize.FileUtil; import org.by1337.bauction.util.*; import java.io.File; import java.io.IOException; import java.util.*;
10,055
package org.by1337.bauction.db.kernel; public class FileDataBase extends DataBaseCore implements Listener { protected final long removeTime; protected final boolean removeExpiredItems; private BukkitTask boostTask; public FileDataBase(Map<NameKey, Category> categoryMap, Map<NameKey, Sorting> sortingMap) { super(categoryMap, sortingMap); removeExpiredItems = Main.getCfg().getConfig().getAsBoolean("remove-expired-items.enable"); removeTime = NumberUtil.getTime(Main.getCfg().getConfig().getAsString("remove-expired-items.time")); Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); boostTask = new BukkitRunnable() { @Override public void run() { Bukkit.getOnlinePlayers().forEach(player -> boostCheck(player.getUniqueId())); } }.runTaskTimerAsynchronously(Main.getInstance(), 20 * 5, 20 * 5); expiredChecker(); unsoldItemRemover(); } protected Runnable sellItemRemChecker; protected BukkitTask sellItemRemCheckerTask; protected Runnable unsoldItemRemChecker; protected BukkitTask unsoldItemRemCheckerTask; protected void expiredChecker() { sellItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getSellItemsSize() > 0) { SellItem sellItem = getFirstSellItem(); if (sellItem.getRemovalDate() < time) { expiredItem(sellItem); removed++; if (removed >= 30) break; } else { sleep = Math.min((sellItem.getRemovalDate() - time) + 50, 50L * 100); // 100 ticks break; } } if (sellItemRemCheckerTask.isCancelled()) return; sellItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), sellItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; sellItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), sellItemRemChecker, 0); } protected void unsoldItemRemover() { if (removeExpiredItems) { unsoldItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getUnsoldItemsSize() > 0) { UnsoldItem unsoldItem = getFirstUnsoldItem(); if (unsoldItem.getDeleteVia() < time) { removeUnsoldItem(unsoldItem.getUniqueName()); removed++; if (removed >= 30) break; } else { sleep = Math.min((unsoldItem.getDeleteVia() - time) + 50, 50L * 100); // 100 ticks break; } } if (unsoldItemRemCheckerTask.isCancelled()) return; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, 0); } } @EventHandler public void onJoin(PlayerJoinEvent event) { boostCheck(event.getPlayer().getUniqueId()); } @Override protected void expiredItem(SellItem item) { removeSellItem(item.getUniqueName()); CUnsoldItem unsoldItem = new CUnsoldItem(item.getItem(), item.getSellerUuid(), item.getRemovalDate(), item.getRemovalDate() + removeTime); addUnsoldItem(unsoldItem); } public void validateAndAddItem(SellItemEvent event) { try { update(); SellItem sellItem = event.getSellItem(); if (!hasUser(event.getUser().getUuid())) { throw new IllegalStateException("user non-exist: " + event.getUser()); } if (hasSellItem(sellItem.getUniqueName())) { throw new IllegalStateException("sell item non-exist: " + event.getSellItem()); } CUser user = (CUser) getUser(event.getUser().getUuid()); SellItemProcess sellItemProcess = new SellItemProcess(!SyncDetectorManager.isSync(), user, sellItem); Bukkit.getPluginManager().callEvent(sellItemProcess); if (sellItemProcess.isCancelled()) { event.setValid(false); event.setReason(sellItemProcess.getReason()); return; } if (Main.getCfg().getMaxSlots() <= (sellItemsCountByUser(user.uuid) - user.getExternalSlots())) { event.setValid(false);
package org.by1337.bauction.db.kernel; public class FileDataBase extends DataBaseCore implements Listener { protected final long removeTime; protected final boolean removeExpiredItems; private BukkitTask boostTask; public FileDataBase(Map<NameKey, Category> categoryMap, Map<NameKey, Sorting> sortingMap) { super(categoryMap, sortingMap); removeExpiredItems = Main.getCfg().getConfig().getAsBoolean("remove-expired-items.enable"); removeTime = NumberUtil.getTime(Main.getCfg().getConfig().getAsString("remove-expired-items.time")); Bukkit.getPluginManager().registerEvents(this, Main.getInstance()); boostTask = new BukkitRunnable() { @Override public void run() { Bukkit.getOnlinePlayers().forEach(player -> boostCheck(player.getUniqueId())); } }.runTaskTimerAsynchronously(Main.getInstance(), 20 * 5, 20 * 5); expiredChecker(); unsoldItemRemover(); } protected Runnable sellItemRemChecker; protected BukkitTask sellItemRemCheckerTask; protected Runnable unsoldItemRemChecker; protected BukkitTask unsoldItemRemCheckerTask; protected void expiredChecker() { sellItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getSellItemsSize() > 0) { SellItem sellItem = getFirstSellItem(); if (sellItem.getRemovalDate() < time) { expiredItem(sellItem); removed++; if (removed >= 30) break; } else { sleep = Math.min((sellItem.getRemovalDate() - time) + 50, 50L * 100); // 100 ticks break; } } if (sellItemRemCheckerTask.isCancelled()) return; sellItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), sellItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; sellItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), sellItemRemChecker, 0); } protected void unsoldItemRemover() { if (removeExpiredItems) { unsoldItemRemChecker = () -> { long time = System.currentTimeMillis(); try { long sleep = 50L * 5; int removed = 0; while (getUnsoldItemsSize() > 0) { UnsoldItem unsoldItem = getFirstUnsoldItem(); if (unsoldItem.getDeleteVia() < time) { removeUnsoldItem(unsoldItem.getUniqueName()); removed++; if (removed >= 30) break; } else { sleep = Math.min((unsoldItem.getDeleteVia() - time) + 50, 50L * 100); // 100 ticks break; } } if (unsoldItemRemCheckerTask.isCancelled()) return; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, sleep / 50); } catch (Exception e) { Main.getMessage().error(e); } }; unsoldItemRemCheckerTask = Bukkit.getScheduler().runTaskLaterAsynchronously(Main.getInstance(), unsoldItemRemChecker, 0); } } @EventHandler public void onJoin(PlayerJoinEvent event) { boostCheck(event.getPlayer().getUniqueId()); } @Override protected void expiredItem(SellItem item) { removeSellItem(item.getUniqueName()); CUnsoldItem unsoldItem = new CUnsoldItem(item.getItem(), item.getSellerUuid(), item.getRemovalDate(), item.getRemovalDate() + removeTime); addUnsoldItem(unsoldItem); } public void validateAndAddItem(SellItemEvent event) { try { update(); SellItem sellItem = event.getSellItem(); if (!hasUser(event.getUser().getUuid())) { throw new IllegalStateException("user non-exist: " + event.getUser()); } if (hasSellItem(sellItem.getUniqueName())) { throw new IllegalStateException("sell item non-exist: " + event.getSellItem()); } CUser user = (CUser) getUser(event.getUser().getUuid()); SellItemProcess sellItemProcess = new SellItemProcess(!SyncDetectorManager.isSync(), user, sellItem); Bukkit.getPluginManager().callEvent(sellItemProcess); if (sellItemProcess.isCancelled()) { event.setValid(false); event.setReason(sellItemProcess.getReason()); return; } if (Main.getCfg().getMaxSlots() <= (sellItemsCountByUser(user.uuid) - user.getExternalSlots())) { event.setValid(false);
event.setReason(Lang.getMessage("auction_item_limit_reached"));
5
2023-11-08 18:25:18+00:00
12k
Svydovets-Bobocode-Java-Ultimate-3-0/Bring
src/main/java/svydovets/core/context/beanFactory/BeanFactoryImpl.java
[ { "identifier": "AutowiredAnnotationBeanPostProcessor", "path": "src/main/java/svydovets/core/bpp/AutowiredAnnotationBeanPostProcessor.java", "snippet": "public class AutowiredAnnotationBeanPostProcessor implements BeanPostProcessor {\r\n\r\n private static final Logger log = LoggerFactory.getLogger(...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import svydovets.core.annotation.PostConstruct; import svydovets.core.annotation.Qualifier; import svydovets.core.bpp.AutowiredAnnotationBeanPostProcessor; import svydovets.core.bpp.BeanPostProcessor; import svydovets.core.context.ApplicationContext; import svydovets.core.context.beanDefinition.BeanAnnotationBeanDefinition; import svydovets.core.context.beanDefinition.BeanDefinition; import svydovets.core.context.beanDefinition.BeanDefinitionFactory; import svydovets.core.context.beanDefinition.ComponentAnnotationBeanDefinition; import svydovets.core.context.beanFactory.command.CommandFactory; import svydovets.core.context.beanFactory.command.CommandFunctionName; import svydovets.core.exception.*; import svydovets.util.ErrorMessageConstants; import svydovets.util.PackageScanner; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; import static svydovets.util.ErrorMessageConstants.ERROR_CREATED_BEAN_OF_TYPE; import static svydovets.util.ErrorMessageConstants.ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT; import static svydovets.util.ErrorMessageConstants.ERROR_THE_METHOD_THAT_WAS_ANNOTATED_WITH_POST_CONSTRUCT; import static svydovets.util.ErrorMessageConstants.NO_BEAN_DEFINITION_FOUND_OF_TYPE; import static svydovets.util.ErrorMessageConstants.NO_BEAN_FOUND_OF_TYPE; import static svydovets.util.ErrorMessageConstants.NO_UNIQUE_BEAN_FOUND_OF_TYPE; import static svydovets.util.NameResolver.resolveBeanName; import static svydovets.util.ReflectionsUtil.prepareConstructor; import static svydovets.util.ReflectionsUtil.prepareMethod;
10,468
package svydovets.core.context.beanFactory; /** * The {@code BeanFactoryImpl} class is an implementation of the {@link BeanFactory} interface, * providing comprehensive functionality for managing beans within the custom Inversion of Control (IoC) framework. * This class includes features for bean registration, retrieval, lifecycle management, and advanced capabilities * such as package scanning and custom command execution. * * <h2>Supported Scopes:</h2> * The {@code BeanFactoryImpl} supports the following bean scopes: * <ul> * <li>{@link ApplicationContext#SCOPE_SINGLETON}: Indicates that a single instance of the bean should be created * and shared within the IoC container.</li> * <li>{@link ApplicationContext#SCOPE_PROTOTYPE}: Indicates that a new instance of the bean should be created * whenever it is requested.</li> * </ul> * * <h2>Bean Lifecycle and Post-Processing:</h2> * Beans' lifecycle and post-processing are managed through the use of {@link BeanPostProcessor} instances, * allowing for customization and processing of beans before and after instantiation. The default implementation * includes an {@link AutowiredAnnotationBeanPostProcessor} for handling autowiring dependencies using annotations. * Additional post-processors can be added to the {@code beanPostProcessors} list for extended functionality. * * <h2>Command Factory:</h2> * The {@code BeanFactoryImpl} utilizes a {@link CommandFactory} to register and execute commands related to * bean creation and retrieval. Commands are registered for operations such as getting a bean by type and * getting beans of a specific type. Custom commands can be added to the {@code commandFactory} for specialized use cases. * * <h2>Package Scanning:</h2> * The package scanning functionality is provided by the {@link PackageScanner}, allowing developers to register * beans by specifying base packages or base classes. Beans are identified based on specific annotations. * * <h2>Bean Registration:</h2> * The following methods are available for registering beans: * <ul> * <li>{@link #registerBeans(String) registerBeans(String basePackage)}: Scans the specified base package for * classes annotated as beans and registers them in the IoC container.</li> * <li>{@link #registerBeans(Class[]) registerBeans(Class<?>... classes)}: Manually registers the provided classes * as beans in the IoC container.</li> * <li>{@link #registerBean(String, BeanDefinition) registerBean(String beanName, BeanDefinition beanDefinition)}: * Manually registers a bean with a specified name and its corresponding {@link BeanDefinition}.</li> * </ul> * * <h2>Bean Retrieval:</h2> * The following methods are available for retrieving beans: * <ul> * <li>{@link #getBean(Class) getBean(Class<T> requiredType)}: Retrieves a bean of the specified type from the IoC container.</li> * <li>{@link #getBean(String, Class) getBean(String name, Class<T> requiredType)}: Retrieves a named bean of the specified type * from the IoC container.</li> * <li>{@link #getBeansOfType(Class) getBeansOfType(Class<T> requiredType)}: Retrieves all beans of the specified type from the * IoC container, mapping bean names to their instances.</li> * <li>{@link #getBeans() getBeans()}: Retrieves all registered beans in the IoC container, mapping bean names to their instances.</li> * </ul> * * <h2>Usage Example:</h2> * * <pre> * * // Create an instance of the BeanFactory * * BeanFactory beanFactory = new BeanFactoryImpl(); * * * * // Register beans by scanning a base package * * beanFactory.registerBeans("com.example.beans"); * * * * // Register beans manually * * BeanDefinition beanDefinition = new ComponentAnnotationBeanDefinition("myBean", MyBean.class) * * beanFactory.registerBean("myBean", beanDefinition); * * * * // Retrieve a bean by type * * MyBean myBean = beanFactory.getBean(MyBean.class); * * * * // Retrieve a named bean by type * * AnotherBean anotherBean = beanFactory.getBean("anotherBean", AnotherBean.class); * * * * // Retrieve all beans of a specific type * * Map<String, SomeInterface> beansOfType = beanFactory.getBeansOfType(SomeInterface.class); * * * * // Retrieve all registered beans * * Map<String, Object> allBeans = beanFactory.getBeans(); * * </pre> * * <p> * <b>Note:</b> Developers should be familiar with IoC principles and specific annotations or configurations required * for beans to be correctly identified and registered within the IoC container. Additionally, customizations such as * post-processors and commands can be added to extend the functionality of the {@code BeanFactoryImpl}. * * @see PackageScanner * @see BeanPostProcessor * @see BeanDefinitionFactory * @see CommandFactory */ public class BeanFactoryImpl implements BeanFactory { private static final Logger log = LoggerFactory.getLogger(BeanFactoryImpl.class); public static final Set<String> SUPPORTED_SCOPES = new HashSet<>(Arrays.asList( ApplicationContext.SCOPE_SINGLETON, ApplicationContext.SCOPE_PROTOTYPE )); private final Map<String, Object> beanMap = new LinkedHashMap<>(); private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>(); private final PackageScanner packageScanner = new PackageScanner(); private final BeanDefinitionFactory beanDefinitionFactory = new BeanDefinitionFactory(); private final CommandFactory commandFactory = new CommandFactory(); public BeanFactoryImpl() { commandFactory.registryCommand(CommandFunctionName.FC_GET_BEAN, this::createBeanIfNotPresent); commandFactory.registryCommand(CommandFunctionName.FC_GET_BEANS_OF_TYPE, this::getBeansOfType); beanPostProcessors.add(new AutowiredAnnotationBeanPostProcessor(commandFactory)); } /** * Scans the specified base package for classes annotated as beans and registers them in the bean map. * * @param basePackage The base package to scan for classes annotated as beans. */ @Override public void registerBeans(String basePackage) { log.info("Scanning package: {}", basePackage); Set<Class<?>> beanClasses = packageScanner.findAllBeanCandidatesByBasePackage(basePackage); log.info("Registering beans"); doRegisterBeans(beanClasses); } @Override public void registerBeans(Class<?>... classes) { Set<Class<?>> beanClasses = packageScanner.findAllBeanCandidatesByClassTypes(classes); doRegisterBeans(beanClasses); } @Override public void registerBean(String beanName, BeanDefinition beanDefinition) { log.trace("Call registerBean({}, {})", beanName, beanDefinition); if (beanDefinition.getScope().equals(ApplicationContext.SCOPE_SINGLETON) && beanDefinition.getCreationStatus().equals(BeanDefinition.BeanCreationStatus.NOT_CREATED.name())) { saveBean(beanName, beanDefinition); } } @Override public <T> T getBean(Class<T> requiredType) { log.trace("Call getBean({})", requiredType); if (!isSelectSingleBeansOfType(requiredType) || isSelectMoreOneBeanDefinitionsOfType(requiredType)) { return createBeanIfNotPresent(requiredType, true); } String beanName = resolveBeanName(requiredType); return getBean(beanName, requiredType); } @Override public <T> T getBean(String name, Class<T> requiredType) { log.trace("Call getBean({}, {})", name, requiredType); Object bean = Optional.ofNullable(beanMap.get(name)) .or(() -> checkAndCreatePrototypeBean(name, requiredType)) .orElseThrow(() -> new NoSuchBeanDefinitionException(String .format(NO_BEAN_FOUND_OF_TYPE, requiredType.getName()))); return requiredType.cast(bean); } @Override public <T> Map<String, T> getBeansOfType(Class<T> requiredType) { return beanMap.entrySet() .stream() .filter(entry -> requiredType.isAssignableFrom(entry.getValue().getClass())) .collect(Collectors.toMap(Map.Entry::getKey, entry -> requiredType.cast(entry.getValue()))); } @Override public Map<String, Object> getBeans() { log.trace("Call getBeans()"); return beanMap; } public BeanDefinitionFactory beanDefinitionFactory() { return beanDefinitionFactory; } private void doRegisterBeans(Set<Class<?>> beanClasses) { log.trace("Call doRegisterBeans({})", beanClasses); beanDefinitionFactory .registerBeanDefinitions(beanClasses) .forEach(this::registerBean); log.info("Beans post processing"); beanMap.forEach(this::initializeBeanAfterRegistering); } private Object postProcessBeforeInitialization(Object bean, String beanName) { var beanProcess = bean; for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { beanProcess = beanPostProcessor.postProcessBeforeInitialization(bean, beanName); } return beanProcess; } private Object postProcessAfterInitialization(Object bean, String beanName) { var beanProcess = bean; for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { beanProcess = beanPostProcessor.postProcessAfterInitialization(bean, beanName); } return beanProcess; } private Object initWithBeanPostProcessor(String beanName, Object bean) { bean = postProcessBeforeInitialization(bean, beanName); postConstructInitialization(bean); return postProcessAfterInitialization(bean, beanName); } private void postConstructInitialization(Object bean) throws NoUniquePostConstructException { Class<?> beanType = bean.getClass(); Method[] declaredMethods = beanType.getDeclaredMethods(); Predicate<Method> isAnnotatedMethod = method -> method.isAnnotationPresent(PostConstruct.class); List<Method> methodsAnnotatedWithPostConstruct = Arrays.stream(declaredMethods) .filter(isAnnotatedMethod) .toList(); if (methodsAnnotatedWithPostConstruct.size() > 1) { log.error(ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT); throw new NoUniquePostConstructException(ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT); } methodsAnnotatedWithPostConstruct.stream() .findFirst() .ifPresent(method -> invokePostConstructMethod(bean, method)); } private void invokePostConstructMethod(Object bean, Method method) { try { prepareMethod(method).invoke(bean); } catch (IllegalAccessException | InvocationTargetException exception) {
package svydovets.core.context.beanFactory; /** * The {@code BeanFactoryImpl} class is an implementation of the {@link BeanFactory} interface, * providing comprehensive functionality for managing beans within the custom Inversion of Control (IoC) framework. * This class includes features for bean registration, retrieval, lifecycle management, and advanced capabilities * such as package scanning and custom command execution. * * <h2>Supported Scopes:</h2> * The {@code BeanFactoryImpl} supports the following bean scopes: * <ul> * <li>{@link ApplicationContext#SCOPE_SINGLETON}: Indicates that a single instance of the bean should be created * and shared within the IoC container.</li> * <li>{@link ApplicationContext#SCOPE_PROTOTYPE}: Indicates that a new instance of the bean should be created * whenever it is requested.</li> * </ul> * * <h2>Bean Lifecycle and Post-Processing:</h2> * Beans' lifecycle and post-processing are managed through the use of {@link BeanPostProcessor} instances, * allowing for customization and processing of beans before and after instantiation. The default implementation * includes an {@link AutowiredAnnotationBeanPostProcessor} for handling autowiring dependencies using annotations. * Additional post-processors can be added to the {@code beanPostProcessors} list for extended functionality. * * <h2>Command Factory:</h2> * The {@code BeanFactoryImpl} utilizes a {@link CommandFactory} to register and execute commands related to * bean creation and retrieval. Commands are registered for operations such as getting a bean by type and * getting beans of a specific type. Custom commands can be added to the {@code commandFactory} for specialized use cases. * * <h2>Package Scanning:</h2> * The package scanning functionality is provided by the {@link PackageScanner}, allowing developers to register * beans by specifying base packages or base classes. Beans are identified based on specific annotations. * * <h2>Bean Registration:</h2> * The following methods are available for registering beans: * <ul> * <li>{@link #registerBeans(String) registerBeans(String basePackage)}: Scans the specified base package for * classes annotated as beans and registers them in the IoC container.</li> * <li>{@link #registerBeans(Class[]) registerBeans(Class<?>... classes)}: Manually registers the provided classes * as beans in the IoC container.</li> * <li>{@link #registerBean(String, BeanDefinition) registerBean(String beanName, BeanDefinition beanDefinition)}: * Manually registers a bean with a specified name and its corresponding {@link BeanDefinition}.</li> * </ul> * * <h2>Bean Retrieval:</h2> * The following methods are available for retrieving beans: * <ul> * <li>{@link #getBean(Class) getBean(Class<T> requiredType)}: Retrieves a bean of the specified type from the IoC container.</li> * <li>{@link #getBean(String, Class) getBean(String name, Class<T> requiredType)}: Retrieves a named bean of the specified type * from the IoC container.</li> * <li>{@link #getBeansOfType(Class) getBeansOfType(Class<T> requiredType)}: Retrieves all beans of the specified type from the * IoC container, mapping bean names to their instances.</li> * <li>{@link #getBeans() getBeans()}: Retrieves all registered beans in the IoC container, mapping bean names to their instances.</li> * </ul> * * <h2>Usage Example:</h2> * * <pre> * * // Create an instance of the BeanFactory * * BeanFactory beanFactory = new BeanFactoryImpl(); * * * * // Register beans by scanning a base package * * beanFactory.registerBeans("com.example.beans"); * * * * // Register beans manually * * BeanDefinition beanDefinition = new ComponentAnnotationBeanDefinition("myBean", MyBean.class) * * beanFactory.registerBean("myBean", beanDefinition); * * * * // Retrieve a bean by type * * MyBean myBean = beanFactory.getBean(MyBean.class); * * * * // Retrieve a named bean by type * * AnotherBean anotherBean = beanFactory.getBean("anotherBean", AnotherBean.class); * * * * // Retrieve all beans of a specific type * * Map<String, SomeInterface> beansOfType = beanFactory.getBeansOfType(SomeInterface.class); * * * * // Retrieve all registered beans * * Map<String, Object> allBeans = beanFactory.getBeans(); * * </pre> * * <p> * <b>Note:</b> Developers should be familiar with IoC principles and specific annotations or configurations required * for beans to be correctly identified and registered within the IoC container. Additionally, customizations such as * post-processors and commands can be added to extend the functionality of the {@code BeanFactoryImpl}. * * @see PackageScanner * @see BeanPostProcessor * @see BeanDefinitionFactory * @see CommandFactory */ public class BeanFactoryImpl implements BeanFactory { private static final Logger log = LoggerFactory.getLogger(BeanFactoryImpl.class); public static final Set<String> SUPPORTED_SCOPES = new HashSet<>(Arrays.asList( ApplicationContext.SCOPE_SINGLETON, ApplicationContext.SCOPE_PROTOTYPE )); private final Map<String, Object> beanMap = new LinkedHashMap<>(); private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>(); private final PackageScanner packageScanner = new PackageScanner(); private final BeanDefinitionFactory beanDefinitionFactory = new BeanDefinitionFactory(); private final CommandFactory commandFactory = new CommandFactory(); public BeanFactoryImpl() { commandFactory.registryCommand(CommandFunctionName.FC_GET_BEAN, this::createBeanIfNotPresent); commandFactory.registryCommand(CommandFunctionName.FC_GET_BEANS_OF_TYPE, this::getBeansOfType); beanPostProcessors.add(new AutowiredAnnotationBeanPostProcessor(commandFactory)); } /** * Scans the specified base package for classes annotated as beans and registers them in the bean map. * * @param basePackage The base package to scan for classes annotated as beans. */ @Override public void registerBeans(String basePackage) { log.info("Scanning package: {}", basePackage); Set<Class<?>> beanClasses = packageScanner.findAllBeanCandidatesByBasePackage(basePackage); log.info("Registering beans"); doRegisterBeans(beanClasses); } @Override public void registerBeans(Class<?>... classes) { Set<Class<?>> beanClasses = packageScanner.findAllBeanCandidatesByClassTypes(classes); doRegisterBeans(beanClasses); } @Override public void registerBean(String beanName, BeanDefinition beanDefinition) { log.trace("Call registerBean({}, {})", beanName, beanDefinition); if (beanDefinition.getScope().equals(ApplicationContext.SCOPE_SINGLETON) && beanDefinition.getCreationStatus().equals(BeanDefinition.BeanCreationStatus.NOT_CREATED.name())) { saveBean(beanName, beanDefinition); } } @Override public <T> T getBean(Class<T> requiredType) { log.trace("Call getBean({})", requiredType); if (!isSelectSingleBeansOfType(requiredType) || isSelectMoreOneBeanDefinitionsOfType(requiredType)) { return createBeanIfNotPresent(requiredType, true); } String beanName = resolveBeanName(requiredType); return getBean(beanName, requiredType); } @Override public <T> T getBean(String name, Class<T> requiredType) { log.trace("Call getBean({}, {})", name, requiredType); Object bean = Optional.ofNullable(beanMap.get(name)) .or(() -> checkAndCreatePrototypeBean(name, requiredType)) .orElseThrow(() -> new NoSuchBeanDefinitionException(String .format(NO_BEAN_FOUND_OF_TYPE, requiredType.getName()))); return requiredType.cast(bean); } @Override public <T> Map<String, T> getBeansOfType(Class<T> requiredType) { return beanMap.entrySet() .stream() .filter(entry -> requiredType.isAssignableFrom(entry.getValue().getClass())) .collect(Collectors.toMap(Map.Entry::getKey, entry -> requiredType.cast(entry.getValue()))); } @Override public Map<String, Object> getBeans() { log.trace("Call getBeans()"); return beanMap; } public BeanDefinitionFactory beanDefinitionFactory() { return beanDefinitionFactory; } private void doRegisterBeans(Set<Class<?>> beanClasses) { log.trace("Call doRegisterBeans({})", beanClasses); beanDefinitionFactory .registerBeanDefinitions(beanClasses) .forEach(this::registerBean); log.info("Beans post processing"); beanMap.forEach(this::initializeBeanAfterRegistering); } private Object postProcessBeforeInitialization(Object bean, String beanName) { var beanProcess = bean; for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { beanProcess = beanPostProcessor.postProcessBeforeInitialization(bean, beanName); } return beanProcess; } private Object postProcessAfterInitialization(Object bean, String beanName) { var beanProcess = bean; for (BeanPostProcessor beanPostProcessor : beanPostProcessors) { beanProcess = beanPostProcessor.postProcessAfterInitialization(bean, beanName); } return beanProcess; } private Object initWithBeanPostProcessor(String beanName, Object bean) { bean = postProcessBeforeInitialization(bean, beanName); postConstructInitialization(bean); return postProcessAfterInitialization(bean, beanName); } private void postConstructInitialization(Object bean) throws NoUniquePostConstructException { Class<?> beanType = bean.getClass(); Method[] declaredMethods = beanType.getDeclaredMethods(); Predicate<Method> isAnnotatedMethod = method -> method.isAnnotationPresent(PostConstruct.class); List<Method> methodsAnnotatedWithPostConstruct = Arrays.stream(declaredMethods) .filter(isAnnotatedMethod) .toList(); if (methodsAnnotatedWithPostConstruct.size() > 1) { log.error(ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT); throw new NoUniquePostConstructException(ERROR_NOT_UNIQUE_METHOD_THAT_ANNOTATED_POST_CONSTRUCT); } methodsAnnotatedWithPostConstruct.stream() .findFirst() .ifPresent(method -> invokePostConstructMethod(bean, method)); } private void invokePostConstructMethod(Object bean, Method method) { try { prepareMethod(method).invoke(bean); } catch (IllegalAccessException | InvocationTargetException exception) {
log.error(ERROR_THE_METHOD_THAT_WAS_ANNOTATED_WITH_POST_CONSTRUCT);
13
2023-11-07 06:36:50+00:00
12k
oneqxz/RiseLoader
src/main/java/me/oneqxz/riseloader/fxml/controllers/impl/ClientLaunchController.java
[ { "identifier": "RiseLoaderMain", "path": "src/main/java/me/oneqxz/riseloader/RiseLoaderMain.java", "snippet": "public class RiseLoaderMain {\n\n private static final Logger log = LogManager.getLogger(\"RiseLoader\");\n\n public static void main(String[] args) {\n log.info(\"Starting RiseLo...
import javafx.application.Platform; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import me.oneqxz.riseloader.RiseLoaderMain; import me.oneqxz.riseloader.RiseUI; import me.oneqxz.riseloader.fxml.components.impl.ErrorBox; import me.oneqxz.riseloader.fxml.controllers.Controller; import me.oneqxz.riseloader.fxml.rpc.DiscordRichPresence; import me.oneqxz.riseloader.fxml.scenes.MainScene; import me.oneqxz.riseloader.rise.RiseInfo; import me.oneqxz.riseloader.rise.pub.PublicInstance; import me.oneqxz.riseloader.rise.pub.interfaces.IPublicData; import me.oneqxz.riseloader.rise.run.RunClient; import me.oneqxz.riseloader.settings.Settings; import me.oneqxz.riseloader.utils.OSUtils; import me.oneqxz.riseloader.utils.requests.Requests; import me.oneqxz.riseloader.utils.requests.Response; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream;
8,457
package me.oneqxz.riseloader.fxml.controllers.impl; public class ClientLaunchController extends Controller { Logger log = LogManager.getLogger("ClientLaunch"); Button cancel; Label status; ProgressBar mainProgress, subProgress; boolean aborted = false; private void stop() { aborted = true;
package me.oneqxz.riseloader.fxml.controllers.impl; public class ClientLaunchController extends Controller { Logger log = LogManager.getLogger("ClientLaunch"); Button cancel; Label status; ProgressBar mainProgress, subProgress; boolean aborted = false; private void stop() { aborted = true;
MainScene.removeChildren(root);
5
2023-11-01 01:40:52+00:00
12k
YufiriaMazenta/CrypticLib
common/src/main/java/crypticlib/BukkitPlugin.java
[ { "identifier": "AnnotationProcessor", "path": "common/src/main/java/crypticlib/annotation/AnnotationProcessor.java", "snippet": "public enum AnnotationProcessor {\n\n INSTANCE;\n\n private final Map<Class<?>, Object> singletonObjectMap;\n private final Map<Class<? extends Annotation>, BiConsum...
import crypticlib.annotation.AnnotationProcessor; import crypticlib.chat.LangConfigContainer; import crypticlib.chat.LangConfigHandler; import crypticlib.chat.MessageSender; import crypticlib.command.BukkitCommand; import crypticlib.command.CommandInfo; import crypticlib.command.CommandManager; import crypticlib.config.ConfigContainer; import crypticlib.config.ConfigHandler; import crypticlib.config.ConfigWrapper; import crypticlib.listener.BukkitListener; import crypticlib.perm.PermissionManager; import org.bukkit.Bukkit; import org.bukkit.command.TabExecutor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.event.Listener; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; import java.util.Map; import java.util.concurrent.ConcurrentHashMap;
7,348
package crypticlib; public abstract class BukkitPlugin extends JavaPlugin { protected final Map<String, ConfigContainer> configContainerMap = new ConcurrentHashMap<>();
package crypticlib; public abstract class BukkitPlugin extends JavaPlugin { protected final Map<String, ConfigContainer> configContainerMap = new ConcurrentHashMap<>();
protected final Map<String, LangConfigContainer> langConfigContainerMap = new ConcurrentHashMap<>();
1
2023-11-07 12:39:20+00:00
12k
Traben-0/resource_explorer
common/src/main/java/traben/resource_explorer/mixin/OptionsScreenMixin.java
[ { "identifier": "REConfig", "path": "common/src/main/java/traben/resource_explorer/REConfig.java", "snippet": "public class REConfig {\n\n private static REConfig instance;\n public boolean showResourcePackButton = true;\n public boolean logFullFileTree = false;\n public boolean addCauseToRe...
import net.minecraft.client.gui.DrawContext; import net.minecraft.client.gui.screen.ButtonTextures; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.option.OptionsScreen; import net.minecraft.client.gui.tooltip.Tooltip; import net.minecraft.client.gui.widget.GridWidget; import net.minecraft.client.gui.widget.TexturedButtonWidget; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; import traben.resource_explorer.REConfig; import traben.resource_explorer.explorer.REExplorer; import traben.resource_explorer.explorer.REExplorerScreen; import static traben.resource_explorer.ResourceExplorerClient.MOD_ID;
7,496
package traben.resource_explorer.mixin; @Mixin(OptionsScreen.class) public abstract class OptionsScreenMixin extends Screen { @SuppressWarnings("unused") protected OptionsScreenMixin(Text title) { super(title); } @Inject(method = "init", at = @At(value = "TAIL"), locals = LocalCapture.CAPTURE_FAILHARD) private void re$afterAdder(CallbackInfo ci, GridWidget gridWidget, GridWidget.Adder adder) { if (REConfig.getInstance().showResourcePackButton) { int x = gridWidget.getX() - 16; int y = gridWidget.getY() + 128; addDrawableChild(new TexturedButtonWidget( x, y, 16, 16,
package traben.resource_explorer.mixin; @Mixin(OptionsScreen.class) public abstract class OptionsScreenMixin extends Screen { @SuppressWarnings("unused") protected OptionsScreenMixin(Text title) { super(title); } @Inject(method = "init", at = @At(value = "TAIL"), locals = LocalCapture.CAPTURE_FAILHARD) private void re$afterAdder(CallbackInfo ci, GridWidget gridWidget, GridWidget.Adder adder) { if (REConfig.getInstance().showResourcePackButton) { int x = gridWidget.getX() - 16; int y = gridWidget.getY() + 128; addDrawableChild(new TexturedButtonWidget( x, y, 16, 16,
new ButtonTextures(REExplorer.ICON_FOLDER, REExplorer.ICON_FOLDER_OPEN),
1
2023-11-05 17:35:39+00:00
12k
txline0420/nacos-dm
config/src/main/java/com/alibaba/nacos/config/server/service/datasource/ExternalDataSourceProperties.java
[ { "identifier": "Preconditions", "path": "common/src/main/java/com/alibaba/nacos/common/utils/Preconditions.java", "snippet": "public class Preconditions {\n\n private Preconditions() {\n }\n\n /**\n * check precondition.\n * @param expression a boolean expression\n * @param errorMe...
import com.alibaba.nacos.common.utils.Preconditions; import com.alibaba.nacos.common.utils.StringUtils; import com.zaxxer.hikari.HikariDataSource; import org.apache.commons.collections.CollectionUtils; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.core.env.Environment; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static com.alibaba.nacos.common.utils.CollectionUtils.getOrDefault;
9,113
/* * Copyright 1999-2018 Alibaba Group Holding 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.alibaba.nacos.config.server.service.datasource; /** * Properties of external DataSource. * * @author Nacos */ public class ExternalDataSourceProperties { private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String TEST_QUERY = "SELECT 1"; private Integer num; private List<String> url = new ArrayList<>(); private List<String> user = new ArrayList<>(); private List<String> password = new ArrayList<>(); public void setNum(Integer num) { this.num = num; } public void setUrl(List<String> url) { this.url = url; } public void setUser(List<String> user) { this.user = user; } public void setPassword(List<String> password) { this.password = password; } private String jdbcDriverName; public String getJdbcDriverName() { return jdbcDriverName; } public void setJdbcDriverName(String jdbcDriverName) { this.jdbcDriverName = jdbcDriverName; } /** * Build serveral HikariDataSource. * * @param environment {@link Environment} * @param callback Callback function when constructing data source * @return List of {@link HikariDataSource} */ List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) { List<HikariDataSource> dataSources = new ArrayList<>(); Binder.get(environment).bind("db", Bindable.ofInstance(this)); Preconditions.checkArgument(Objects.nonNull(num), "db.num is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(user), "db.user or db.user.[index] is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(password), "db.password or db.password.[index] is null"); for (int index = 0; index < num; index++) { int currentSize = index + 1; Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index); DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment); if (StringUtils.isEmpty(poolProperties.getDataSource().getDriverClassName())) { System.out.println("==================================="); System.out.println("jdbcDriverName=" + jdbcDriverName); if (StringUtils.isNotEmpty(jdbcDriverName)) { poolProperties.setDriverClassName(jdbcDriverName); } else { poolProperties.setDriverClassName(JDBC_DRIVER_NAME); } System.out.println("==================================="); System.out.println("dataSources=" + dataSources); } poolProperties.setJdbcUrl(url.get(index).trim());
/* * Copyright 1999-2018 Alibaba Group Holding 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.alibaba.nacos.config.server.service.datasource; /** * Properties of external DataSource. * * @author Nacos */ public class ExternalDataSourceProperties { private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver"; private static final String TEST_QUERY = "SELECT 1"; private Integer num; private List<String> url = new ArrayList<>(); private List<String> user = new ArrayList<>(); private List<String> password = new ArrayList<>(); public void setNum(Integer num) { this.num = num; } public void setUrl(List<String> url) { this.url = url; } public void setUser(List<String> user) { this.user = user; } public void setPassword(List<String> password) { this.password = password; } private String jdbcDriverName; public String getJdbcDriverName() { return jdbcDriverName; } public void setJdbcDriverName(String jdbcDriverName) { this.jdbcDriverName = jdbcDriverName; } /** * Build serveral HikariDataSource. * * @param environment {@link Environment} * @param callback Callback function when constructing data source * @return List of {@link HikariDataSource} */ List<HikariDataSource> build(Environment environment, Callback<HikariDataSource> callback) { List<HikariDataSource> dataSources = new ArrayList<>(); Binder.get(environment).bind("db", Bindable.ofInstance(this)); Preconditions.checkArgument(Objects.nonNull(num), "db.num is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(user), "db.user or db.user.[index] is null"); Preconditions.checkArgument(CollectionUtils.isNotEmpty(password), "db.password or db.password.[index] is null"); for (int index = 0; index < num; index++) { int currentSize = index + 1; Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index); DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment); if (StringUtils.isEmpty(poolProperties.getDataSource().getDriverClassName())) { System.out.println("==================================="); System.out.println("jdbcDriverName=" + jdbcDriverName); if (StringUtils.isNotEmpty(jdbcDriverName)) { poolProperties.setDriverClassName(jdbcDriverName); } else { poolProperties.setDriverClassName(JDBC_DRIVER_NAME); } System.out.println("==================================="); System.out.println("dataSources=" + dataSources); } poolProperties.setJdbcUrl(url.get(index).trim());
poolProperties.setUsername(getOrDefault(user, index, user.get(0)).trim());
2
2023-11-02 01:34:09+00:00
12k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/attendce/AttendceController.java
[ { "identifier": "StringtoDate", "path": "src/main/java/cn/gson/oasys/common/StringtoDate.java", "snippet": "@Configuration\npublic class StringtoDate implements Converter<String, Date> {\n\n\t SimpleDateFormat sdf=new SimpleDateFormat();\n\t private List<String> patterns = new ArrayList<>();\n\t \...
import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.ibatis.annotations.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import ch.qos.logback.core.joran.action.IADataForComplexProperty; import ch.qos.logback.core.net.SyslogOutputStream; import cn.gson.oasys.common.StringtoDate; import cn.gson.oasys.model.dao.attendcedao.AttendceDao; import cn.gson.oasys.model.dao.attendcedao.AttendceService; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.dao.user.UserService; import cn.gson.oasys.model.entity.attendce.Attends; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User;
10,618
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired
package cn.gson.oasys.controller.attendce; @Controller @RequestMapping("/") public class AttendceController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired AttendceDao attenceDao; @Autowired AttendceService attendceService; @Autowired
UserDao uDao;
5
2023-11-03 02:08:22+00:00
12k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/actions/JarMergeAction.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.jarmanager.JarManager; import com.hypherionmc.jarrelocator.Relocation; import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.utils.FileTools; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.zip.Deflater; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.logger; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.utils.FileTools.*;
9,920
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.actions; /** * @author HypherionSA * The main logic class of the plugin. This class is responsible for * extracting, remapping, de-duplicating and finally merging the input jars */ @RequiredArgsConstructor(staticName = "of") public class JarMergeAction { // File Inputs @Setter private File forgeInput; @Setter private File fabricInput; @Setter private File quiltInput; private final Map<FusionerExtension.CustomConfiguration, File> customInputs; // Relocations @Setter private Map<String, String> forgeRelocations; @Setter private Map<String, String> fabricRelocations; @Setter private Map<String, String> quiltRelocations; // Mixins @Setter private List<String> forgeMixins; // Custom private Map<FusionerExtension.CustomConfiguration, Map<File, File>> customTemps; // Relocations private final List<String> ignoredPackages; private final Map<String, String> ignoredDuplicateRelocations = new HashMap<>(); private final Map<String, String> removeDuplicateRelocationResources = new HashMap<>(); private final List<Relocation> relocations = new ArrayList<>(); JarManager jarManager = JarManager.getInstance(); // Settings private final String group; private final File tempDir; private final String outJarName; /** * Start the merge process * @param skipIfExists - Should the task be cancelled if an existing merged jar is found * @return - The fully merged jar file * @throws IOException - Thrown when an IO Exception occurs */ public File mergeJars(boolean skipIfExists) throws IOException { jarManager.setCompressionLevel(Deflater.BEST_COMPRESSION); File outJar = new File(tempDir, outJarName); if (outJar.exists()) { if (skipIfExists) return outJar; outJar.delete(); } logger.lifecycle("Cleaning output Directory"); FileTools.createOrReCreate(tempDir); // Check if the required input files exists if (forgeInput == null && fabricInput == null && quiltInput == null && customInputs.isEmpty()) { throw new IllegalArgumentException("No input jars were provided."); }
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.actions; /** * @author HypherionSA * The main logic class of the plugin. This class is responsible for * extracting, remapping, de-duplicating and finally merging the input jars */ @RequiredArgsConstructor(staticName = "of") public class JarMergeAction { // File Inputs @Setter private File forgeInput; @Setter private File fabricInput; @Setter private File quiltInput; private final Map<FusionerExtension.CustomConfiguration, File> customInputs; // Relocations @Setter private Map<String, String> forgeRelocations; @Setter private Map<String, String> fabricRelocations; @Setter private Map<String, String> quiltRelocations; // Mixins @Setter private List<String> forgeMixins; // Custom private Map<FusionerExtension.CustomConfiguration, Map<File, File>> customTemps; // Relocations private final List<String> ignoredPackages; private final Map<String, String> ignoredDuplicateRelocations = new HashMap<>(); private final Map<String, String> removeDuplicateRelocationResources = new HashMap<>(); private final List<Relocation> relocations = new ArrayList<>(); JarManager jarManager = JarManager.getInstance(); // Settings private final String group; private final File tempDir; private final String outJarName; /** * Start the merge process * @param skipIfExists - Should the task be cancelled if an existing merged jar is found * @return - The fully merged jar file * @throws IOException - Thrown when an IO Exception occurs */ public File mergeJars(boolean skipIfExists) throws IOException { jarManager.setCompressionLevel(Deflater.BEST_COMPRESSION); File outJar = new File(tempDir, outJarName); if (outJar.exists()) { if (skipIfExists) return outJar; outJar.delete(); } logger.lifecycle("Cleaning output Directory"); FileTools.createOrReCreate(tempDir); // Check if the required input files exists if (forgeInput == null && fabricInput == null && quiltInput == null && customInputs.isEmpty()) { throw new IllegalArgumentException("No input jars were provided."); }
if (modFusionerExtension.getForgeConfiguration() != null && !FileTools.exists(forgeInput)) {
4
2023-11-03 23:19:08+00:00
12k
data-harness-cloud/data_harness-be
application-webadmin/src/main/java/supie/webadmin/app/model/ProjectDatasource.java
[ { "identifier": "SysDept", "path": "application-webadmin/src/main/java/supie/webadmin/upms/model/SysDept.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(value = \"sdt_sys_dept\")\npublic class SysDept extends BaseModel {\n\n /**\n * 测试字段。\n */\n private Long mark...
import com.baomidou.mybatisplus.annotation.*; import supie.webadmin.upms.model.SysDept; import supie.webadmin.upms.model.SysUser; import supie.webadmin.app.model.constant.DataSourceConnectStatus; import supie.common.core.util.MyCommonUtil; import supie.common.core.annotation.*; import supie.common.core.base.model.BaseModel; import supie.common.core.base.mapper.BaseModelMapper; import supie.webadmin.app.vo.ProjectDatasourceVo; import lombok.Data; import lombok.EqualsAndHashCode; import org.mapstruct.*; import org.mapstruct.factory.Mappers; import java.util.Map;
8,716
package supie.webadmin.app.model; /** * ProjectDatasource实体对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Data @EqualsAndHashCode(callSuper = true) @TableName(value = "sdt_project_datasource") public class ProjectDatasource extends BaseModel { /** * 租户号。 */ @TableId(value = "id") private Long id; /** * 数据所属人。 */ @UserFilterColumn private Long dataUserId; /** * 数据所属部门。 */ @DeptFilterColumn private Long dataDeptId; /** * 逻辑删除标记字段(1: 正常 -1: 已删除)。 */ @TableLogic private Integer isDelete; /** * 数据源名称。 */ private String datasourceName; /** * 数据源类型。 */ private String datasourceType; /** * 数据源显示名称。 */ private String datasourceShowName; /** * 数据源描述。 */ private String datasourceDescription; /** * 数据源连接信息存储为json字段。 */ private String datasourceContent; /** * 数据源图标。 */ private String datasourceIcon; /** * 数据源分组。 */ private String datasourceGroup; /** * 数据源连通性。 */ private Integer datasourceConnect; /** * 是否采集元数据。 */ private Integer isMetaCollect; /** * 所属项目ID */ private Long projectId; /** * updateTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String updateTimeStart; /** * updateTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String updateTimeEnd; /** * createTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String createTimeStart; /** * createTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String createTimeEnd; /** * datasource_name / datasource_show_name / datasource_description / datasource_content / datasource_group LIKE搜索字符串。 */ @TableField(exist = false) private String searchString; public void setSearchString(String searchString) { this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); } /** * id 的多对多关联表数据对象。 */ @TableField(exist = false) private ProjectDatasourceRelation projectDatasourceRelation; @RelationDict( masterIdField = "dataUserId", slaveModelClass = SysUser.class, slaveIdField = "userId", slaveNameField = "loginName") @TableField(exist = false) private Map<String, Object> dataUserIdDictMap; @RelationDict( masterIdField = "dataDeptId",
package supie.webadmin.app.model; /** * ProjectDatasource实体对象。 * * @author rm -rf .bug * @date 2020-11-12 */ @Data @EqualsAndHashCode(callSuper = true) @TableName(value = "sdt_project_datasource") public class ProjectDatasource extends BaseModel { /** * 租户号。 */ @TableId(value = "id") private Long id; /** * 数据所属人。 */ @UserFilterColumn private Long dataUserId; /** * 数据所属部门。 */ @DeptFilterColumn private Long dataDeptId; /** * 逻辑删除标记字段(1: 正常 -1: 已删除)。 */ @TableLogic private Integer isDelete; /** * 数据源名称。 */ private String datasourceName; /** * 数据源类型。 */ private String datasourceType; /** * 数据源显示名称。 */ private String datasourceShowName; /** * 数据源描述。 */ private String datasourceDescription; /** * 数据源连接信息存储为json字段。 */ private String datasourceContent; /** * 数据源图标。 */ private String datasourceIcon; /** * 数据源分组。 */ private String datasourceGroup; /** * 数据源连通性。 */ private Integer datasourceConnect; /** * 是否采集元数据。 */ private Integer isMetaCollect; /** * 所属项目ID */ private Long projectId; /** * updateTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String updateTimeStart; /** * updateTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String updateTimeEnd; /** * createTime 范围过滤起始值(>=)。 */ @TableField(exist = false) private String createTimeStart; /** * createTime 范围过滤结束值(<=)。 */ @TableField(exist = false) private String createTimeEnd; /** * datasource_name / datasource_show_name / datasource_description / datasource_content / datasource_group LIKE搜索字符串。 */ @TableField(exist = false) private String searchString; public void setSearchString(String searchString) { this.searchString = MyCommonUtil.replaceSqlWildcard(searchString); } /** * id 的多对多关联表数据对象。 */ @TableField(exist = false) private ProjectDatasourceRelation projectDatasourceRelation; @RelationDict( masterIdField = "dataUserId", slaveModelClass = SysUser.class, slaveIdField = "userId", slaveNameField = "loginName") @TableField(exist = false) private Map<String, Object> dataUserIdDictMap; @RelationDict( masterIdField = "dataDeptId",
slaveModelClass = SysDept.class,
0
2023-11-04 12:36:44+00:00
12k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Robot.java
[ { "identifier": "Vector", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OrbitUtils/Vector.java", "snippet": "public final class Vector {\n\n public float x;\n public float y;\n\n public Vector(final float x, final float y) {\n this.x = x;\n this.y = y;\n }\n\n ...
import com.acmerobotics.dashboard.FtcDashboard; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.dashboard.telemetry.TelemetryPacket; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DigitalChannel; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.OrbitUtils.Vector; import org.firstinspires.ftc.teamcode.Sensors.OrbitGyro; import org.firstinspires.ftc.teamcode.positionTracker.PoseStorage; import org.firstinspires.ftc.teamcode.robotData.GlobalData; import org.firstinspires.ftc.teamcode.robotSubSystems.OrbitLED; import org.firstinspires.ftc.teamcode.robotSubSystems.RobotState; import org.firstinspires.ftc.teamcode.robotSubSystems.SubSystemManager; import org.firstinspires.ftc.teamcode.robotSubSystems.climb.Climb; import org.firstinspires.ftc.teamcode.robotSubSystems.drivetrain.Drivetrain; import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.Elevator; import org.firstinspires.ftc.teamcode.robotSubSystems.fourbar.Fourbar; import org.firstinspires.ftc.teamcode.robotSubSystems.intake.Intake; import org.firstinspires.ftc.teamcode.robotSubSystems.outtake.Outtake; import org.firstinspires.ftc.teamcode.robotSubSystems.plane.Plane; import org.firstinspires.ftc.teamcode.robotSubSystems.plane.PlaneState;
7,529
package org.firstinspires.ftc.teamcode; //import org.firstinspires.ftc.teamcode.robotSubSystems.SubSystemManager; //import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.Elevator; @Config @TeleOp(name = "main") public class Robot extends LinearOpMode { public static DigitalChannel coneDistanceSensor; public static TelemetryPacket packet; @Override public void runOpMode() throws InterruptedException { FtcDashboard dashboard = FtcDashboard.getInstance(); packet = new TelemetryPacket(); // coneDistanceSensor = hardwareMap.get(DigitalChannel.class, "clawDistanceSensor"); // coneDistanceSensor.setMode(DigitalChannel.Mode.INPUT); ElapsedTime robotTime = new ElapsedTime(); robotTime.reset(); Drivetrain.init(hardwareMap); OrbitGyro.init(hardwareMap); Elevator.init(hardwareMap); Outtake.init(hardwareMap); Intake.init(hardwareMap); Fourbar.init(hardwareMap); Climb.init(hardwareMap); Plane.init(hardwareMap); OrbitGyro.resetGyroStartTeleop((float) Math.toDegrees(PoseStorage.currentPose.getHeading())); telemetry.update(); telemetry.addData("gyro", Math.toDegrees(PoseStorage.currentPose.getHeading())); telemetry.addData("lastAngle", OrbitGyro.lastAngle); telemetry.update();
package org.firstinspires.ftc.teamcode; //import org.firstinspires.ftc.teamcode.robotSubSystems.SubSystemManager; //import org.firstinspires.ftc.teamcode.robotSubSystems.elevator.Elevator; @Config @TeleOp(name = "main") public class Robot extends LinearOpMode { public static DigitalChannel coneDistanceSensor; public static TelemetryPacket packet; @Override public void runOpMode() throws InterruptedException { FtcDashboard dashboard = FtcDashboard.getInstance(); packet = new TelemetryPacket(); // coneDistanceSensor = hardwareMap.get(DigitalChannel.class, "clawDistanceSensor"); // coneDistanceSensor.setMode(DigitalChannel.Mode.INPUT); ElapsedTime robotTime = new ElapsedTime(); robotTime.reset(); Drivetrain.init(hardwareMap); OrbitGyro.init(hardwareMap); Elevator.init(hardwareMap); Outtake.init(hardwareMap); Intake.init(hardwareMap); Fourbar.init(hardwareMap); Climb.init(hardwareMap); Plane.init(hardwareMap); OrbitGyro.resetGyroStartTeleop((float) Math.toDegrees(PoseStorage.currentPose.getHeading())); telemetry.update(); telemetry.addData("gyro", Math.toDegrees(PoseStorage.currentPose.getHeading())); telemetry.addData("lastAngle", OrbitGyro.lastAngle); telemetry.update();
GlobalData.inAutonomous = false;
3
2023-11-03 13:32:48+00:00
12k
beminder/BeautyMinder
java/src/test/java/app/beautyminder/service/UserServiceTest.java
[ { "identifier": "PasswordResetToken", "path": "java/src/main/java/app/beautyminder/domain/PasswordResetToken.java", "snippet": "@Document(collection = \"password_tokens\")\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\npublic class PasswordResetToken {\n\n @Id\n private String id;\n\n @Crea...
import app.beautyminder.domain.PasswordResetToken; import app.beautyminder.domain.User; import app.beautyminder.repository.PasswordResetTokenRepository; import app.beautyminder.repository.RefreshTokenRepository; import app.beautyminder.repository.TodoRepository; import app.beautyminder.repository.UserRepository; import app.beautyminder.service.auth.EmailService; import app.beautyminder.service.auth.TokenService; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticExpiryService; import app.beautyminder.service.review.ReviewService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.server.ResponseStatusException; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.*;
10,540
package app.beautyminder.service; @Slf4j @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private UserRepository userRepository; @Mock private TodoRepository todoRepository; @Mock private RefreshTokenRepository refreshTokenRepository; @Mock private PasswordResetTokenRepository passwordResetTokenRepository; @Mock private EmailService emailService; @Mock private TokenService tokenService; @Mock private ReviewService reviewService; @Mock private CosmeticExpiryService expiryService; @Mock private FileStorageService fileStorageService; @Mock private BCryptPasswordEncoder bCryptPasswordEncoder; @InjectMocks private UserService userService; @BeforeEach public void setup() { userRepository = mock(UserRepository.class); todoRepository = mock(TodoRepository.class); refreshTokenRepository = mock(RefreshTokenRepository.class); passwordResetTokenRepository = mock(PasswordResetTokenRepository.class); emailService = mock(EmailService.class); tokenService = mock(TokenService.class); reviewService = mock(ReviewService.class); expiryService = mock(CosmeticExpiryService.class); fileStorageService = mock(FileStorageService.class); bCryptPasswordEncoder = mock(BCryptPasswordEncoder.class); userService = new UserService( userRepository, todoRepository, refreshTokenRepository, passwordResetTokenRepository, emailService, tokenService , reviewService, expiryService, fileStorageService, bCryptPasswordEncoder); } @Test public void testFindByNickname_Found() { User mockUser = User.builder().nickname("nickname").build(); when(userRepository.findByNickname("nickname")).thenReturn(Optional.of(mockUser)); User result = userService.findByNickname("nickname"); assertEquals(mockUser, result); } @Test public void testFindByNickname_NotFound() { when(userRepository.findByNickname("nickname")).thenReturn(Optional.empty()); assertThrows(IllegalArgumentException.class, () -> userService.findByNickname("nickname")); } @Test public void testFindUsersWithProfileImage() { User mockUser = User.builder().nickname("nickname").build(); List<User> mockUsers = Collections.singletonList(mockUser); when(userRepository.findByProfileImageIsNotNull()).thenReturn(mockUsers); List<User> result = userService.findUsersWithProfileImage(); assertEquals(mockUsers, result); } @Test public void testResetPassword_ValidToken() {
package app.beautyminder.service; @Slf4j @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private UserRepository userRepository; @Mock private TodoRepository todoRepository; @Mock private RefreshTokenRepository refreshTokenRepository; @Mock private PasswordResetTokenRepository passwordResetTokenRepository; @Mock private EmailService emailService; @Mock private TokenService tokenService; @Mock private ReviewService reviewService; @Mock private CosmeticExpiryService expiryService; @Mock private FileStorageService fileStorageService; @Mock private BCryptPasswordEncoder bCryptPasswordEncoder; @InjectMocks private UserService userService; @BeforeEach public void setup() { userRepository = mock(UserRepository.class); todoRepository = mock(TodoRepository.class); refreshTokenRepository = mock(RefreshTokenRepository.class); passwordResetTokenRepository = mock(PasswordResetTokenRepository.class); emailService = mock(EmailService.class); tokenService = mock(TokenService.class); reviewService = mock(ReviewService.class); expiryService = mock(CosmeticExpiryService.class); fileStorageService = mock(FileStorageService.class); bCryptPasswordEncoder = mock(BCryptPasswordEncoder.class); userService = new UserService( userRepository, todoRepository, refreshTokenRepository, passwordResetTokenRepository, emailService, tokenService , reviewService, expiryService, fileStorageService, bCryptPasswordEncoder); } @Test public void testFindByNickname_Found() { User mockUser = User.builder().nickname("nickname").build(); when(userRepository.findByNickname("nickname")).thenReturn(Optional.of(mockUser)); User result = userService.findByNickname("nickname"); assertEquals(mockUser, result); } @Test public void testFindByNickname_NotFound() { when(userRepository.findByNickname("nickname")).thenReturn(Optional.empty()); assertThrows(IllegalArgumentException.class, () -> userService.findByNickname("nickname")); } @Test public void testFindUsersWithProfileImage() { User mockUser = User.builder().nickname("nickname").build(); List<User> mockUsers = Collections.singletonList(mockUser); when(userRepository.findByProfileImageIsNotNull()).thenReturn(mockUsers); List<User> result = userService.findUsersWithProfileImage(); assertEquals(mockUsers, result); } @Test public void testResetPassword_ValidToken() {
PasswordResetToken resetToken = PasswordResetToken.builder().expiryDate(LocalDateTime.now().plusHours(1)).email("user@example.com").build();
0
2023-11-01 12:37:16+00:00
12k
FallenDeity/GameEngine2DJava
src/main/java/engine/scenes/Scene.java
[ { "identifier": "Sprite", "path": "src/main/java/engine/components/sprites/Sprite.java", "snippet": "public class Sprite {\n\tprivate Texture texture = null;\n\tprivate float width = 0, height = 0;\n\tprivate Vector2f[] texCoords =\n\t\t\tnew Vector2f[]{\n\t\t\t\t\tnew Vector2f(1, 1), new Vector2f(1, 0)...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import engine.components.*; import engine.components.sprites.Sprite; import engine.physics2d.Physics2D; import engine.renderer.Camera; import engine.renderer.Renderer; import engine.ruby.Window; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.ComponentDeserializer; import engine.util.GameObjectDeserializer; import org.joml.Vector2f; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.logging.Logger; import java.util.stream.Stream;
7,957
package engine.scenes; public abstract class Scene { protected final Renderer renderer = new Renderer(); protected final List<GameObject> gameObjects = new ArrayList<>(); protected final Physics2D physics2D; protected final Camera camera; private final List<GameObject> pendingGameObjects = new ArrayList<>(); private final String storePath = "%s/scenes".formatted(CONSTANTS.RESOURCE_PATH.getValue()); private boolean isRunning = false; protected Scene() { load(); for (GameObject g : gameObjects) { if (g.getComponent(SpriteRenderer.class) != null) { Sprite sp = g.getComponent(SpriteRenderer.class).getSprite(); if (sp.getTexture() != null) { sp.setTexture(AssetPool.getTexture(sp.getTexture().getFilePath())); } } if (g.getComponent(StateMachine.class) != null) { StateMachine sm = g.getComponent(StateMachine.class); sm.refresh(); } } camera = new Camera(new Vector2f()); physics2D = new Physics2D(); } public static GameObject createGameObject(String name) { GameObject gameObject = new GameObject(name); gameObject.addComponent(new Transform()); gameObject.transform = gameObject.getComponent(Transform.class); return gameObject; } public final void start() { if (isRunning) return; isRunning = true; for (GameObject gameObject : gameObjects) { gameObject.start(); renderer.add(gameObject); physics2D.add(gameObject); } } public final void addGameObjectToScene(GameObject gameObject) { if (isRunning) { pendingGameObjects.add(gameObject); } else { gameObjects.add(gameObject); } } public final void destroy() { gameObjects.forEach(GameObject::destroy);
package engine.scenes; public abstract class Scene { protected final Renderer renderer = new Renderer(); protected final List<GameObject> gameObjects = new ArrayList<>(); protected final Physics2D physics2D; protected final Camera camera; private final List<GameObject> pendingGameObjects = new ArrayList<>(); private final String storePath = "%s/scenes".formatted(CONSTANTS.RESOURCE_PATH.getValue()); private boolean isRunning = false; protected Scene() { load(); for (GameObject g : gameObjects) { if (g.getComponent(SpriteRenderer.class) != null) { Sprite sp = g.getComponent(SpriteRenderer.class).getSprite(); if (sp.getTexture() != null) { sp.setTexture(AssetPool.getTexture(sp.getTexture().getFilePath())); } } if (g.getComponent(StateMachine.class) != null) { StateMachine sm = g.getComponent(StateMachine.class); sm.refresh(); } } camera = new Camera(new Vector2f()); physics2D = new Physics2D(); } public static GameObject createGameObject(String name) { GameObject gameObject = new GameObject(name); gameObject.addComponent(new Transform()); gameObject.transform = gameObject.getComponent(Transform.class); return gameObject; } public final void start() { if (isRunning) return; isRunning = true; for (GameObject gameObject : gameObjects) { gameObject.start(); renderer.add(gameObject); physics2D.add(gameObject); } } public final void addGameObjectToScene(GameObject gameObject) { if (isRunning) { pendingGameObjects.add(gameObject); } else { gameObjects.add(gameObject); } } public final void destroy() { gameObjects.forEach(GameObject::destroy);
} private String defaultScene = Window.getScene() == null ? "default" : Window.getScene().getDefaultScene();
4
2023-11-04 13:19:21+00:00
12k
RezaGooner/University-food-ordering
Frames/Profile/UpdatePassword.java
[ { "identifier": "StyledButtonUI", "path": "Classes/Theme/StyledButtonUI.java", "snippet": "public class StyledButtonUI extends BasicButtonUI {\r\n\r\n @Override\r\n public void installUI (JComponent c) {\r\n super.installUI(c);\r\n AbstractButton button = (AbstractButton) c;\r\n ...
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Classes.Theme.SoundEffect.successSound; import static Classes.Pathes.FilesPath.UserPassPath; import Classes.Theme.StyledButtonUI; import Frames.LoginFrame;
7,203
panel.setBackground(ForgotPassword.colorBackground); panel.add(newPasswordLabel); panel.add(newPasswordField); panel.add(confirmPasswordLabel); panel.add(confirmPasswordField); panel.add(changePasswordButton); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(ForgotPassword.colorButton); setJMenuBar(menuBar); JMenuItem backItem = new JMenuItem("بازگشت"); backItem.setBackground(ForgotPassword.colorButton); menuBar.add(backItem); backItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); new LoginFrame(); } } }); JMenuItem exitItem = new JMenuItem("خروج"); exitItem.setBackground(ForgotPassword.colorButton); menuBar.add(exitItem); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا خارج می شوید؟", "خروج", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); } } }); add(panel); setVisible(true); changePasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { id = Id; String newPassword = new String(newPasswordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); if (id.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) { try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "لطفاً تمامی فیلدها را پر کنید.", "خطا", JOptionPane.ERROR_MESSAGE); return; } else if (! isValidPassword(newPassword)){ try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "رمز عبور باید حاوی اعداد و کاراکترها ، حروف بزرگ و کوجک انگلیسی باشد.", "خطا", JOptionPane.ERROR_MESSAGE); return; } if (!newPassword.equals(confirmPassword)) { try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "رمز عبور جدید و تکرار آن با هم مطابقت ندارند.", "خطا", JOptionPane.ERROR_MESSAGE); return; } try (BufferedReader reader = new BufferedReader(new FileReader(UserPassPath))) { String line; boolean idExists = false; StringBuilder fileContent = new StringBuilder(); while ((line = reader.readLine()) != null) { String[] parts = line.split(","); String storedId = parts[0]; String name = parts[2]; String lastName = parts[3]; String gender = parts[4]; String number = parts[5]; String organization = parts[6]; if (id.equals(storedId)) { idExists = true; line = id + "," + newPassword + "," + name + "," + lastName + "," + gender + "," + number + "," + organization; } fileContent.append(line).append(System.lineSeparator()); } if (!idExists) { try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "شناسه‌ی وارد شده در سیستم موجود نیست.", "خطا",JOptionPane.ERROR_MESSAGE); return; } try (BufferedWriter writer = new BufferedWriter(new FileWriter(UserPassPath))) { writer.write(fileContent.toString()); } try {
package Frames.Profile; /* این کد برای این است که به کاربران اجازه دهد تا رمز عبور خود را تغییر دهند. این برنامه با ساخت یک پنجره شروع می‌شود. در این پنجره دو فیلد رمز عبور برای رمز عبور جدید و تایید آن و یک دکمه "تغییر رمز عبور" وجود دارد. این کلاس یک متد به نام `isValidPassword` نیز تعریف می‌کند که یک رشته را به عنوان ورودی می‌گیرد و بررسی می‌کند که آیا آن برای یک رمز عبور معتبر کافی است یا نه. شرایطی که برای یک رمز عبور معتبر تعیین شده‌اند این است که رمز عبور حداقل باید 8 کاراکتر باشد، شامل حداقل یک عدد، یک حرف کوچک، یک حرف بزرگ و یک کاراکتر خاص (مانند !، @، # و غیره) باشد. این متد در صورتی که رمز عبور تمامی شرایط را برآورده کند، `true` و در غیر این صورت `false` برمی‌گرداند. سازنده‌ی کلاس یک رشته به نام `Id` را به عنوان ورودی دریافت می‌کند که شناسه‌ی کاربر را نشان می‌دهد. هنگامی که کاربر روی دکمه "تغییر رمز عبور" کلیک می‌کند، سازنده مقادیر وارد شده در فیلدهای رمز عبور را دریافت می‌کند، با استفاده از متد `isValidPassword` اعتبارسنجی می‌کند و آن‌ها را با یکدیگر مقایسه می‌کند تا مطمئن شود که هر دوی آن‌ها یکسان هستند. اگر مقادیر معتبر و مطابق باشند، سازنده یک فایل حاوی اطلاعات کاربر را خوانده و رمز عبور کاربر با شناسه‌ی وارد شده راتغییر میدهد. سپس یک پیام برای اطلاع کاربر از موفقیت تغییر رمز عبور نمایش داده می‌شود و پنجره فعلی بسته می‌شود. حال کاربر می‌تواند با رمز عبور جدید وارد شود. این کد همچنین یک نوار منو با دو آیتم "بازگشت" و "خروج" ایجاد می‌کند. با کلیک بر روی آیتم "بازگشت"، کاربر با یک پیام تأییدی تأیید مواجه می‌شود تا تأیید کند که آیا می‌خواهد از پنجره‌ی فعلی خارج شده و به پنجره‌ی قبلی بازگردد یا نه. همچنین با کلیک بر روی آیتم "خروج"، کاربر با یک پیام تأیید مواجه می‌شود تا تأیید کند که آیا می‌خواهد از برنامه خارج شود یا نه. ````````````````````````````````````````````````````` It represents a graphical user interface for updating a user's password. Here is a breakdown of the code: 1. The class imports various classes and libraries for GUI components, event handling, file operations, and sound effects. 2. The class extends the `JFrame` class. 3. The class defines instance variables, including a string variable for storing the user's ID, password fields for entering the new and confirmed passwords, and a regular expression method for validating passwords. 4. The constructor of the class initializes the frame, sets its properties (title, size, icon, etc.), and creates the necessary GUI components (labels, password fields, button, etc.) using Swing. 5. The constructor sets up the menu bar, which contains "Back" and "Exit" items. 6. The constructor adds action listeners to the "Back" and "Exit" items. If the user chooses to go back, a confirmation dialog is shown, and if confirmed, the current frame is disposed, and a new `LoginFrame` is created. If the user chooses to exit, a confirmation dialog is shown, and if confirmed, the current frame is disposed. 7. The constructor adds the GUI components to a panel and sets the panel as the content pane of the frame. 8. The constructor sets the frame as visible and non-resizable. 9. The `actionPerformed` method is implemented from the `ActionListener` interface and is called when the change password button is clicked. 10. The `actionPerformed` method retrieves the values entered in the password fields, validates the input, and performs the necessary operations. 11. If any of the fields are empty, an error sound effect is played, an error message dialog is shown, and the method returns. 12. If the new password does not meet the specified criteria (numbers, lowercase and uppercase letters, special characters, minimum length), an error sound effect is played, an error message dialog is shown, and the method returns. 13. If the new password and the confirmed password do not match, an error sound effect is played, an error message dialog is shown, and the method returns. 14. The method reads the user password file (`UserPassPath`) and searches for a matching user ID. 15. If a match is found, the user's password is updated in the file, a success sound effect is played, a success message dialog is shown, the current frame is disposed, and a new `LoginFrame` is created. 16. If the user ID is not found, an error sound effect is played, an error message dialog is shown, and the method returns. 17. If there is an exception during file operations, an error sound effect is played, an error message dialog is shown, and the method returns. Overall, this code provides a GUI for updating a user's password, validates user input, searches for a match in a password file, and handles success and error scenarios accordingly. */ public class UpdatePassword extends JFrame { private String id ; private final JPasswordField newPasswordField; private final JPasswordField confirmPasswordField; public static boolean isValidPassword(String str) { return str.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[-+|!@#%^&*()-_=/.])(?=\\S+$).{8,}$"); } public UpdatePassword(String Id) { setTitle("تغییر رمز عبور"); setSize(400, 150); setIconImage(icon.getImage()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setResizable(false); JLabel newPasswordLabel = new JLabel(": رمز عبورجدید"); newPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER); newPasswordField = new JPasswordField(10); JLabel confirmPasswordLabel = new JLabel(": تکرار رمز عبور جدید"); confirmPasswordLabel.setHorizontalAlignment(SwingConstants.CENTER); confirmPasswordField = new JPasswordField(10); JButton changePasswordButton = new JButton("تغییر رمز عبور"); changePasswordButton.setUI(new StyledButtonUI()); changePasswordButton.setBackground(ForgotPassword.colorButton); JPanel panel = new JPanel(new GridLayout(3, 1)); panel.setBackground(ForgotPassword.colorBackground); panel.add(newPasswordLabel); panel.add(newPasswordField); panel.add(confirmPasswordLabel); panel.add(confirmPasswordField); panel.add(changePasswordButton); JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(ForgotPassword.colorButton); setJMenuBar(menuBar); JMenuItem backItem = new JMenuItem("بازگشت"); backItem.setBackground(ForgotPassword.colorButton); menuBar.add(backItem); backItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا از ادامه مراحل انصراف می دهید؟", "بازگشت به صفحه اصلی", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); new LoginFrame(); } } }); JMenuItem exitItem = new JMenuItem("خروج"); exitItem.setBackground(ForgotPassword.colorButton); menuBar.add(exitItem); exitItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Object[] options = {"خیر", "بله"}; int exitResult = JOptionPane.showOptionDialog(null, "آیا خارج می شوید؟", "خروج", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (exitResult == JOptionPane.NO_OPTION) { dispose(); } } }); add(panel); setVisible(true); changePasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { id = Id; String newPassword = new String(newPasswordField.getPassword()); String confirmPassword = new String(confirmPasswordField.getPassword()); if (id.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) { try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "لطفاً تمامی فیلدها را پر کنید.", "خطا", JOptionPane.ERROR_MESSAGE); return; } else if (! isValidPassword(newPassword)){ try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "رمز عبور باید حاوی اعداد و کاراکترها ، حروف بزرگ و کوجک انگلیسی باشد.", "خطا", JOptionPane.ERROR_MESSAGE); return; } if (!newPassword.equals(confirmPassword)) { try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "رمز عبور جدید و تکرار آن با هم مطابقت ندارند.", "خطا", JOptionPane.ERROR_MESSAGE); return; } try (BufferedReader reader = new BufferedReader(new FileReader(UserPassPath))) { String line; boolean idExists = false; StringBuilder fileContent = new StringBuilder(); while ((line = reader.readLine()) != null) { String[] parts = line.split(","); String storedId = parts[0]; String name = parts[2]; String lastName = parts[3]; String gender = parts[4]; String number = parts[5]; String organization = parts[6]; if (id.equals(storedId)) { idExists = true; line = id + "," + newPassword + "," + name + "," + lastName + "," + gender + "," + number + "," + organization; } fileContent.append(line).append(System.lineSeparator()); } if (!idExists) { try { errorSound(); } catch (Exception ex) { } JOptionPane.showMessageDialog(null, "شناسه‌ی وارد شده در سیستم موجود نیست.", "خطا",JOptionPane.ERROR_MESSAGE); return; } try (BufferedWriter writer = new BufferedWriter(new FileWriter(UserPassPath))) { writer.write(fileContent.toString()); } try {
successSound();
4
2023-11-03 08:35:22+00:00
12k
af19git5/EasyImage
src/main/java/io/github/af19git5/builder/ImageBuilder.java
[ { "identifier": "Image", "path": "src/main/java/io/github/af19git5/entity/Image.java", "snippet": "@Getter\npublic class Image extends Item {\n\n private final BufferedImage bufferedImage;\n\n private int overrideWidth = -1;\n\n private int overrideHeight = -1;\n\n /**\n * @param x 放置x軸位...
import io.github.af19git5.entity.Image; import io.github.af19git5.entity.Item; import io.github.af19git5.entity.Text; import io.github.af19git5.exception.ImageException; import io.github.af19git5.type.OutputType; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Base64; import java.util.List; import javax.imageio.ImageIO;
8,039
package io.github.af19git5.builder; /** * 圖片建構器 * * @author Jimmy Kang */ public class ImageBuilder { private final int width; private final int height; private final Color backgroundColor; private final List<Item> itemList = new ArrayList<>(); /** * @param width 圖片寬 * @param height 圖片高 */ public ImageBuilder(int width, int height) { this.width = width; this.height = height; this.backgroundColor = Color.WHITE; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColor 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, Color backgroundColor) { this.width = width; this.height = height; this.backgroundColor = backgroundColor; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColorHex 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, String backgroundColorHex) { this.width = width; this.height = height; this.backgroundColor = Color.decode(backgroundColorHex); } /** * 加入文字 * * @param text 文字物件 */
package io.github.af19git5.builder; /** * 圖片建構器 * * @author Jimmy Kang */ public class ImageBuilder { private final int width; private final int height; private final Color backgroundColor; private final List<Item> itemList = new ArrayList<>(); /** * @param width 圖片寬 * @param height 圖片高 */ public ImageBuilder(int width, int height) { this.width = width; this.height = height; this.backgroundColor = Color.WHITE; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColor 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, Color backgroundColor) { this.width = width; this.height = height; this.backgroundColor = backgroundColor; } /** * @param width 圖片寬 * @param height 圖片高 * @param backgroundColorHex 圖片背景色(16進位色碼) */ public ImageBuilder(int width, int height, String backgroundColorHex) { this.width = width; this.height = height; this.backgroundColor = Color.decode(backgroundColorHex); } /** * 加入文字 * * @param text 文字物件 */
public ImageBuilder add(Text text) {
2
2023-11-01 03:55:06+00:00
12k
schadfield/shogi-explorer
src/main/java/com/chadfield/shogiexplorer/utils/NotationUtils.java
[ { "identifier": "KifParser", "path": "src/main/java/com/chadfield/shogiexplorer/main/KifParser.java", "snippet": "public class KifParser {\n\n private static final String DATE = \"開始日時:\";\n private static final String PLACE = \"場所:\";\n private static final String TIME_LIMIT = \"持ち時間:\";\n ...
import com.chadfield.shogiexplorer.main.KifParser; import com.chadfield.shogiexplorer.objects.Board; import com.chadfield.shogiexplorer.objects.Coordinate; import com.chadfield.shogiexplorer.objects.Koma; import java.util.ArrayList; import java.util.List; import java.util.Objects;
8,200
getSourcesForKoma(board, destination, new int[]{1, 0, -1, 1, -1, 0}, new int[]{1, 1, 1, 0, 0, -1}, komaType); case GKI, GTO, GNK, GNY, GNG -> getSourcesForKoma(board, destination, new int[]{1, 0, -1, 1, -1, 0}, new int[]{-1, -1, -1, 0, 0, 1}, komaType); case SKY -> { resultCoordinate = getSourceOnVector(board, destination, 0, 1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } yield result; } case GKY -> { resultCoordinate = getSourceOnVector(board, destination, 0, -1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } yield result; } case SKA, GKA -> getSourcesOnDiagonalVectors(board, destination, komaType); case SHI, GHI -> getSourcesOnHorizontalVectors(board, destination, komaType); case SUM, GUM -> { result = getSourcesForKoma(board, destination, new int[]{-1, 1, 0, 0}, new int[]{0, 0, -1, 1}, komaType); for (Coordinate thisCoordinate : getSourcesOnDiagonalVectors(board, destination, komaType)) { result.add(thisCoordinate); } yield result; } case SRY, GRY -> { result = getSourcesForKoma(board, destination, new int[]{-1, 1, 1, -1}, new int[]{-1, -1, 1, 1}, komaType); for (Coordinate thisCoordinate : getSourcesOnHorizontalVectors(board, destination, komaType)) { result.add(thisCoordinate); } yield result; } default -> result; }; } public static Coordinate getSourceCoordinate(String move) { Coordinate result = new Coordinate(); result.setX(Integer.parseInt(move.substring(move.indexOf("(") + 1, move.indexOf("(") + 2))); result.setY(Integer.parseInt(move.substring(move.indexOf("(") + 1, move.indexOf(")"))) - result.getX() * 10); return result; } private static List<Coordinate> getSourcesOnHorizontalVectors(Board board, Coordinate destination, Koma.Type komaType) { List<Coordinate> result = new ArrayList<>(); Coordinate resultCoordinate; resultCoordinate = getSourceOnVector(board, destination, -1, 0, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 1, 0, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 0, -1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 0, 1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } return result; } private static String bottomThree(Coordinate sourceCoordinate, Coordinate destinationCoordinate, List<Coordinate> sourceList, boolean isSente) { if (numWithSameY(sourceCoordinate, sourceList) == 1) { // Simple up case. return UPWARD; } else if (onLeft(sourceCoordinate, destinationCoordinate, isSente)) { // Below-left. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_LEFT; } else { return FROM_LEFT + UPWARD; } } else if (onRight(sourceCoordinate, destinationCoordinate, isSente)) { // Below-right. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_RIGHT; } else { return FROM_RIGHT + UPWARD; } } else { // Directly below destination. return VERTICAL; } } private static boolean haveSameY(Coordinate first, Coordinate second) { return Objects.equals(first.getY(), second.getY()); } static boolean onLeft(Coordinate firstCoordinate, Coordinate secondCoordinate, boolean isSente) { if (isSente) { return firstCoordinate.getX() > secondCoordinate.getX(); } else { return firstCoordinate.getX() < secondCoordinate.getX(); } } private static int numWithSameX(Coordinate coordinate, List<Coordinate> coordinateList) { int count = 0; for (Coordinate thisCoordinate : coordinateList) { if (haveSameX(coordinate, thisCoordinate)) { count++; } } return count; } public static List<Coordinate> getSourcesForKoma(Board board, Coordinate destination, int[] offsetX, int[] offsetY, Koma.Type komaType) { List<Coordinate> result = new ArrayList<>(); for (int k = 0; k < offsetX.length; k++) { Coordinate testCoordinate = new Coordinate(destination.getX() + offsetX[k], destination.getY() + offsetY[k]); if (NotationUtils.onBoard(testCoordinate)) {
/* Copyright © 2021, 2022 Stephen R Chadfield. This file is part of Shogi Explorer. Shogi Explorer 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. Shogi Explorer 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 Shogi Explorer. If not, see <https://www.gnu.org/licenses/>. */ package com.chadfield.shogiexplorer.utils; public class NotationUtils { public static final String PROMOTED = "成"; public static final String RESIGNS = "投了"; public static final String LOSING = "切れ負け"; public static final String SUSPENDED = "中断"; public static final String MADE = "まで"; public static final String DROPPED = "打"; public static final String DOWNWARD = "引"; public static final String HORIZONTALLY = "寄"; public static final String UPWARD = "上"; public static final String FROM_RIGHT = "右"; public static final String FROM_LEFT = "左"; public static final String VERTICAL = "直"; public static final String UPWARD_UD = "行"; public static final String ICHI = "一"; public static final String NI = "二"; public static final String SAN = "三"; public static final String SHI = "四"; public static final String GO = "五"; public static final String ROKU = "六"; public static final String NANA = "七"; public static final String HACHI = "八"; public static final String KYUU = "九"; public static final String SAME = "同"; private static boolean onBoard(Coordinate coordinate) { return coordinate.getX() > 0 && coordinate.getX() < 10 && coordinate.getY() > 0 && coordinate.getY() < 10; } private static Coordinate getSourceOnVector(Board board, Coordinate destination, int deltaX, int deltaY, Koma.Type komaType) { Coordinate testCoordinate = new Coordinate(destination.getX() + deltaX, destination.getY() + deltaY); while (true) { if (!onBoard(testCoordinate)) { return null; } Koma koma = board.getMasu()[9 - testCoordinate.getX()][testCoordinate.getY() - 1]; if (koma != null) { if (koma.getType() == komaType) { return testCoordinate; } else { return null; } } testCoordinate.setX(testCoordinate.getX() + deltaX); testCoordinate.setY(testCoordinate.getY() + deltaY); } } private static int numWithSameY(Coordinate coordinate, List<Coordinate> coordinateList) { int count = 0; for (Coordinate thisCoordinate : coordinateList) { if (haveSameY(coordinate, thisCoordinate)) { count++; } } return count; } static boolean onRight(Coordinate firstCoordinate, Coordinate secondCoordinate, boolean isSente) { if (isSente) { return firstCoordinate.getX() < secondCoordinate.getX(); } else { return firstCoordinate.getX() > secondCoordinate.getX(); } } static boolean isAbove(Coordinate firstCoordinate, Coordinate secondCoordinate, boolean isSente) { if (isSente) { return firstCoordinate.getY() < secondCoordinate.getY(); } else { return firstCoordinate.getY() > secondCoordinate.getY(); } } private static String disXHI(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { boolean isSente = komaType == Koma.Type.SHI; List<Coordinate> sourceList = getPossibleSources(board, destinationCoordinate, komaType); if (sourceList.size() > 1) { // There is ambiguity. if (isAbove(sourceCoordinate, destinationCoordinate, isSente)) { // The source is above the destination. return DOWNWARD; } else if (isBelow(sourceCoordinate, destinationCoordinate, isSente)) { // The source is below the destination. return UPWARD; } else { if (numWithSameY(sourceCoordinate, sourceList) > 1) { if (onLeft(sourceCoordinate, destinationCoordinate, isSente)) { // The source is left of the destination. return FROM_LEFT; } else { return FROM_RIGHT; } } else { return HORIZONTALLY; } } } return ""; } private static String disXGI(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { boolean isSente = komaType == Koma.Type.SGI; List<Coordinate> sourceList = getPossibleSources(board, destinationCoordinate, komaType); if (sourceList.size() > 1) { // There is ambiguity. if (isAbove(sourceCoordinate, destinationCoordinate, isSente)) { // The source is one of two locations above the destination. if (numWithSameY(sourceCoordinate, sourceList) == 1) { // Simple down case. return DOWNWARD; } else if (onLeft(sourceCoordinate, destinationCoordinate, isSente)) { // Above-left. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_LEFT; } else { return FROM_LEFT + DOWNWARD; } } else { // Above-right. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_RIGHT; } else { return FROM_RIGHT + DOWNWARD; } } } else { // The source is one of three locations below the destination. return bottomThree(sourceCoordinate, destinationCoordinate, sourceList, isSente); } } return ""; } private static String disXKXI(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { boolean isSente = komaType == Koma.Type.SKI || komaType == Koma.Type.STO || komaType == Koma.Type.SNK || komaType == Koma.Type.SNY || komaType == Koma.Type.SNG; List<Coordinate> sourceList = getPossibleSources(board, destinationCoordinate, komaType); if (sourceList.size() > 1) { // There is ambiguity. if (isAbove(sourceCoordinate, destinationCoordinate, isSente)) { // The source is in the single location above the destination. return DOWNWARD; } else if (Objects.equals(sourceCoordinate.getY(), destinationCoordinate.getY())) { // The source is next to the destination. if (numWithSameY(sourceCoordinate, sourceList) == 1) { // Simple horizontal case. return HORIZONTALLY; } else if (onLeft(sourceCoordinate, destinationCoordinate, isSente)) { // Above-left. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_LEFT; } else { return FROM_LEFT + HORIZONTALLY; } } else { // Above-right. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_RIGHT; } else { return FROM_RIGHT + HORIZONTALLY; } } } else { // The source is one of three locations below the destination. return bottomThree(sourceCoordinate, destinationCoordinate, sourceList, isSente); } } return ""; } private static boolean haveSameX(Coordinate first, Coordinate second) { return Objects.equals(first.getX(), second.getX()); } private static String disXKE(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { boolean isSente = komaType == Koma.Type.SKE; List<Coordinate> sourceList = getPossibleSources(board, destinationCoordinate, komaType); if (sourceList.size() > 1) { if (onLeft(sourceCoordinate, destinationCoordinate, isSente)) { return FROM_LEFT; } else { return FROM_RIGHT; } } return ""; } static boolean isBelow(Coordinate firstCoordinate, Coordinate secondCoordinate, boolean isSente) { if (isSente) { return firstCoordinate.getY() > secondCoordinate.getY(); } else { return firstCoordinate.getY() < secondCoordinate.getY(); } } private static String disXUMRY(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { boolean isSente = komaType == Koma.Type.SUM || komaType == Koma.Type.SRY; List<Coordinate> sourceList = getPossibleSources(board, destinationCoordinate, komaType); if (sourceList.size() > 1) { // There is ambiguity. Coordinate otherCoordinate = getOtherCoordinate(sourceCoordinate, sourceList); if (isBelow(sourceCoordinate, destinationCoordinate, isSente)) { // The source is below the destination. if (isBelow(otherCoordinate, destinationCoordinate, isSente)) { // The other piece is also below the destination. if (onLeft(sourceCoordinate, otherCoordinate, isSente)) { // The source is to left of the other. return FROM_LEFT; } else { return FROM_RIGHT; } } else { // Simple upwards. return UPWARD; } } else if (isAbove(sourceCoordinate, destinationCoordinate, isSente)) { // The source is above the destination. if (isAbove(otherCoordinate, destinationCoordinate, isSente)) { // The other piece is also above the destination. if (onLeft(sourceCoordinate, otherCoordinate, isSente)) { // The source is to left of the other. return FROM_LEFT; } else { return FROM_RIGHT; } } else { // Simple downwards. return DOWNWARD; } } else { // The source is level with the destination. if (numWithSameY(sourceCoordinate, sourceList) > 1) { // Both possible pieces are level with the destination. if (onLeft(sourceCoordinate, otherCoordinate, isSente)) { // The source is to left of the other. return FROM_LEFT; } else { return FROM_RIGHT; } } else { // Simple horizontal. return HORIZONTALLY; } } } return ""; } private static Coordinate getOtherCoordinate(Coordinate sourceCoordinate, List<Coordinate> sourceList) { if (!sourceCoordinate.sameValue(sourceList.get(0))) { return sourceList.get(0); } else { return sourceList.get(1); } } private static String disXKA(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { boolean isSente = komaType == Koma.Type.SKA; List<Coordinate> sourceList = getPossibleSources(board, destinationCoordinate, komaType); if (sourceList.size() > 1) { // There is ambiguity. Coordinate otherCoordinate = getOtherCoordinate(sourceCoordinate, sourceList); if (isBelow(sourceCoordinate, destinationCoordinate, isSente)) { // The source is below the destination. if (isBelow(otherCoordinate, destinationCoordinate, isSente)) { // The other piece is also below the destination. if (onLeft(sourceCoordinate, otherCoordinate, isSente)) { return FROM_LEFT; } else { return FROM_RIGHT; } } else { // Simple upward. return UPWARD; } } else // The source is above the destination. if (isAbove(otherCoordinate, destinationCoordinate, isSente)) { // The other piece is also above the destination. if (onLeft(sourceCoordinate, otherCoordinate, isSente)) { return FROM_LEFT; } else { return FROM_RIGHT; } } else { // Simple downward. return DOWNWARD; } } return ""; } private static List<Coordinate> getSourcesOnDiagonalVectors(Board board, Coordinate destination, Koma.Type komaType) { List<Coordinate> result = new ArrayList<>(); Coordinate resultCoordinate; resultCoordinate = getSourceOnVector(board, destination, -1, -1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 1, -1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, -1, 1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 1, 1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } return result; } public static String getDisambiguation(Board board, Coordinate sourceCoordinate, Coordinate destinationCoordinate, Koma.Type komaType) { return switch (komaType) { case SKE, GKE -> disXKE(board, sourceCoordinate, destinationCoordinate, komaType); case SGI, GGI -> disXGI(board, sourceCoordinate, destinationCoordinate, komaType); case SKI, STO, SNK, SNY, SNG, GKI, GTO, GNK, GNY, GNG -> disXKXI(board, sourceCoordinate, destinationCoordinate, komaType); case SKA, GKA -> disXKA(board, sourceCoordinate, destinationCoordinate, komaType); case SHI, GHI -> disXHI(board, sourceCoordinate, destinationCoordinate, komaType); case SUM, SRY, GUM, GRY -> disXUMRY(board, sourceCoordinate, destinationCoordinate, komaType); default -> ""; }; } public static List<Coordinate> getPossibleSources(Board board, Coordinate destination, Koma.Type komaType) { List<Coordinate> result = new ArrayList<>(); Coordinate resultCoordinate; return switch (komaType) { case SKE -> getSourcesForKoma(board, destination, new int[]{1, -1}, new int[]{2, 2}, komaType); case GKE -> getSourcesForKoma(board, destination, new int[]{1, -1}, new int[]{-2, -2}, komaType); case SGI -> getSourcesForKoma(board, destination, new int[]{1, 0, -1, 1, -1}, new int[]{1, 1, 1, -1, -1}, komaType); case GGI -> getSourcesForKoma(board, destination, new int[]{1, 0, -1, 1, -1}, new int[]{-1, -1, -1, 1, 1}, komaType); case SKI, STO, SNK, SNY, SNG -> getSourcesForKoma(board, destination, new int[]{1, 0, -1, 1, -1, 0}, new int[]{1, 1, 1, 0, 0, -1}, komaType); case GKI, GTO, GNK, GNY, GNG -> getSourcesForKoma(board, destination, new int[]{1, 0, -1, 1, -1, 0}, new int[]{-1, -1, -1, 0, 0, 1}, komaType); case SKY -> { resultCoordinate = getSourceOnVector(board, destination, 0, 1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } yield result; } case GKY -> { resultCoordinate = getSourceOnVector(board, destination, 0, -1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } yield result; } case SKA, GKA -> getSourcesOnDiagonalVectors(board, destination, komaType); case SHI, GHI -> getSourcesOnHorizontalVectors(board, destination, komaType); case SUM, GUM -> { result = getSourcesForKoma(board, destination, new int[]{-1, 1, 0, 0}, new int[]{0, 0, -1, 1}, komaType); for (Coordinate thisCoordinate : getSourcesOnDiagonalVectors(board, destination, komaType)) { result.add(thisCoordinate); } yield result; } case SRY, GRY -> { result = getSourcesForKoma(board, destination, new int[]{-1, 1, 1, -1}, new int[]{-1, -1, 1, 1}, komaType); for (Coordinate thisCoordinate : getSourcesOnHorizontalVectors(board, destination, komaType)) { result.add(thisCoordinate); } yield result; } default -> result; }; } public static Coordinate getSourceCoordinate(String move) { Coordinate result = new Coordinate(); result.setX(Integer.parseInt(move.substring(move.indexOf("(") + 1, move.indexOf("(") + 2))); result.setY(Integer.parseInt(move.substring(move.indexOf("(") + 1, move.indexOf(")"))) - result.getX() * 10); return result; } private static List<Coordinate> getSourcesOnHorizontalVectors(Board board, Coordinate destination, Koma.Type komaType) { List<Coordinate> result = new ArrayList<>(); Coordinate resultCoordinate; resultCoordinate = getSourceOnVector(board, destination, -1, 0, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 1, 0, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 0, -1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } resultCoordinate = getSourceOnVector(board, destination, 0, 1, komaType); if (resultCoordinate != null) { result.add(resultCoordinate); } return result; } private static String bottomThree(Coordinate sourceCoordinate, Coordinate destinationCoordinate, List<Coordinate> sourceList, boolean isSente) { if (numWithSameY(sourceCoordinate, sourceList) == 1) { // Simple up case. return UPWARD; } else if (onLeft(sourceCoordinate, destinationCoordinate, isSente)) { // Below-left. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_LEFT; } else { return FROM_LEFT + UPWARD; } } else if (onRight(sourceCoordinate, destinationCoordinate, isSente)) { // Below-right. if (numWithSameX(sourceCoordinate, sourceList) == 1) { return FROM_RIGHT; } else { return FROM_RIGHT + UPWARD; } } else { // Directly below destination. return VERTICAL; } } private static boolean haveSameY(Coordinate first, Coordinate second) { return Objects.equals(first.getY(), second.getY()); } static boolean onLeft(Coordinate firstCoordinate, Coordinate secondCoordinate, boolean isSente) { if (isSente) { return firstCoordinate.getX() > secondCoordinate.getX(); } else { return firstCoordinate.getX() < secondCoordinate.getX(); } } private static int numWithSameX(Coordinate coordinate, List<Coordinate> coordinateList) { int count = 0; for (Coordinate thisCoordinate : coordinateList) { if (haveSameX(coordinate, thisCoordinate)) { count++; } } return count; } public static List<Coordinate> getSourcesForKoma(Board board, Coordinate destination, int[] offsetX, int[] offsetY, Koma.Type komaType) { List<Coordinate> result = new ArrayList<>(); for (int k = 0; k < offsetX.length; k++) { Coordinate testCoordinate = new Coordinate(destination.getX() + offsetX[k], destination.getY() + offsetY[k]); if (NotationUtils.onBoard(testCoordinate)) {
Koma koma = KifParser.getKoma(board, testCoordinate);
0
2023-11-08 09:24:57+00:00
12k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/config/strategy/applyFriend/AbstractApplyFriendStrategy.java
[ { "identifier": "FriendAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/FriendAdapt.java", "snippet": "public class FriendAdapt {\n\n /**\n * 构建保存好友信息\n *\n * @param applyFriendDTO 申请好友 dto\n * @return {@link SysUserApply }\n * @author q...
import com.qingmeng.config.adapt.FriendAdapt; import com.qingmeng.config.adapt.WsAdapter; import com.qingmeng.config.cache.UserCache; import com.qingmeng.dao.SysUserApplyDao; import com.qingmeng.dto.user.ApplyFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserApply; import com.qingmeng.enums.user.ApplyStatusEnum; import com.qingmeng.config.netty.service.WebSocketService; import com.qingmeng.utils.AssertUtils; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Objects;
10,323
package com.qingmeng.config.strategy.applyFriend; /** * @author 清梦 * @version 1.0.0 * @Description 抽象实现类 * @createTime 2023年11月27日 14:18:00 */ @Component public abstract class AbstractApplyFriendStrategy implements ApplyFriendStrategy { @Resource private SysUserApplyDao sysUserApplyDao; @Resource private WebSocketService webSocketService; @Resource
package com.qingmeng.config.strategy.applyFriend; /** * @author 清梦 * @version 1.0.0 * @Description 抽象实现类 * @createTime 2023年11月27日 14:18:00 */ @Component public abstract class AbstractApplyFriendStrategy implements ApplyFriendStrategy { @Resource private SysUserApplyDao sysUserApplyDao; @Resource private WebSocketService webSocketService; @Resource
private UserCache userCache;
2
2023-11-07 16:04:55+00:00
12k
MonstrousSoftware/Tut3D
core/src/main/java/com/monstrous/tut3d/World.java
[ { "identifier": "CookBehaviour", "path": "core/src/main/java/com/monstrous/tut3d/behaviours/CookBehaviour.java", "snippet": "public class CookBehaviour extends Behaviour {\n\n private static final float SHOOT_INTERVAL = 2f; // seconds between shots\n\n private float shootTimer;\n private fi...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.model.Node; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.monstrous.tut3d.behaviours.CookBehaviour; import com.monstrous.tut3d.inputs.PlayerController; import com.monstrous.tut3d.nav.NavMesh; import com.monstrous.tut3d.nav.NavMeshBuilder; import com.monstrous.tut3d.nav.NavNode; import com.monstrous.tut3d.physics.*; import net.mgsx.gltf.scene3d.scene.Scene; import net.mgsx.gltf.scene3d.scene.SceneAsset;
7,229
package com.monstrous.tut3d; public class World implements Disposable { private final Array<GameObject> gameObjects; private GameObject player; public GameStats stats; private final SceneAsset sceneAsset; private final PhysicsWorld physicsWorld; private final PhysicsBodyFactory factory; private final PlayerController playerController; public final PhysicsRayCaster rayCaster; public final WeaponState weaponState; public NavMesh navMesh; public NavNode navNode; private int prevNode = -1; public World() { gameObjects = new Array<>(); stats = new GameStats(); sceneAsset = Main.assets.sceneAsset; // for(Node node : sceneAsset.scene.model.nodes){ // print some debug info // Gdx.app.log("Node ", node.id); // } physicsWorld = new PhysicsWorld(this); factory = new PhysicsBodyFactory(physicsWorld); rayCaster = new PhysicsRayCaster(physicsWorld); playerController = new PlayerController(this); weaponState = new WeaponState(); } public void clear() { physicsWorld.reset(); playerController.reset(); stats.reset(); weaponState.reset(); gameObjects.clear(); player = null; navMesh = null; prevNode = -1; } public int getNumGameObjects() { return gameObjects.size; } public GameObject getGameObject(int index) { return gameObjects.get(index); } public GameObject getPlayer() { return player; } public void setPlayer( GameObject player ){ this.player = player; player.body.setCapsuleCharacteristics(); //navMesh.updateDistances(player.getPosition()); } public PlayerController getPlayerController() { return playerController; } public GameObject spawnObject(GameObjectType type, String name, String proxyName, CollisionShapeType shapeType, boolean resetPosition, Vector3 position){ Scene scene = loadNode( name, resetPosition, position ); ModelInstance collisionInstance = scene.modelInstance; if(proxyName != null) { Scene proxyScene = loadNode( proxyName, resetPosition, position ); collisionInstance = proxyScene.modelInstance; } PhysicsBody body = null; if(type == GameObjectType.TYPE_NAVMESH){ navMesh = NavMeshBuilder.build(scene.modelInstance); return null; } body = factory.createBody(collisionInstance, shapeType, type.isStatic); GameObject go = new GameObject(type, scene, body); gameObjects.add(go); if(go.type == GameObjectType.TYPE_ENEMY) stats.numEnemies++; if(go.type == GameObjectType.TYPE_PICKUP_COIN) stats.numCoins++; return go; } private Scene loadNode( String nodeName, boolean resetPosition, Vector3 position ) { Scene scene = new Scene(sceneAsset.scene, nodeName); if(scene.modelInstance.nodes.size == 0) throw new RuntimeException("Cannot find node in GLTF file: " + nodeName); applyNodeTransform(resetPosition, scene.modelInstance, scene.modelInstance.nodes.first()); // incorporate nodes' transform into model instance transform scene.modelInstance.transform.translate(position); return scene; } private void applyNodeTransform(boolean resetPosition, ModelInstance modelInstance, Node node ){ if(!resetPosition) modelInstance.transform.mul(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); modelInstance.calculateTransforms(); } public void removeObject(GameObject gameObject){ gameObject.health = 0; if(gameObject.type == GameObjectType.TYPE_ENEMY) stats.numEnemies--; gameObjects.removeValue(gameObject, true); gameObject.dispose(); } public void update( float deltaTime ) { if(stats.numEnemies > 0 || stats.coinsCollected < stats.numCoins) stats.gameTime += deltaTime; else { if(!stats.levelComplete) Main.assets.sounds.GAME_COMPLETED.play(); stats.levelComplete = true; } weaponState.update(deltaTime); playerController.update(player, deltaTime); physicsWorld.update(deltaTime); syncToPhysics(); for(GameObject go : gameObjects) { if(go.getPosition().y < -10) // delete objects that fell off the map removeObject(go); go.update(this, deltaTime); } // navNode = navMesh.findNode( player.getPosition(), Settings.groundRayLength ); // if(navNode == null) // Gdx.app.error("player outside the nav mesh:", " pos:"+ player.getPosition().toString()); // if (navNode != null && navNode.id != prevNode) { // Gdx.app.log("player moves to nav node:", "" + navNode.id + " pos:" + player.getPosition().toString()); // prevNode = navNode.id; // navMesh.updateDistances(player.getPosition()); // } } private void syncToPhysics() { for(GameObject go : gameObjects){ if( go.body != null && go.body.geom.getBody() != null) { if(go.type == GameObjectType.TYPE_PLAYER){ // use information from the player controller, since the rigid body is not rotated. player.scene.modelInstance.transform.setToRotation(Vector3.Z, playerController.getForwardDirection()); player.scene.modelInstance.transform.setTranslation(go.body.getPosition()); } else if(go.type == GameObjectType.TYPE_ENEMY){
package com.monstrous.tut3d; public class World implements Disposable { private final Array<GameObject> gameObjects; private GameObject player; public GameStats stats; private final SceneAsset sceneAsset; private final PhysicsWorld physicsWorld; private final PhysicsBodyFactory factory; private final PlayerController playerController; public final PhysicsRayCaster rayCaster; public final WeaponState weaponState; public NavMesh navMesh; public NavNode navNode; private int prevNode = -1; public World() { gameObjects = new Array<>(); stats = new GameStats(); sceneAsset = Main.assets.sceneAsset; // for(Node node : sceneAsset.scene.model.nodes){ // print some debug info // Gdx.app.log("Node ", node.id); // } physicsWorld = new PhysicsWorld(this); factory = new PhysicsBodyFactory(physicsWorld); rayCaster = new PhysicsRayCaster(physicsWorld); playerController = new PlayerController(this); weaponState = new WeaponState(); } public void clear() { physicsWorld.reset(); playerController.reset(); stats.reset(); weaponState.reset(); gameObjects.clear(); player = null; navMesh = null; prevNode = -1; } public int getNumGameObjects() { return gameObjects.size; } public GameObject getGameObject(int index) { return gameObjects.get(index); } public GameObject getPlayer() { return player; } public void setPlayer( GameObject player ){ this.player = player; player.body.setCapsuleCharacteristics(); //navMesh.updateDistances(player.getPosition()); } public PlayerController getPlayerController() { return playerController; } public GameObject spawnObject(GameObjectType type, String name, String proxyName, CollisionShapeType shapeType, boolean resetPosition, Vector3 position){ Scene scene = loadNode( name, resetPosition, position ); ModelInstance collisionInstance = scene.modelInstance; if(proxyName != null) { Scene proxyScene = loadNode( proxyName, resetPosition, position ); collisionInstance = proxyScene.modelInstance; } PhysicsBody body = null; if(type == GameObjectType.TYPE_NAVMESH){ navMesh = NavMeshBuilder.build(scene.modelInstance); return null; } body = factory.createBody(collisionInstance, shapeType, type.isStatic); GameObject go = new GameObject(type, scene, body); gameObjects.add(go); if(go.type == GameObjectType.TYPE_ENEMY) stats.numEnemies++; if(go.type == GameObjectType.TYPE_PICKUP_COIN) stats.numCoins++; return go; } private Scene loadNode( String nodeName, boolean resetPosition, Vector3 position ) { Scene scene = new Scene(sceneAsset.scene, nodeName); if(scene.modelInstance.nodes.size == 0) throw new RuntimeException("Cannot find node in GLTF file: " + nodeName); applyNodeTransform(resetPosition, scene.modelInstance, scene.modelInstance.nodes.first()); // incorporate nodes' transform into model instance transform scene.modelInstance.transform.translate(position); return scene; } private void applyNodeTransform(boolean resetPosition, ModelInstance modelInstance, Node node ){ if(!resetPosition) modelInstance.transform.mul(node.globalTransform); node.translation.set(0,0,0); node.scale.set(1,1,1); node.rotation.idt(); modelInstance.calculateTransforms(); } public void removeObject(GameObject gameObject){ gameObject.health = 0; if(gameObject.type == GameObjectType.TYPE_ENEMY) stats.numEnemies--; gameObjects.removeValue(gameObject, true); gameObject.dispose(); } public void update( float deltaTime ) { if(stats.numEnemies > 0 || stats.coinsCollected < stats.numCoins) stats.gameTime += deltaTime; else { if(!stats.levelComplete) Main.assets.sounds.GAME_COMPLETED.play(); stats.levelComplete = true; } weaponState.update(deltaTime); playerController.update(player, deltaTime); physicsWorld.update(deltaTime); syncToPhysics(); for(GameObject go : gameObjects) { if(go.getPosition().y < -10) // delete objects that fell off the map removeObject(go); go.update(this, deltaTime); } // navNode = navMesh.findNode( player.getPosition(), Settings.groundRayLength ); // if(navNode == null) // Gdx.app.error("player outside the nav mesh:", " pos:"+ player.getPosition().toString()); // if (navNode != null && navNode.id != prevNode) { // Gdx.app.log("player moves to nav node:", "" + navNode.id + " pos:" + player.getPosition().toString()); // prevNode = navNode.id; // navMesh.updateDistances(player.getPosition()); // } } private void syncToPhysics() { for(GameObject go : gameObjects){ if( go.body != null && go.body.geom.getBody() != null) { if(go.type == GameObjectType.TYPE_PLAYER){ // use information from the player controller, since the rigid body is not rotated. player.scene.modelInstance.transform.setToRotation(Vector3.Z, playerController.getForwardDirection()); player.scene.modelInstance.transform.setTranslation(go.body.getPosition()); } else if(go.type == GameObjectType.TYPE_ENEMY){
CookBehaviour cb = (CookBehaviour) go.behaviour;
0
2023-11-04 13:15:48+00:00
12k
Einzieg/EinziegCloud
src/main/java/com/cloud/service/impl/AuthenticationService.java
[ { "identifier": "AuthenticationDTO", "path": "src/main/java/com/cloud/entity/AuthenticationDTO.java", "snippet": "@Data\npublic class AuthenticationDTO implements Serializable, UserDetails {\n\n\t@Serial\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate String id;\n\n\tprivate String emai...
import com.alibaba.fastjson2.JSON; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cloud.entity.AuthenticationDTO; import com.cloud.entity.User; import com.cloud.entity.UserRole; import com.cloud.entity.request.AuthenticationRequest; import com.cloud.entity.request.RegisterRequest; import com.cloud.entity.response.AuthenticationResponse; import com.cloud.mapper.AuthenticationMapper; import com.cloud.service.IAuthenticationService; import com.cloud.service.IUserRoleService; import com.cloud.service.IUserService; import com.cloud.util.HttpUtil; import com.cloud.util.IPUtil; import com.cloud.util.JwtUtil; import com.cloud.util.RedisUtil; import com.cloud.util.msg.Msg; import com.cloud.util.msg.ResultCode; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Optional;
9,182
package com.cloud.service.impl; /** * 身份验证服务 * * @author Einzieg */ @Slf4j @Service @RequiredArgsConstructor public class AuthenticationService extends ServiceImpl<AuthenticationMapper, AuthenticationDTO> implements IAuthenticationService { private final IUserService userService; private final IUserRoleService userRoleService; private final PasswordEncoder passwordEncoder; private final AuthenticationManager authenticationManager;
package com.cloud.service.impl; /** * 身份验证服务 * * @author Einzieg */ @Slf4j @Service @RequiredArgsConstructor public class AuthenticationService extends ServiceImpl<AuthenticationMapper, AuthenticationDTO> implements IAuthenticationService { private final IUserService userService; private final IUserRoleService userRoleService; private final PasswordEncoder passwordEncoder; private final AuthenticationManager authenticationManager;
private final JwtUtil jwtUtil;
12
2023-11-07 07:27:53+00:00
12k
hlysine/create_power_loader
src/main/java/com/hlysine/create_power_loader/command/ListLoadersCommand.java
[ { "identifier": "ChunkLoadManager", "path": "src/main/java/com/hlysine/create_power_loader/content/ChunkLoadManager.java", "snippet": "public class ChunkLoadManager {\n private static final Logger LOGGER = LogUtils.getLogger();\n private static final int SAVED_CHUNKS_DISCARD_TICKS = 100;\n\n pr...
import com.hlysine.create_power_loader.content.ChunkLoadManager; import com.hlysine.create_power_loader.content.ChunkLoader; import com.hlysine.create_power_loader.content.LoaderMode; import com.hlysine.create_power_loader.content.WeakCollection; import com.hlysine.create_power_loader.content.trains.CarriageChunkLoader; import com.hlysine.create_power_loader.content.trains.StationChunkLoader; import com.hlysine.create_power_loader.content.trains.TrainChunkLoader; import com.mojang.brigadier.Command; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.ArgumentBuilder; import com.simibubi.create.foundation.utility.Components; import com.simibubi.create.foundation.utility.Pair; import net.minecraft.ChatFormatting; import net.minecraft.commands.CommandSourceStack; import net.minecraft.commands.Commands; import net.minecraft.core.BlockPos; import net.minecraft.core.registries.Registries; import net.minecraft.network.chat.ClickEvent; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.HoverEvent; import net.minecraft.network.chat.MutableComponent; import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.phys.Vec3; import net.minecraftforge.server.command.EnumArgument; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function;
7,494
package com.hlysine.create_power_loader.command; public class ListLoadersCommand { public static ArgumentBuilder<CommandSourceStack, ?> register() { return Commands.literal("list") .requires(cs -> cs.hasPermission(2)) .then(Commands.argument("type", EnumArgument.enumArgument(LoaderMode.class)) .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, true)) ) ).executes(handler(true, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, false)) ) ).executes(handler(true, false, false)) ) ) .then(Commands.literal("all") .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, true)) ) ).executes(handler(false, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, false)) ) ).executes(handler(false, false, false)) ) ); } private static Command<CommandSourceStack> handler(boolean hasMode, boolean hasLimit, boolean activeOnly) { return ctx -> { CommandSourceStack source = ctx.getSource(); fillReport(source.getLevel(), source.getPosition(), hasMode ? ctx.getArgument("type", LoaderMode.class) : null, hasLimit ? ctx.getArgument("limit", Integer.class) : 20, activeOnly, (s, f) -> source.sendSuccess(() -> Components.literal(s).withStyle(st -> st.withColor(f)), false), (c) -> source.sendSuccess(() -> c, false)); return Command.SINGLE_SUCCESS; }; } private static void fillReport(ServerLevel level, Vec3 location, @Nullable LoaderMode mode, int limit, boolean activeOnly, BiConsumer<String, Integer> chat, Consumer<Component> chatRaw) { int white = ChatFormatting.WHITE.getColor(); int gray = ChatFormatting.GRAY.getColor(); int blue = 0xD3DEDC; int darkBlue = 0x5955A1; int orange = 0xFFAD60; List<ChunkLoader> loaders = new LinkedList<>(); if (mode == null) {
package com.hlysine.create_power_loader.command; public class ListLoadersCommand { public static ArgumentBuilder<CommandSourceStack, ?> register() { return Commands.literal("list") .requires(cs -> cs.hasPermission(2)) .then(Commands.argument("type", EnumArgument.enumArgument(LoaderMode.class)) .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, true)) ) ).executes(handler(true, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(true, true, false)) ) ).executes(handler(true, false, false)) ) ) .then(Commands.literal("all") .then(Commands.literal("active") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, true)) ) ).executes(handler(false, false, true)) ) .then(Commands.literal("all") .then(Commands.literal("limit") .then(Commands.argument("limit", IntegerArgumentType.integer(1)) .executes(handler(false, true, false)) ) ).executes(handler(false, false, false)) ) ); } private static Command<CommandSourceStack> handler(boolean hasMode, boolean hasLimit, boolean activeOnly) { return ctx -> { CommandSourceStack source = ctx.getSource(); fillReport(source.getLevel(), source.getPosition(), hasMode ? ctx.getArgument("type", LoaderMode.class) : null, hasLimit ? ctx.getArgument("limit", Integer.class) : 20, activeOnly, (s, f) -> source.sendSuccess(() -> Components.literal(s).withStyle(st -> st.withColor(f)), false), (c) -> source.sendSuccess(() -> c, false)); return Command.SINGLE_SUCCESS; }; } private static void fillReport(ServerLevel level, Vec3 location, @Nullable LoaderMode mode, int limit, boolean activeOnly, BiConsumer<String, Integer> chat, Consumer<Component> chatRaw) { int white = ChatFormatting.WHITE.getColor(); int gray = ChatFormatting.GRAY.getColor(); int blue = 0xD3DEDC; int darkBlue = 0x5955A1; int orange = 0xFFAD60; List<ChunkLoader> loaders = new LinkedList<>(); if (mode == null) {
for (WeakCollection<ChunkLoader> list : ChunkLoadManager.allLoaders.values()) {
0
2023-11-09 04:29:33+00:00
12k
dingodb/dingo-expr
runtime/src/main/java/io/dingodb/expr/runtime/op/collection/MapConstructorOpFactory.java
[ { "identifier": "VariadicOp", "path": "runtime/src/main/java/io/dingodb/expr/runtime/op/VariadicOp.java", "snippet": "public abstract class VariadicOp extends AbstractOp<VariadicOp> {\n private static final long serialVersionUID = 6629213458109720362L;\n\n protected Object evalNonNullValue(@NonNul...
import io.dingodb.expr.runtime.op.VariadicOp; import io.dingodb.expr.runtime.type.AnyType; import io.dingodb.expr.runtime.type.BoolType; import io.dingodb.expr.runtime.type.BytesType; import io.dingodb.expr.runtime.type.DateType; import io.dingodb.expr.runtime.type.DecimalType; import io.dingodb.expr.runtime.type.DoubleType; import io.dingodb.expr.runtime.type.FloatType; import io.dingodb.expr.runtime.type.IntType; import io.dingodb.expr.runtime.type.LongType; import io.dingodb.expr.runtime.type.MapType; import io.dingodb.expr.runtime.type.StringType; import io.dingodb.expr.runtime.type.TimeType; import io.dingodb.expr.runtime.type.TimestampType; import io.dingodb.expr.runtime.type.Type; import io.dingodb.expr.runtime.type.TypeVisitorBase; import io.dingodb.expr.runtime.type.Types; import lombok.AccessLevel; import lombok.RequiredArgsConstructor; import org.checkerframework.checker.nullness.qual.NonNull;
8,344
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime.op.collection; public class MapConstructorOpFactory extends CollectionConstructorOpFactory { public static final MapConstructorOpFactory INSTANCE = new MapConstructorOpFactory(); public static final String NAME = "MAP"; private static final long serialVersionUID = 5608719489744552506L; protected MapConstructorOpFactory() { } @Override public VariadicOp getOp(Object key) { if (key != null) { MapType type = (MapType) key; if (type.getKeyType().equals(Types.STRING) && type.getValueType().isScalar()) { return StringMapConstructorOpCreator.INSTANCE.visit(type.getValueType()); } return new MapConstructorOp(type); } return null; } @Override public @NonNull String getName() { return NAME; } @Override public Object keyOf(@NonNull Type @NonNull ... types) { int size = types.length; if (size == 0) { return Types.MAP_ANY_ANY; } else if (size % 2 == 0) { Type keyType = types[0]; Type valueType = types[1]; for (int i = 2; i < types.length; i += 2) { if (!types[i].equals(keyType)) { keyType = Types.ANY; break; } if (!types[i + 1].equals(valueType)) { valueType = Types.ANY; break; } } return Types.map(keyType, valueType); } return null; } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class StringMapConstructorOpCreator extends TypeVisitorBase<MapConstructorOp, Type> { private static final StringMapConstructorOpCreator INSTANCE = new StringMapConstructorOpCreator(); private static final MapConstructorOp MAP_STRING_INT_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_INT); private static final MapConstructorOp MAP_STRING_LONG_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_LONG); private static final MapConstructorOp MAP_STRING_FLOAT_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_FLOAT); private static final MapConstructorOp MAP_STRING_DOUBLE_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_DOUBLE); private static final MapConstructorOp MAP_STRING_BOOL_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_BOOL); private static final MapConstructorOp MAP_STRING_DECIMAL_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_DECIMAL); private static final MapConstructorOp MAP_STRING_STRING_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_STRING); private static final MapConstructorOp MAP_STRING_BYTES_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_BYTES); private static final MapConstructorOp MAP_STRING_DATE_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_DATE); private static final MapConstructorOp MAP_STRING_TIME_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_TIME); private static final MapConstructorOp MAP_STRING_TIMESTAMP_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_TIMESTAMP); private static final MapConstructorOp MAP_STRING_ANY_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_ANY); @Override public MapConstructorOp visitIntType(@NonNull IntType type, Type obj) { return MAP_STRING_INT_CONSTRUCTOR; } @Override public MapConstructorOp visitLongType(@NonNull LongType type, Type obj) { return MAP_STRING_LONG_CONSTRUCTOR; } @Override
/* * Copyright 2021 DataCanvas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dingodb.expr.runtime.op.collection; public class MapConstructorOpFactory extends CollectionConstructorOpFactory { public static final MapConstructorOpFactory INSTANCE = new MapConstructorOpFactory(); public static final String NAME = "MAP"; private static final long serialVersionUID = 5608719489744552506L; protected MapConstructorOpFactory() { } @Override public VariadicOp getOp(Object key) { if (key != null) { MapType type = (MapType) key; if (type.getKeyType().equals(Types.STRING) && type.getValueType().isScalar()) { return StringMapConstructorOpCreator.INSTANCE.visit(type.getValueType()); } return new MapConstructorOp(type); } return null; } @Override public @NonNull String getName() { return NAME; } @Override public Object keyOf(@NonNull Type @NonNull ... types) { int size = types.length; if (size == 0) { return Types.MAP_ANY_ANY; } else if (size % 2 == 0) { Type keyType = types[0]; Type valueType = types[1]; for (int i = 2; i < types.length; i += 2) { if (!types[i].equals(keyType)) { keyType = Types.ANY; break; } if (!types[i + 1].equals(valueType)) { valueType = Types.ANY; break; } } return Types.map(keyType, valueType); } return null; } @RequiredArgsConstructor(access = AccessLevel.PRIVATE) private static class StringMapConstructorOpCreator extends TypeVisitorBase<MapConstructorOp, Type> { private static final StringMapConstructorOpCreator INSTANCE = new StringMapConstructorOpCreator(); private static final MapConstructorOp MAP_STRING_INT_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_INT); private static final MapConstructorOp MAP_STRING_LONG_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_LONG); private static final MapConstructorOp MAP_STRING_FLOAT_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_FLOAT); private static final MapConstructorOp MAP_STRING_DOUBLE_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_DOUBLE); private static final MapConstructorOp MAP_STRING_BOOL_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_BOOL); private static final MapConstructorOp MAP_STRING_DECIMAL_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_DECIMAL); private static final MapConstructorOp MAP_STRING_STRING_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_STRING); private static final MapConstructorOp MAP_STRING_BYTES_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_BYTES); private static final MapConstructorOp MAP_STRING_DATE_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_DATE); private static final MapConstructorOp MAP_STRING_TIME_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_TIME); private static final MapConstructorOp MAP_STRING_TIMESTAMP_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_TIMESTAMP); private static final MapConstructorOp MAP_STRING_ANY_CONSTRUCTOR = new MapConstructorOp(Types.MAP_STRING_ANY); @Override public MapConstructorOp visitIntType(@NonNull IntType type, Type obj) { return MAP_STRING_INT_CONSTRUCTOR; } @Override public MapConstructorOp visitLongType(@NonNull LongType type, Type obj) { return MAP_STRING_LONG_CONSTRUCTOR; } @Override
public MapConstructorOp visitFloatType(@NonNull FloatType type, Type obj) {
7
2023-11-04 08:43:49+00:00
12k