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
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/widget/DeviceTestPartView.java
[ { "identifier": "HomeDevice", "path": "app/src/main/java/kr/or/kashi/hde/HomeDevice.java", "snippet": "public class HomeDevice {\n private static final String TAG = HomeDevice.class.getSimpleName();\n private static final String PROP_PREFIX = \"0.\";\n\n /**\n * Application registers {@link HomeDevice.Callback} object to receive\n * notifications about the home network.\n */\n public interface Callback {\n /**\n * Called when property has been changed\n * @param device {@link HomeDevice} object that some state has been changed.\n * @param props {@link List} object that contains properties.\n */\n default void onPropertyChanged(HomeDevice device, PropertyMap props) {}\n\n /**\n * Called when an error is occurred.\n * @param device {@link HomeDevice} object where this error has been occurred.\n * @param error Error code.\n */\n default void onErrorOccurred(HomeDevice device, @Error int error) {}\n }\n\n /**\n * Types\n */\n public @interface Type {\n int UNKNOWN = 0;\n int LIGHT = 1;\n int DOOR_LOCK = 2;\n int VENTILATION = 3;\n int GAS_VALVE = 4;\n int HOUSE_METER = 5;\n int CURTAIN = 6;\n int THERMOSTAT = 7;\n int BATCH_SWITCH = 8;\n int SENSOR = 9;\n int AIRCONDITIONER = 10;\n int POWER_SAVER = 11;\n }\n\n /**\n * Areas\n */\n public @interface Area {\n int UNKNOWN = 0;\n int ENTERANCE = 1;\n int LIVING_ROOM = 2;\n int MAIN_ROOM = 3;\n int OTHER_ROOM = 4;\n int KITCHEN = 5;\n }\n\n /**\n * Error codes\n */\n public @interface Error {\n int NONE = 0;\n int UNKNOWN = -1;\n int CANT_CONTROL = -2;\n int NO_RESPONDING = -3;\n int NO_DEVICE = -4;\n }\n\n /** Property of the address */\n @PropertyDef(valueClass=String.class)\n public static final String PROP_ADDR = PROP_PREFIX + \"addr\";\n\n /** Property of the area that the device is installed in */\n @PropertyDef(valueClass=Area.class, defValueI=Area.UNKNOWN)\n public static final String PROP_AREA = PROP_PREFIX + \"area\";\n\n /** Property of the name of device */\n @PropertyDef(valueClass=String.class)\n public static final String PROP_NAME = PROP_PREFIX + \"name\";\n\n /** Property of connection state */\n @PropertyDef(valueClass=Boolean.class)\n public static final String PROP_CONNECTED = PROP_PREFIX + \"connected\";\n\n /** Property of on/off state */\n @PropertyDef(valueClass=Boolean.class)\n public static final String PROP_ONOFF = PROP_PREFIX + \"onoff\";\n\n /** Property of error code that is defined in {@link Error} */\n @PropertyDef(valueClass=Error.class)\n public static final String PROP_ERROR = PROP_PREFIX + \"error\";\n\n /** Property of the numeric code of device vendor */\n @PropertyDef(valueClass=Integer.class)\n public static final String PROP_VENDOR_CODE = PROP_PREFIX + \"vendor.code\";\n\n /** Property of the name of device vendor */\n @PropertyDef(valueClass=String.class)\n public static final String PROP_VENDOR_NAME = PROP_PREFIX + \"vendor.name\";\n\n /** @hide */\n @PropertyDef(valueClass=Boolean.class)\n public static final String PROP_IS_SLAVE = PROP_PREFIX + \"is_salve\";\n\n private static Map<Class, Map<String, PropertyValue>> sDefaultPropertyMap\n = new ConcurrentHashMap<>();\n\n private final DeviceContextBase mDeviceContext;\n\n private final Handler mHandler;\n private final Executor mHandlerExecutor;\n private final Object mLock = new Object();\n private DeviceContextListenerImpl mDeviceListener = null;\n private final List<Pair<Callback,Executor>> mCallbacks = new ArrayList<>();\n private final Map<String, PropertyValue> mStagedProperties = new ConcurrentHashMap<>();\n private final Runnable mCommitPropsRunnable = this::commitStagedProperties;\n\n public HomeDevice(DeviceContextBase deviceContext) {\n mDeviceContext = deviceContext;\n mHandler = new Handler(Looper.getMainLooper());\n mHandlerExecutor = mHandler::post;\n }\n\n /** @hide */\n public DeviceContextBase dc() {\n return mDeviceContext;\n }\n\n /**\n * Returns the {@link Type} of device.\n * @return The type of device.\n */\n public @Type int getType() {\n return Type.UNKNOWN;\n }\n\n /**\n * Returns the name of this device.\n * @return The name of device.\n */\n public String getName() {\n return getProperty(PROP_NAME, String.class);\n }\n\n /**\n * Change the name of this device.\n * @param name New name of device.\n */\n public void setName(String name) {\n setProperty(PROP_NAME, String.class, (name == null ? \"\" : name));\n }\n\n /**\n * Set the {@link Area} where the device is located in.\n * @param area The location of device.\n */\n public void setArea(@Area int area) {\n setProperty(PROP_AREA, Integer.class, area);\n }\n\n /**\n * Returns the address of device.\n * @return Address in string format of {@link InetAddress}.\n */\n public String getAddress() {\n return getProperty(PROP_ADDR, String.class);\n }\n\n /**\n * Whether the device is connected.\n * @return {@code true} if device is connected.\n */\n public boolean isConnected() {\n return getProperty(PROP_CONNECTED, Boolean.class);\n }\n\n /**\n * Whether the device is on\n * @return {@code true} if device is on.\n */\n public boolean isOn() {\n return getProperty(PROP_ONOFF, Boolean.class);\n }\n\n /**\n * Sets the on / off state to device\n * @param on The new state whether if device is on.\n */\n public void setOn(boolean on) {\n setProperty(PROP_ONOFF, Boolean.class, on);\n }\n\n /**\n * Retrives last code of {@link Error}\n */\n public @Error int getError() {\n return getProperty(PROP_ERROR, Integer.class);\n }\n\n /**\n * Register callback. The methods of the callback will be called when new events arrived.\n * @param callback The callback to handle event.\n */\n public void addCallback(Callback callback) {\n addCallback(callback, mHandlerExecutor);\n }\n\n public void addCallback(Callback callback, Executor executor) {\n synchronized (mLock) {\n if (mCallbacks.isEmpty() && mDeviceListener == null) {\n mDeviceListener = new DeviceContextListenerImpl(this);\n mDeviceContext.setListener(mDeviceListener);\n }\n mCallbacks.add(Pair.create(callback, executor));\n }\n }\n\n /**\n * Unregisters callback.\n * @param callback The callback to handle event.\n */\n public void removeCallback(Callback callback) {\n synchronized (mLock) {\n Iterator it = mCallbacks.iterator();\n while (it.hasNext()) {\n Pair<Callback,Executor> cb = (Pair<Callback,Executor>) it.next();\n if (cb.first == callback) {\n it.remove();\n }\n }\n if (mCallbacks.isEmpty() && mDeviceListener != null) {\n mDeviceContext.setListener(null);\n mDeviceListener = null;\n }\n }\n }\n\n /**\n * Get current value of a property.\n *\n * @param propName The name of property.\n * @param valueClass Class type of property value.\n * @return Current value of property.\n */\n public <E> E getProperty(String propName, Class<E> valueClass) {\n PropertyValue<E> prop = mDeviceContext.getProperty(propName);\n return prop.getValue();\n }\n\n /**\n * Set value to a property.\n *\n * @param propName The name of property.\n * @param valueClass Class type of property value.\n * @param value New value to set.\n */\n public <E> void setProperty(String propName, Class<E> valueClass, E value) {\n setProperty(new PropertyValue<E>(propName, value));\n }\n\n public <E> E getStagedProperty(String name, Class<E> clazz) {\n if (mStagedProperties.containsKey(name)) {\n return (E) mStagedProperties.get(name).getValue();\n }\n return getProperty(name, clazz);\n }\n\n public long getPropertyL(String name) {\n return getProperty(name, Long.class);\n }\n\n public PropertyMap getReadPropertyMap() {\n return mDeviceContext.getReadPropertyMap();\n }\n\n public void setProperty(PropertyValue prop) {\n mStagedProperties.put(prop.getName(), prop);\n if (!mHandler.hasCallbacks(mCommitPropsRunnable)) {\n mHandler.postDelayed(mCommitPropsRunnable, 1 /* Minimum delay */);\n }\n }\n\n public void setPropertyNow(PropertyValue prop) {\n mStagedProperties.put(prop.getName(), prop);\n flushProperties();\n }\n\n public void flushProperties() {\n mHandler.removeCallbacks(mCommitPropsRunnable);\n commitStagedProperties();\n }\n\n private void commitStagedProperties() {\n if (mStagedProperties.size() > 0) {\n mDeviceContext.setProperty(new ArrayList<>(mStagedProperties.values()));\n mStagedProperties.clear();\n }\n }\n\n private static class DeviceContextListenerImpl implements DeviceContextBase.Listener {\n private final WeakReference<HomeDevice> mWeakOwner;\n\n DeviceContextListenerImpl(HomeDevice device) {\n mWeakOwner = new WeakReference<>(device);\n }\n\n public void onPropertyChanged(List<PropertyValue> props) {\n HomeDevice device = mWeakOwner.get();\n if (device != null) {\n device.onPropertyChanged(props);\n }\n }\n\n public void onErrorOccurred(int error) {\n HomeDevice device = mWeakOwner.get();\n if (device != null) {\n device.onErrorOccurred(error);\n }\n }\n }\n\n public void onPropertyChanged(List<PropertyValue> props) {\n Collection<Pair<Callback,Executor>> callbacks;\n synchronized (mLock) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n PropertyMap propMap = new ReadOnlyPropertyMap(props);\n\n for (Pair<Callback,Executor> cb : callbacks) {\n cb.second.execute(() -> cb.first.onPropertyChanged(this, propMap));\n }\n }\n\n public void onErrorOccurred(int error) {\n Collection<Pair<Callback,Executor>> callbacks;\n synchronized (mLock) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (Pair<Callback,Executor> cb : callbacks) {\n cb.second.execute(() -> cb.first.onErrorOccurred(this, error));\n }\n }\n\n /** @hide */\n public static String typeToString(@Type int type) {\n switch (type) {\n case Type.UNKNOWN: return \"UNKNOWN\";\n case Type.LIGHT: return \"LIGHT\";\n case Type.DOOR_LOCK: return \"DOOR_LOCK\";\n case Type.VENTILATION: return \"VENTILATION\";\n case Type.GAS_VALVE: return \"GAS_VALVE\";\n case Type.HOUSE_METER: return \"HOUSE_METER\";\n case Type.CURTAIN: return \"CURTAIN\";\n case Type.THERMOSTAT: return \"THERMOSTAT\";\n case Type.BATCH_SWITCH: return \"BATCH_SWITCH\";\n case Type.SENSOR: return \"SENSOR\";\n case Type.AIRCONDITIONER: return \"AIRCONDITIONER\";\n case Type.POWER_SAVER: return \"POWER_SAVER\";\n }\n return \"UNKNOWN\";\n }\n\n /** @hide */\n public static String areaToString(@Area int area) {\n switch (area) {\n case Area.UNKNOWN: return \"UNKNOWN\";\n case Area.ENTERANCE: return \"ENTERANCE\";\n case Area.LIVING_ROOM: return \"LIVING_ROOM\";\n case Area.MAIN_ROOM: return \"MAIN_ROOM\";\n case Area.OTHER_ROOM: return \"OTHER_ROOM\";\n case Area.KITCHEN: return \"KITCHEN\";\n }\n return \"UNKNOWN\";\n }\n\n /** @hide */\n @Override\n public String toString() {\n return \"HomeDevice {\" +\n \" name=\" + getName() +\n \" type=\" + typeToString(getType()) +\n \" address=\" + getAddress().toString() + \" }\";\n }\n}" }, { "identifier": "DeviceTestCallback", "path": "app/src/main/java/kr/or/kashi/hde/test/DeviceTestCallback.java", "snippet": "public interface DeviceTestCallback {\n default void onTestRunnerStarted() {}\n default void onTestRunnerFinished() {}\n default void onDeviceTestStarted(HomeDevice device) {}\n default void onDeviceTestExecuted(HomeDevice device, TestCase test, TestResult result, int progress) {}\n default void onDeviceTestFinished(HomeDevice device) {}\n}" }, { "identifier": "DeviceTestRunner", "path": "app/src/main/java/kr/or/kashi/hde/test/DeviceTestRunner.java", "snippet": "public class DeviceTestRunner implements Runnable {\n private static final String TAG = DeviceTestRunner.class.getSimpleName();\n\n private final Handler mHandler;\n private final Executor mHandlerExecutor;\n private final List<DeviceTestCallback> mCallbacks = new ArrayList<>();\n private List<HomeDevice> mDevices = new ArrayList<>();\n private Thread mThread = null;\n private boolean mRun = true;\n\n public DeviceTestRunner(Handler handler) {\n mHandler = handler;\n mHandlerExecutor = mHandler::post;\n }\n\n public void addCallback(DeviceTestCallback callback) {\n synchronized (mCallbacks) {\n mCallbacks.add(callback);\n }\n }\n\n public void removeCallback(DeviceTestCallback callback) {\n synchronized (mCallbacks) {\n mCallbacks.remove(callback);\n }\n }\n\n public boolean isRunning() {\n return mRun;\n }\n\n public boolean start(List<HomeDevice> devices) {\n if (mThread != null) {\n stop();\n }\n\n mDevices.addAll(devices);\n\n mRun = true;\n mThread = new Thread(this, TAG + \".\" + DeviceTestRunner.class.getSimpleName());\n mThread.start();\n\n return true;\n }\n\n public void stop() {\n if (mThread == null) {\n return;\n }\n\n mRun = false;\n\n try {\n mThread.join(200);\n } catch (InterruptedException e) {\n }\n\n mThread = null;\n mDevices.clear();\n }\n\n private void callOnTestRunnerStarted() {\n Collection<DeviceTestCallback> callbacks;\n\n synchronized (mCallbacks) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (DeviceTestCallback cb : callbacks) {\n mHandlerExecutor.execute(cb::onTestRunnerStarted);\n }\n }\n\n private void callOnTestRunnerFinished() {\n Collection<DeviceTestCallback> callbacks;\n\n synchronized (mCallbacks) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (DeviceTestCallback cb : callbacks) {\n mHandlerExecutor.execute(cb::onTestRunnerFinished);\n }\n }\n\n private void callOnDeviceTestStarted(HomeDevice device) {\n Collection<DeviceTestCallback> callbacks;\n\n synchronized (mCallbacks) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (DeviceTestCallback cb : callbacks) {\n mHandlerExecutor.execute(() -> cb.onDeviceTestStarted(device));\n }\n }\n\n private void callOnDeviceTestExecuted(HomeDevice device, TestCase test, TestResult result, int progress) {\n Collection<DeviceTestCallback> callbacks;\n\n synchronized (mCallbacks) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (DeviceTestCallback cb : callbacks) {\n mHandlerExecutor.execute(() -> cb.onDeviceTestExecuted(device, test, result, progress));\n }\n }\n\n private void callOnDeviceTestFinished(HomeDevice device) {\n Collection<DeviceTestCallback> callbacks;\n\n synchronized (mCallbacks) {\n if (mCallbacks.isEmpty()) return;\n callbacks = new ArraySet<>(mCallbacks);\n }\n\n for (DeviceTestCallback cb : callbacks) {\n mHandlerExecutor.execute(() -> cb.onDeviceTestFinished(device));\n }\n }\n\n @Override\n public void run() {\n Log.d(TAG, \"thread started\");\n callOnTestRunnerStarted();\n\n for (int i=0; i<mDevices.size(); i++) {\n HomeDevice device = mDevices.get(i);\n\n // Test only single devices\n if (new KSAddress(device.getAddress()).getDeviceSubId().hasFull()) {\n continue;\n }\n\n callOnDeviceTestStarted(device);\n\n int progress = (int) (((double)i / (double)mDevices.size()) * 100.0);\n\n for (DeviceTestCase test: buildDeviceTestCases(device)) {\n TestResult result = new TestResult(); // TODO:\n test.run(result);\n callOnDeviceTestExecuted(device, test, result, progress);\n }\n\n callOnDeviceTestFinished(device);\n }\n\n mRun = false;\n callOnTestRunnerFinished();\n Log.d(TAG, \"thread finished\");\n }\n\n private List<DeviceTestCase> buildDeviceTestCases(HomeDevice device) {\n String testPackage = device.getClass().getPackage().getName();\n String testClassName = device.getClass().getSimpleName() + \"Test\";\n\n Class<?> testClass = null;\n try {\n testClass = Class.forName(testPackage + \".\" + testClassName);\n } catch (ClassNotFoundException e) {\n }\n\n if (testClass == null) {\n return new ArrayList<>();\n }\n\n List<DeviceTestCase> tests = createTestsFromClass(testClass);\n for (DeviceTestCase t: tests) {\n if (t instanceof DeviceTestCase) {\n ((DeviceTestCase)t).setDevice(device);\n }\n }\n return tests;\n }\n\n private List<DeviceTestCase> createTestsFromClass(final Class<?> testClass) {\n List tests = new ArrayList<>();\n\n try {\n getTestConstructor(testClass);\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n return tests;\n }\n\n if (!Modifier.isPublic(testClass.getModifiers())) {\n Log.e(TAG, \"Class \" + testClass.getName() + \" is not public\");\n return tests;\n }\n\n Class<?> clazz = testClass;\n while (DeviceTestCase.class.isAssignableFrom(clazz)) {\n for (Method m : clazz.getDeclaredMethods()) {\n DeviceTestCase test = createTestByMethod(testClass, m);\n if (test != null) tests.add(test);\n }\n clazz = clazz.getSuperclass();\n }\n\n return tests;\n }\n\n public static Constructor<?> getTestConstructor(Class<?> testClass)\n throws NoSuchMethodException {\n try {\n return testClass.getConstructor(String.class);\t\n } catch (NoSuchMethodException e) {\n }\n return testClass.getConstructor(new Class[0]);\n }\n\n private static DeviceTestCase createTestByMethod(Class<?> testClass, Method testMethod) {\n if (!isTestMethod(testMethod)) {\n return null;\n }\n return createTest(testClass, testMethod.getName());\n }\n\n private static DeviceTestCase createTest(Class<?> testClass, String testName) {\n Constructor<?> constructor;\n try {\n constructor = getTestConstructor(testClass);\n } catch (NoSuchMethodException e) {\n e.printStackTrace();\n return null;\n }\n\n DeviceTestCase test = null;\n\n try {\n if (constructor.getParameterTypes().length == 0) {\n test = (DeviceTestCase) constructor.newInstance(new Object[0]);\n if (test instanceof TestCase) ((TestCase)test).setName(testName);\n } else {\n test = (DeviceTestCase) constructor.newInstance(new Object[]{testName});\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return test;\n }\n\n private static boolean isTestMethod(Method m) {\n return (m.getModifiers() & Modifier.PUBLIC) != 0 &&\n m.getParameterTypes().length == 0 && \n m.getName().startsWith(\"test\") && \n m.getReturnType().equals(Void.TYPE);\n }\n}" }, { "identifier": "DebugLog", "path": "app/src/main/java/kr/or/kashi/hde/util/DebugLog.java", "snippet": "public interface DebugLog {\n public static final int EVENT = 1 << 1;\n public static final int TXRX = 1 << 2;\n\n class LoggerHolder {\n public DebugLog logger = null;\n }\n public static LoggerHolder sHolder = new LoggerHolder();\n\n public static void setLogger(DebugLog logger) {\n sHolder.logger = logger;\n }\n\n public static void printEvent(String text) {\n print(EVENT, text);\n }\n\n public static void printTxRx(String text) {\n print(TXRX, text);\n }\n\n public static void print(int type, String text) {\n if (sHolder.logger != null) {\n sHolder.logger.onPrint(type, text);\n }\n }\n\n void onPrint(int type, String text);\n}" } ]
import java.util.List; import kr.or.kashi.hde.HomeDevice; import kr.or.kashi.hde.R; import kr.or.kashi.hde.test.DeviceTestCallback; import kr.or.kashi.hde.test.DeviceTestRunner; import kr.or.kashi.hde.util.DebugLog; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.Nullable; import junit.framework.TestCase; import junit.framework.TestResult;
5,855
/* * 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.widget; public class DeviceTestPartView extends LinearLayout implements DeviceTestCallback { private static final String TAG = DeviceTestPartView.class.getSimpleName(); private final Context mContext; private final Handler mHandler; private final DeviceTestRunner mDeviceTestRunner; private final DeviceTestReportDialog mReportDialog; private TextView mTestStateText; private TextView mTestProgressText; private Button mReportButton; private TestResultView mTestResultView; public DeviceTestPartView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; mHandler = new Handler(Looper.getMainLooper()); mDeviceTestRunner = new DeviceTestRunner(mHandler); mReportDialog = new DeviceTestReportDialog(context); } @Override protected void onFinishInflate() { super.onFinishInflate(); mTestStateText = findViewById(R.id.test_state_text); mTestProgressText = findViewById(R.id.test_progress_text); mReportButton = findViewById(R.id.report_button); mReportButton.setOnClickListener(view -> onReportClicked()); mTestResultView = findViewById(R.id.test_result_view); mDeviceTestRunner.addCallback(this); mDeviceTestRunner.addCallback(mTestResultView); mDeviceTestRunner.addCallback(mReportDialog); } public DeviceTestRunner getTestRunner() { return mDeviceTestRunner; }
/* * 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.widget; public class DeviceTestPartView extends LinearLayout implements DeviceTestCallback { private static final String TAG = DeviceTestPartView.class.getSimpleName(); private final Context mContext; private final Handler mHandler; private final DeviceTestRunner mDeviceTestRunner; private final DeviceTestReportDialog mReportDialog; private TextView mTestStateText; private TextView mTestProgressText; private Button mReportButton; private TestResultView mTestResultView; public DeviceTestPartView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; mHandler = new Handler(Looper.getMainLooper()); mDeviceTestRunner = new DeviceTestRunner(mHandler); mReportDialog = new DeviceTestReportDialog(context); } @Override protected void onFinishInflate() { super.onFinishInflate(); mTestStateText = findViewById(R.id.test_state_text); mTestProgressText = findViewById(R.id.test_progress_text); mReportButton = findViewById(R.id.report_button); mReportButton.setOnClickListener(view -> onReportClicked()); mTestResultView = findViewById(R.id.test_result_view); mDeviceTestRunner.addCallback(this); mDeviceTestRunner.addCallback(mTestResultView); mDeviceTestRunner.addCallback(mReportDialog); } public DeviceTestRunner getTestRunner() { return mDeviceTestRunner; }
public boolean startTest(List<HomeDevice> devices) {
0
2023-11-10 01:19:44+00:00
8k
Bug1312/dm_locator
src/main/java/com/bug1312/dm_locator/mixins/FlightPanelBlockMixin.java
[ { "identifier": "Register", "path": "src/main/java/com/bug1312/dm_locator/Register.java", "snippet": "public class Register {\n\t// Items\n\tpublic static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, ModMain.MOD_ID);\n\tpublic static final RegistryObject<Item> WRITER_ITEM = register(ITEMS, \"locator_data_writer\", () -> new LocatorDataWriterItem(new Properties().tab(DMTabs.DM_TARDIS).stacksTo(1)));\n\tpublic static final RegistryObject<Item> LOCATOR_ATTACHMENT_ITEM = register(ITEMS, \"locator_attachment\", () -> new Item(new Properties().tab(DMTabs.DM_TARDIS)));\n\t\n\t// Tiles\n\tpublic static final DeferredRegister<TileEntityType<?>> TILE_ENTITIES = DeferredRegister.create(ForgeRegistries.TILE_ENTITIES, ModMain.MOD_ID);\n\tpublic static final RegistryObject<TileEntityType<?>> FLIGHT_PANEL_TILE = register(TILE_ENTITIES, \"flight_panel\", () -> Builder.of(FlightPanelTileEntity::new, DMBlocks.FLIGHT_PANEL.get()).build(null));\n\n // Loot Modifiers\n\tpublic static final DeferredRegister<GlobalLootModifierSerializer<?>> LOOT_MODIFIERS = DeferredRegister.create(ForgeRegistries.LOOT_MODIFIER_SERIALIZERS, ModMain.MOD_ID);\n public static final RegistryObject<FlightPanelLootModifier.Serializer> FLIGHT_PANEL_LOOT_MODIFIER = register(LOOT_MODIFIERS, \"flight_panel\", FlightPanelLootModifier.Serializer::new);\n\n\t// Particles\n\tpublic static final DeferredRegister<ParticleType<?>> PARTICLE_TYPES = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, ModMain.MOD_ID);\n\tpublic static final RegistryObject<ParticleType<LocateParticleData>> LOCATE_PARTICLE = register(PARTICLE_TYPES, \"locate\", () -> \n\t\tnew ParticleType<LocateParticleData>(false, LocateParticleData.DESERIALIZER) {\n\t\t\tpublic Codec<LocateParticleData> codec() { return LocateParticleData.CODEC;\t}\n\t\t}\n\t);\n\t\n\t// Advancement Triggers\n\tpublic static final WriteModuleTrigger TRIGGER_WRITE = CriteriaTriggers.register(new WriteModuleTrigger());\n\tpublic static final UseLocatorTrigger TRIGGER_USE = CriteriaTriggers.register(new UseLocatorTrigger());\n\n\t// Key Binds\n public static final KeyBinding KEYBIND_LOCATE = new KeyBinding(String.format(\"%s.keybinds.locate_blast\", ModMain.MOD_ID), 66, \"Dalek Mod\"); // B\n \n // Translations\n public static final Function<LocatorDataWriterMode, TranslationTextComponent> TEXT_SWAP_MODE = (m) -> new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.swap_mode.%s\", ModMain.MOD_ID, m));\n public static final Function<LocatorDataWriterMode, TranslationTextComponent> TEXT_TOOLTIP_MODE = (m) -> new TranslationTextComponent(String.format(\"item.%s.locator_data_writer.hover.mode.%s\", ModMain.MOD_ID, m));\n public static final TranslationTextComponent TEXT_INSUFFICIENT_FUEL = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.insufficient_fuel\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_INVALID_STRUCTURE = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.invalid_structure\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_INVALID_BIOME = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.invalid_biome\", ModMain.MOD_ID));\n public static final TranslationTextComponent TEXT_INVALID_WAYPOINT = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.invalid_waypoint\", ModMain.MOD_ID));\n public static final TranslationTextComponent TEXT_INVALID_MODULE = new TranslationTextComponent(String.format(\"tooltip.%s.flight_mode.invalid_module\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_STRUCTURE = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_structures\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_BIOME = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_biome\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_NO_MODULES = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.no_modules\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_MODULE_WRITTEN = new TranslationTextComponent(String.format(\"tooltip.%s.locator_data_writer.module_written\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_PANEL_LOAD = new TranslationTextComponent(String.format(\"tooltip.%s.flight_panel.load\", ModMain.MOD_ID));\n\tpublic static final TranslationTextComponent TEXT_PANEL_EJECT = new TranslationTextComponent(String.format(\"tooltip.%s.flight_panel.eject\", ModMain.MOD_ID));\n public static final Supplier<TranslationTextComponent> TEXT_USE_BUTTON = () -> new TranslationTextComponent(String.format(\"overlay.%s.flight_mode.use_button\", ModMain.MOD_ID), new KeybindTextComponent(Register.KEYBIND_LOCATE.getName()));\n public static final BiFunction<LocatorDataWriterMode, String, TranslationTextComponent> TEXT_MODULE_NAME = (m, s) -> new TranslationTextComponent(String.format(\"name.%s.structure_module.%s\", ModMain.MOD_ID, m), s);\n\n // Register Method\n\tpublic static <T extends IForgeRegistryEntry<T>, U extends T> RegistryObject<U> register(final DeferredRegister<T> register, final String name, final Supplier<U> supplier) {\n\t\treturn register.register(name, supplier);\n\t}\n}" }, { "identifier": "StructureHelper", "path": "src/main/java/com/bug1312/dm_locator/StructureHelper.java", "snippet": "public class StructureHelper {\n\n\tpublic static final Map<UUID, CompoundNBT> FLYING_PLAYERS_LOCATOR = new HashMap<>();\n\tpublic static boolean isFlyingWithLocator = false;\n\n\tprivate static final Predicate<Pair<MutableBoundingBox, Vector3i>> IS_INSIDE = (pair) -> {\n\t\tMutableBoundingBox bb = pair.getFirst();\n\t\tVector3i pos = pair.getSecond();\n\t\t// Certain structures don't have/require an air gap, \n\t\t// if player is directly above or next to the structure, I still want to pass\n\t\treturn (\n\t\t\tpos.getX() >= bb.x0-1 && pos.getX() <= bb.x1+1 &&\n\t\t\tpos.getZ() >= bb.z0-1 && pos.getZ() <= bb.z1+1 &&\n\t\t\tpos.getY() >= bb.y0-1 && pos.getY() <= bb.y1+1\n\t\t);\n\t};\n\n\tpublic static Optional<ResourceLocation> getStructure(ServerPlayerEntity player) {\n\t\tBlockPos pos = player.blockPosition();\n\t\t\n\t\tStructureManager featureManager = player.getLevel().structureFeatureManager();\n\t\treturn player.getLevel().getChunk(player.blockPosition()).getAllReferences().entrySet().stream() \n\t\t\t// Only look at structures with references inside chunk\n\t\t\t.filter(set -> set.getValue().size() > 0) \n\t\t\t.filter(set -> \n\t\t\t\tDataFixUtils.orElse(featureManager.startsForFeature(SectionPos.of(pos), set.getKey())\n\t\t\t\t\t// Only if player is inside entire structure\n\t\t\t\t\t.filter((start) -> IS_INSIDE.test(Pair.of(start.getBoundingBox(), pos))) \n\t\t\t\t\t// Skip if fastFeature enabled\n\t\t\t\t\t.filter((start) -> Config.SERVER_CONFIG.fastFeature.get() || start.getPieces().stream() \n\t\t\t\t\t\t// Only if player is inside structures' piece\n\t\t\t\t\t\t.anyMatch((piece) -> IS_INSIDE.test(Pair.of(piece.getBoundingBox(), pos)))) \n\t\t\t\t\t.findFirst(), StructureStart.INVALID_START).isValid())\n\t\t\t.findFirst().map(entry -> entry.getKey().getRegistryName());\n\t}\n\t\n\tpublic static String formatResourceLocationName(ResourceLocation resourceLocation) {\n\t\tString reformatted = resourceLocation.getPath().replaceAll(\"_\", \" \");\n\t\tPattern pattern = Pattern.compile(\"(^[a-z]| [a-z])\");\n\t\tMatcher matcher = pattern.matcher(reformatted);\n\t\tStringBuffer noKeyName = new StringBuffer();\n\n\t\twhile (matcher.find()) matcher.appendReplacement(noKeyName, matcher.group().toUpperCase());\n\t\t\n\t\tmatcher.appendTail(noKeyName);\n\t\t\n\t\treturn noKeyName.toString();\n\t}\n\t\n}" }, { "identifier": "FlightPanelTileEntity", "path": "src/main/java/com/bug1312/dm_locator/tiles/FlightPanelTileEntity.java", "snippet": "public class FlightPanelTileEntity extends DMTileEntityBase {\n\t@Nullable\n\tpublic ItemStack cartridge;\n\t\n\tpublic FlightPanelTileEntity() { super(Register.FLIGHT_PANEL_TILE.get()); }\n\n\t@Override\n\tpublic void load(BlockState state, CompoundNBT compound) {\n\t\tif (compound.contains(\"Item\")) this.cartridge = ItemStack.of(compound.getCompound(DMNBTKeys.ITEM));\n\t\t\n\t\tsuper.load(state, compound);\n\t}\n\n\t@Override\n\tpublic CompoundNBT save(CompoundNBT compound) {\n\t\tif (this.cartridge != null && !this.cartridge.isEmpty()) {\n\t\t\tCompoundNBT tag = new CompoundNBT();\n\t\t\tthis.cartridge.save(tag);\n\t\t\tcompound.put(\"Item\", tag);\n\t\t}\n\t\t\n\t\treturn super.save(compound);\n\t}\n\n}" } ]
import java.util.UUID; import java.util.function.Supplier; 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.CallbackInfoReturnable; import com.bug1312.dm_locator.Register; import com.bug1312.dm_locator.StructureHelper; import com.bug1312.dm_locator.tiles.FlightPanelTileEntity; import com.swdteam.common.block.AbstractRotateableWaterLoggableBlock; import com.swdteam.common.block.IBlockTooltip; import com.swdteam.common.block.tardis.DataWriterBlock; import com.swdteam.common.block.tardis.FlightPanelBlock; import com.swdteam.common.init.DMFlightMode; import com.swdteam.common.init.DMItems; import com.swdteam.common.init.DMSoundEvents; import com.swdteam.common.item.DataModuleItem; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.entity.EntityType; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.inventory.InventoryHelper; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.state.BooleanProperty; import net.minecraft.state.IntegerProperty; import net.minecraft.state.StateContainer; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResultType; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.shapes.ISelectionContext; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShapes; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.IBlockReader; import net.minecraft.world.World;
3,741
// Copyright 2023 Bug1312 ([email protected]) package com.bug1312.dm_locator.mixins; @Mixin(FlightPanelBlock.class) public abstract class FlightPanelBlockMixin extends AbstractRotateableWaterLoggableBlock implements IBlockTooltip { public FlightPanelBlockMixin(Properties properties) { super(properties); } private static final BooleanProperty HAS_LOCATOR = BooleanProperty.create("has_locator"); private static final IntegerProperty CARTRIDGE = DataWriterBlock.CARTRIDGE_TYPE; private static final VoxelShape N_ADDON_SHAPE = VoxelShapes.box(6/16D, 2/16D, 8/16D, 1, 8/16D, 1); private static final VoxelShape E_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 6/16D, 8/16D, 8/16D, 1); private static final VoxelShape S_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 0, 10/16D, 8/16D, 8/16D); private static final VoxelShape W_ADDON_SHAPE = VoxelShapes.box(8/16D, 2/16D, 0, 1, 8/16D, 10/16D); private static VoxelShape getAddonShape(BlockState state) { switch (state.getValue(BlockStateProperties.HORIZONTAL_FACING)) { default: case NORTH: return N_ADDON_SHAPE; case EAST: return E_ADDON_SHAPE; case SOUTH: return S_ADDON_SHAPE; case WEST: return W_ADDON_SHAPE; } } private static boolean isMouseOnLocator(BlockState state, BlockPos pos, Vector3d mouse, IBlockReader world) { return state.getValue(HAS_LOCATOR) && getAddonShape(state).bounds().inflate(0.5/16D).contains(mouse.subtract(pos.getX(), pos.getY(), pos.getZ())); } private static void eject(BlockState state, World world, BlockPos pos, FlightPanelTileEntity tile) { if (tile.cartridge != null && tile.cartridge.getItem() instanceof DataModuleItem) { Direction direction = state.getValue(BlockStateProperties.HORIZONTAL_FACING); ItemEntity itemEntity = new ItemEntity(EntityType.ITEM, world); itemEntity.absMoveTo((pos.getX() + 0.5 + direction.getStepX()), pos.getY(), (pos.getZ() + 0.5 + direction.getStepZ()), 0, 0); itemEntity.setDeltaMovement((direction.getStepX() / 10D), 0, (direction.getStepZ() / 10D)); itemEntity.setItem(tile.cartridge); world.addFreshEntity(itemEntity); tile.cartridge = ItemStack.EMPTY; } world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, 0)); } @Inject(at = @At("RETURN"), method = "<init>*", remap = false) public void constructor(final CallbackInfo ci) { this.registerDefaultState(this.defaultBlockState().setValue(HAS_LOCATOR, Boolean.valueOf(false)).setValue(CARTRIDGE, 0)); } @Override public void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder); builder.add(HAS_LOCATOR, CARTRIDGE); } @Inject(at = @At("RETURN"), method = "getShape", cancellable = true, remap = false) public void getShape(final BlockState state, final IBlockReader world, final BlockPos pos, final ISelectionContext context, final CallbackInfoReturnable<VoxelShape> ci) { if (state.getValue(HAS_LOCATOR)) ci.setReturnValue(VoxelShapes.or(ci.getReturnValue(), getAddonShape(state))); } @Inject(at = @At("HEAD"), method = "use", cancellable = true, remap = false) public void use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand handIn, final BlockRayTraceResult result, final CallbackInfoReturnable<ActionResultType> ci) { if (isMouseOnLocator(state, pos, result.getLocation(), world)) { if (!world.isClientSide()) { TileEntity tile = world.getBlockEntity(pos); if (tile != null && tile instanceof FlightPanelTileEntity) { FlightPanelTileEntity panel = (FlightPanelTileEntity) tile; ItemStack slotStack = panel.cartridge; if (slotStack != null && !slotStack.isEmpty()) { if (player.isShiftKeyDown()) { eject(state, world, pos, panel); ci.setReturnValue(ActionResultType.CONSUME); } } else { ItemStack heldStack = player.getItemInHand(handIn); if (heldStack != null && !heldStack.isEmpty()) { Item item = heldStack.getItem(); if ((slotStack == null || slotStack.isEmpty()) && item instanceof DataModuleItem) { panel.cartridge = heldStack.split(1); if (player.abilities.instabuild) heldStack.grow(1); world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, heldStack.getItem() == DMItems.DATA_MODULE.get() ? 1 : 2)); world.playSound((PlayerEntity) null, pos.getX(), pos.getY(), pos.getZ(), DMSoundEvents.TARDIS_MODULE_INSERT.get(), SoundCategory.BLOCKS, 1, 1); ci.setReturnValue(ActionResultType.CONSUME); } } } } } } else if (!state.getValue(HAS_LOCATOR)) { ItemStack heldStack = player.getItemInHand(handIn); if (heldStack != null && !heldStack.isEmpty()) { Item item = heldStack.getItem();
// Copyright 2023 Bug1312 ([email protected]) package com.bug1312.dm_locator.mixins; @Mixin(FlightPanelBlock.class) public abstract class FlightPanelBlockMixin extends AbstractRotateableWaterLoggableBlock implements IBlockTooltip { public FlightPanelBlockMixin(Properties properties) { super(properties); } private static final BooleanProperty HAS_LOCATOR = BooleanProperty.create("has_locator"); private static final IntegerProperty CARTRIDGE = DataWriterBlock.CARTRIDGE_TYPE; private static final VoxelShape N_ADDON_SHAPE = VoxelShapes.box(6/16D, 2/16D, 8/16D, 1, 8/16D, 1); private static final VoxelShape E_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 6/16D, 8/16D, 8/16D, 1); private static final VoxelShape S_ADDON_SHAPE = VoxelShapes.box(0, 2/16D, 0, 10/16D, 8/16D, 8/16D); private static final VoxelShape W_ADDON_SHAPE = VoxelShapes.box(8/16D, 2/16D, 0, 1, 8/16D, 10/16D); private static VoxelShape getAddonShape(BlockState state) { switch (state.getValue(BlockStateProperties.HORIZONTAL_FACING)) { default: case NORTH: return N_ADDON_SHAPE; case EAST: return E_ADDON_SHAPE; case SOUTH: return S_ADDON_SHAPE; case WEST: return W_ADDON_SHAPE; } } private static boolean isMouseOnLocator(BlockState state, BlockPos pos, Vector3d mouse, IBlockReader world) { return state.getValue(HAS_LOCATOR) && getAddonShape(state).bounds().inflate(0.5/16D).contains(mouse.subtract(pos.getX(), pos.getY(), pos.getZ())); } private static void eject(BlockState state, World world, BlockPos pos, FlightPanelTileEntity tile) { if (tile.cartridge != null && tile.cartridge.getItem() instanceof DataModuleItem) { Direction direction = state.getValue(BlockStateProperties.HORIZONTAL_FACING); ItemEntity itemEntity = new ItemEntity(EntityType.ITEM, world); itemEntity.absMoveTo((pos.getX() + 0.5 + direction.getStepX()), pos.getY(), (pos.getZ() + 0.5 + direction.getStepZ()), 0, 0); itemEntity.setDeltaMovement((direction.getStepX() / 10D), 0, (direction.getStepZ() / 10D)); itemEntity.setItem(tile.cartridge); world.addFreshEntity(itemEntity); tile.cartridge = ItemStack.EMPTY; } world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, 0)); } @Inject(at = @At("RETURN"), method = "<init>*", remap = false) public void constructor(final CallbackInfo ci) { this.registerDefaultState(this.defaultBlockState().setValue(HAS_LOCATOR, Boolean.valueOf(false)).setValue(CARTRIDGE, 0)); } @Override public void createBlockStateDefinition(StateContainer.Builder<Block, BlockState> builder) { super.createBlockStateDefinition(builder); builder.add(HAS_LOCATOR, CARTRIDGE); } @Inject(at = @At("RETURN"), method = "getShape", cancellable = true, remap = false) public void getShape(final BlockState state, final IBlockReader world, final BlockPos pos, final ISelectionContext context, final CallbackInfoReturnable<VoxelShape> ci) { if (state.getValue(HAS_LOCATOR)) ci.setReturnValue(VoxelShapes.or(ci.getReturnValue(), getAddonShape(state))); } @Inject(at = @At("HEAD"), method = "use", cancellable = true, remap = false) public void use(final BlockState state, final World world, final BlockPos pos, final PlayerEntity player, final Hand handIn, final BlockRayTraceResult result, final CallbackInfoReturnable<ActionResultType> ci) { if (isMouseOnLocator(state, pos, result.getLocation(), world)) { if (!world.isClientSide()) { TileEntity tile = world.getBlockEntity(pos); if (tile != null && tile instanceof FlightPanelTileEntity) { FlightPanelTileEntity panel = (FlightPanelTileEntity) tile; ItemStack slotStack = panel.cartridge; if (slotStack != null && !slotStack.isEmpty()) { if (player.isShiftKeyDown()) { eject(state, world, pos, panel); ci.setReturnValue(ActionResultType.CONSUME); } } else { ItemStack heldStack = player.getItemInHand(handIn); if (heldStack != null && !heldStack.isEmpty()) { Item item = heldStack.getItem(); if ((slotStack == null || slotStack.isEmpty()) && item instanceof DataModuleItem) { panel.cartridge = heldStack.split(1); if (player.abilities.instabuild) heldStack.grow(1); world.setBlockAndUpdate(pos, state.setValue(CARTRIDGE, heldStack.getItem() == DMItems.DATA_MODULE.get() ? 1 : 2)); world.playSound((PlayerEntity) null, pos.getX(), pos.getY(), pos.getZ(), DMSoundEvents.TARDIS_MODULE_INSERT.get(), SoundCategory.BLOCKS, 1, 1); ci.setReturnValue(ActionResultType.CONSUME); } } } } } } else if (!state.getValue(HAS_LOCATOR)) { ItemStack heldStack = player.getItemInHand(handIn); if (heldStack != null && !heldStack.isEmpty()) { Item item = heldStack.getItem();
if (item == Register.LOCATOR_ATTACHMENT_ITEM.get()) {
0
2023-11-13 03:42:37+00:00
8k
zizai-Shen/young-im
young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/adapter/NacosInstanceRegistryService.java
[ { "identifier": "YoungImException", "path": "young-im-common/src/main/java/cn/young/im/common/exception/YoungImException.java", "snippet": "public class YoungImException extends RuntimeException {\n public YoungImException(String errorMsg) {\n super(errorMsg);\n }\n\n public YoungImException(final Throwable e) {\n super(e);\n }\n}" }, { "identifier": "IpUtils", "path": "young-im-common/src/main/java/cn/young/im/common/util/IpUtils.java", "snippet": "public final class IpUtils {\n\n /**\n * ip pattern.\n */\n private static final Pattern IP_PATTERN = Pattern.compile(\"^((25[0-5]|2[0-4]\\\\d|[01]?\\\\d\\\\d?)($|(?!\\\\.$)\\\\.)){4}$\");\n\n /**\n * net card pattern.\n */\n private static final Pattern NET_CARD_PATTERN = Pattern.compile(\"(\\\\d+)$\");\n\n /**\n * System env docker host ip.\n */\n private static final String SYSTEM_ENV_DOCKER_HOST_IP = \"docker_host_ip\";\n\n /**\n * Localhost.\n */\n private static final String LOCALHOST = \"127.0.0.1\";\n\n /**\n * priority of networkInterface when generating client ip.\n */\n private static final String PROPERTY = System.getProperty(\"networkInterface.priority\", \"enp<eth<bond\");\n\n private static final List<String> PREFER_LIST = new ArrayList<>(Arrays.asList(PROPERTY.split(\"<\")));\n\n private static final Comparator<NetCard> BY_NAME = (card1, card2) -> {\n int card1Score = -1;\n int card2Score = -1;\n for (String pre : PREFER_LIST) {\n if (card1.getName().contains(pre)) {\n card1Score = PREFER_LIST.indexOf(pre);\n break;\n }\n }\n for (String pre : PREFER_LIST) {\n if (card2.getName().contains(pre)) {\n card2Score = PREFER_LIST.indexOf(pre);\n break;\n }\n }\n return card2Score - card1Score;\n };\n\n private IpUtils() {\n }\n\n /**\n * Gets host.\n *\n * @return the host\n */\n public static String getHost() {\n return getHost(null);\n }\n\n /**\n * Gets host.\n *\n * @param filterHost host filterHost str\n * @return the host\n */\n public static String getHost(final String filterHost) {\n String hostIp = null;\n String pattern = filterHost;\n // filter matching ip\n if (\"*\".equals(filterHost) || \"\".equals(filterHost)) {\n pattern = null;\n } else if (filterHost != null && !filterHost.contains(\"*\") && !isCompleteHost(filterHost)) {\n pattern = filterHost + \"*\";\n }\n\n // if the progress works under docker environment\n // return the host ip about this docker located from environment value\n String dockerHostIp = System.getenv(SYSTEM_ENV_DOCKER_HOST_IP);\n if (dockerHostIp != null && !\"\".equals(dockerHostIp)) {\n return dockerHostIp;\n }\n\n // Traversal Network interface to scan all network interface\n List<NetCard> ipv4Result = new ArrayList<>();\n List<NetCard> ipv6Result = new ArrayList<>();\n NetCard netCard;\n try {\n Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();\n while (enumeration.hasMoreElements()) {\n final NetworkInterface networkInterface = enumeration.nextElement();\n Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();\n while (addresses.hasMoreElements()) {\n InetAddress inetAddress = addresses.nextElement();\n if (inetAddress != null && !inetAddress.isLoopbackAddress()) {\n if (inetAddress instanceof Inet4Address && isCompleteHost(inetAddress.getHostAddress())) {\n netCard = new NetCard(inetAddress.getHostAddress(),\n getName(networkInterface.getName()),\n getNamePostfix(networkInterface.getName()),\n Integer.parseInt(inetAddress.getHostAddress().split(\"\\\\.\")[3]));\n ipv4Result.add(netCard);\n } else {\n netCard = new NetCard(inetAddress.getHostAddress(),\n getName(networkInterface.getName()),\n getNamePostfix(networkInterface.getName()));\n ipv6Result.add(netCard);\n }\n }\n }\n }\n\n // sort ip\n Comparator<NetCard> byNamePostfix = Comparator.comparing(NetCard::getNamePostfix);\n Comparator<NetCard> byIpv4Postfix = (card1, card2) -> card2.getIpv4Postfix() - card1.getIpv4Postfix();\n ipv4Result.sort(BY_NAME.thenComparing(byNamePostfix).thenComparing(byIpv4Postfix));\n ipv6Result.sort(BY_NAME.thenComparing(byNamePostfix));\n // prefer ipv4\n if (!ipv4Result.isEmpty()) {\n if (pattern != null) {\n for (NetCard card : ipv4Result) {\n if (ipMatch(card.getIp(), pattern)) {\n hostIp = card.getIp();\n break;\n }\n }\n } else {\n hostIp = ipv4Result.get(0).getIp();\n }\n } else if (!ipv6Result.isEmpty()) {\n hostIp = ipv6Result.get(0).getIp();\n }\n // If failed to find,fall back to localhost\n if (Objects.isNull(hostIp)) {\n hostIp = InetAddress.getLocalHost().getHostAddress();\n }\n } catch (SocketException | UnknownHostException ignore) {\n hostIp = LOCALHOST;\n }\n return hostIp;\n }\n\n /**\n * Judge whether host is complete.\n *\n * @param host host ip\n * @return boolean\n */\n public static boolean isCompleteHost(final String host) {\n if (host == null) {\n return false;\n }\n return IP_PATTERN.matcher(host).matches();\n }\n\n /**\n * do ip match.\n *\n * @param ip network ip\n * @param pattern match pattern\n * @return boolean\n */\n private static boolean ipMatch(final String ip, final String pattern) {\n int m = ip.length();\n int n = pattern.length();\n boolean[][] dp = new boolean[m + 1][n + 1];\n dp[0][0] = true;\n for (int i = 1; i <= n; ++i) {\n if (pattern.charAt(i - 1) == '*') {\n dp[0][i] = true;\n } else {\n break;\n }\n }\n for (int i = 1; i <= m; ++i) {\n for (int j = 1; j <= n; ++j) {\n if (pattern.charAt(j - 1) == '*') {\n dp[i][j] = dp[i][j - 1] || dp[i - 1][j];\n } else if (pattern.charAt(j - 1) == '?' || ip.charAt(i - 1) == pattern.charAt(j - 1)) {\n dp[i][j] = dp[i - 1][j - 1];\n }\n }\n }\n return dp[m][n];\n }\n\n /**\n * To obtain a prefix.\n *\n * @param name network interface name\n * @return the name\n */\n private static String getName(final String name) {\n Matcher matcher = NET_CARD_PATTERN.matcher(name);\n if (matcher.find()) {\n return name.replace(matcher.group(), \"\");\n }\n return name;\n }\n\n /**\n * Get the last number.\n *\n * @param name network interface name\n * @return the name postfix\n */\n private static Integer getNamePostfix(final String name) {\n Matcher matcher = NET_CARD_PATTERN.matcher(name);\n if (matcher.find()) {\n return Integer.parseInt(matcher.group());\n }\n return -1;\n }\n\n private static class NetCard implements Serializable {\n\n private String ip;\n\n private String name;\n\n private Integer namePostfix;\n\n private Integer ipv4Postfix;\n\n NetCard(final String ip, final String name, final Integer namePostfix) {\n this.ip = ip;\n this.name = name;\n this.namePostfix = namePostfix;\n }\n\n NetCard(final String ip, final String name, final Integer namePostfix, final Integer postfix) {\n this.ip = ip;\n this.name = name;\n this.namePostfix = namePostfix;\n this.ipv4Postfix = postfix;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(final String ip) {\n this.ip = ip;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(final String name) {\n this.name = name;\n }\n\n public Integer getIpv4Postfix() {\n return ipv4Postfix;\n }\n\n public Integer getNamePostfix() {\n return namePostfix;\n }\n\n public void setNamePostfix(final Integer namePostfix) {\n this.namePostfix = namePostfix;\n }\n\n }\n}" }, { "identifier": "InstanceEntity", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/InstanceEntity.java", "snippet": "@Data\n@Builder\n@Accessors(chain = true)\npublic class InstanceEntity {\n\n /**\n * 主机地址\n */\n private String host;\n\n /**\n * 端口号\n */\n private int port;\n\n /**\n * 实例健康状态\n */\n private Status status;\n\n /**\n * 权重\n */\n private double weight = 1.0D;\n\n /**\n * 客户端名称\n */\n private String serviceName;\n}" }, { "identifier": "InstanceRegistryService", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/InstanceRegistryService.java", "snippet": "@SPI(\"nacos\")\npublic interface InstanceRegistryService {\n\n /**\n * 初始化注册中心\n */\n default void init(RegisterConfig config) {\n\n }\n\n /**\n * 注册\n */\n void registry(InstanceEntity instanceEntity);\n\n\n /**\n * 获取实例\n */\n List<InstanceEntity> listOfInstance(String tenant);\n}" }, { "identifier": "Status", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/Status.java", "snippet": "@AllArgsConstructor\npublic enum Status implements KeyValueEnum<Integer, String> {\n\n HEALTH(1, \"健康\"),\n\n SUBJECTIVE_DOWN_LINE(2, \"主观下线\"),\n\n OBJECTIVE_DOWN(3, \"客观下线\");\n\n\n final int code;\n\n final String desc;\n\n\n @Override\n public Integer getCode() {\n return this.code;\n }\n\n @Override\n public String getDesc() {\n return this.desc;\n }\n}" }, { "identifier": "NacosConfig", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/config/NacosConfig.java", "snippet": "@Data\npublic class NacosConfig {\n\n /**\n * 租户号\n */\n private String namespace;\n\n /**\n * 组\n */\n private String group;\n\n /**\n * 用户名\n */\n private String username;\n\n /**\n * 密码\n */\n private String password;\n}" }, { "identifier": "RegisterConfig", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-registry/src/main/java/cn/young/im/springboot/starter/adapter/registry/config/RegisterConfig.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"young.im.registry\")\npublic class RegisterConfig {\n\n /**\n * 实例刷新模式\n */\n private String mode;\n\n /**\n * 注册类型\n */\n private String registryType;\n\n /**\n * 注册中心列表\n */\n private String serverLists;\n\n /**\n * Nacos\n */\n private NacosConfig nacos;\n}" }, { "identifier": "AnnotationScanner", "path": "young-im-spring-boot-starter/young-im-spring-boot-starter-extension/src/main/java/cn/young/im/springboot/starter/extension/util/AnnotationScanner.java", "snippet": "@Slf4j\npublic class AnnotationScanner {\n /**\n * 扫描RefreshConfig注解的类\n *\n * @param basePackage 扫描包\n * @return 返回类与对应注解信息\n */\n public static Map<Class<?>, Annotation> scanClassByAnnotation(String basePackage, Class<? extends Annotation> annotationClas) {\n Map<Class<?>, Annotation> annotatedClassesMap = new HashMap<>();\n try {\n ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);\n scanner.addIncludeFilter(new AnnotationTypeFilter(annotationClas));\n ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(AnnotationScanner.class.getClassLoader());\n MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(resourcePatternResolver);\n for (BeanDefinition bd : scanner.findCandidateComponents(basePackage)) {\n MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(Objects.requireNonNull(bd.getBeanClassName()));\n String className = metadataReader.getClassMetadata().getClassName();\n Class<?> clazz = Class.forName(className);\n Annotation annotation = clazz.getAnnotation(annotationClas);\n annotatedClassesMap.put(clazz, annotation);\n }\n } catch (IOException | ClassNotFoundException e) {\n log.error(e.getMessage(), e);\n }\n return annotatedClassesMap;\n }\n}" }, { "identifier": "COLONS", "path": "young-im-common/src/main/java/cn/young/im/common/constants/Const.java", "snippet": "public final static String COLONS = \":\";" }, { "identifier": "BASE_PACKAGE", "path": "young-im-common/src/main/java/cn/young/im/common/constants/YoungConst.java", "snippet": "public static final String BASE_PACKAGE = \"cn.young.im\";" }, { "identifier": "DEFAULT", "path": "young-im-common/src/main/java/cn/young/im/common/constants/YoungConst.java", "snippet": "public static final String DEFAULT = \"#\";" } ]
import cn.young.im.common.exception.YoungImException; import cn.young.im.common.util.IpUtils; import cn.young.im.spi.Join; import cn.young.im.springboot.starter.adapter.registry.InstanceEntity; import cn.young.im.springboot.starter.adapter.registry.InstanceRegistryService; import cn.young.im.springboot.starter.adapter.registry.Status; import cn.young.im.springboot.starter.adapter.registry.annotation.AutomaticRegistry; import cn.young.im.springboot.starter.adapter.registry.config.NacosConfig; import cn.young.im.springboot.starter.adapter.registry.config.RegisterConfig; import cn.young.im.springboot.starter.extension.util.AnnotationScanner; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingFactory; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import static cn.young.im.common.constants.Const.COLONS; import static cn.young.im.common.constants.YoungConst.BASE_PACKAGE; import static cn.young.im.common.constants.YoungConst.DEFAULT;
3,941
package cn.young.im.springboot.starter.adapter.registry.adapter; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description Nacos 实例注册服务 * @date 2023/12/10 */ @Slf4j @Join public class NacosInstanceRegistryService implements
package cn.young.im.springboot.starter.adapter.registry.adapter; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description Nacos 实例注册服务 * @date 2023/12/10 */ @Slf4j @Join public class NacosInstanceRegistryService implements
InstanceRegistryService, EnvironmentAware {
3
2023-11-10 06:21:17+00:00
8k
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_NOT_SHOW_ADDED = \"add_app_not_show_added\";\n public static final String SHOW_ANDROID12_TIPS = \"show_android12_tips_v2\";\n public static final String ADD_APP_NOT_SHOW_32BIT = \"add_app_not_show_32bit\";\n\n // 是否应该重新安装 ROM\n // 1. 恢复出厂设置\n // 2. 替换 ROM\n public static final String FORCE_ROM_BE_RE_INSTALL = \"rom_should_be_re_install\";\n\n // 是否应该使用第三方 ROM\n public static final String SHOULD_USE_THIRD_PARTY_ROM = \"should_use_third_party_rom\";\n public static boolean getBooleanConfig(Context context, String key, boolean fallback) {\n return getPref(context).getBoolean(key, fallback);\n }\n\n @SuppressLint(\"ApplySharedPref\")\n public static void setBooleanConfig(Context context, String key, boolean value) {\n getPref(context).edit().putBoolean(key, value).commit();\n }\n\n private static SharedPreferences getPref(Context context) {\n return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n }\n}" }, { "identifier": "CacheManager", "path": "app/src/main/java/io/twoyi/utils/CacheManager.java", "snippet": "public class CacheManager {\n\n private static final byte[] LABEL_LOCK = new byte[0];\n\n private static ACache sLabelCache;\n\n public static ACache getLabelCache(Context context) {\n synchronized (LABEL_LOCK) {\n if (sLabelCache != null) {\n return sLabelCache;\n }\n Context appContext = context.getApplicationContext();\n if (appContext == null) {\n appContext = context;\n }\n\n sLabelCache = ACache.get(appContext, \"labelCache\");\n return sLabelCache;\n }\n }\n\n public static String getLabel(Context context, ApplicationInfo info, PackageManager pm) {\n PackageManager packageManager;\n if (pm != null) {\n packageManager = pm;\n } else {\n packageManager = context.getPackageManager();\n }\n\n if (info == null) {\n return null;\n }\n\n String key = info.packageName;\n ACache labelCache = getLabelCache(context);\n synchronized (LABEL_LOCK) {\n String label = labelCache.getAsString(key);\n if (label == null) {\n // 缓存没有,那么直接读\n String label1 = info.loadLabel(packageManager).toString();\n labelCache.put(key, label1);\n return label1;\n }\n return label;\n }\n }\n}" }, { "identifier": "IOUtils", "path": "app/src/main/java/io/twoyi/utils/IOUtils.java", "snippet": "@Keep\npublic class IOUtils {\n\n public static void ensureCreated(File file) {\n if (!file.exists()) {\n boolean ret = file.mkdirs();\n if (!ret) {\n throw new RuntimeException(\"create dir: \" + file + \" failed\");\n }\n }\n }\n\n public static boolean deleteDir(File dir) {\n if (dir == null) {\n return false;\n }\n boolean success = true;\n if (dir.isDirectory()) {\n String[] children = dir.list();\n for (String file : children) {\n boolean ret = deleteDir(new File(dir, file));\n if (!ret) {\n success = false;\n }\n }\n if (success) {\n // if all subdirectory are deleted, delete the dir itself.\n return dir.delete();\n }\n }\n return dir.delete();\n }\n\n public static void deleteAll(List<File> files) {\n if (files.isEmpty()) {\n return;\n }\n\n for (File file : files) {\n //noinspection ResultOfMethodCallIgnored\n file.delete();\n }\n }\n\n public static void copyFile(File source, File target) throws IOException {\n FileInputStream inputStream = null;\n FileOutputStream outputStream = null;\n try {\n inputStream = new FileInputStream(source);\n outputStream = new FileOutputStream(target);\n FileChannel iChannel = inputStream.getChannel();\n FileChannel oChannel = outputStream.getChannel();\n\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n while (true) {\n buffer.clear();\n int r = iChannel.read(buffer);\n if (r == -1)\n break;\n buffer.limit(buffer.position());\n buffer.position(0);\n oChannel.write(buffer);\n }\n } finally {\n closeSilently(inputStream);\n closeSilently(outputStream);\n }\n }\n\n public static void closeSilently(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException e) {\n // e.printStackTrace();\n }\n }\n\n public static void setPermissions(String path, int mode, int uid, int gid) {\n try {\n Class<?> fileUtilsClass = Class.forName(\"android.os.FileUtils\");\n Method setPermissions = fileUtilsClass.getDeclaredMethod(\"setPermissions\", String.class, int.class, int.class, int.class);\n setPermissions.setAccessible(true);\n setPermissions.invoke(null, path, mode, uid, gid);\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n\n public static void writeContent(File file, String content) {\n if (file == null || TextUtils.isEmpty(content)) {\n return;\n }\n FileWriter fileWriter = null;\n try {\n fileWriter = new FileWriter(file);\n fileWriter.write(content);\n fileWriter.flush();\n } catch (Throwable ignored) {\n } finally {\n IOUtils.closeSilently(fileWriter);\n }\n }\n\n public static String readContent(File file) {\n if (file == null) {\n return null;\n }\n BufferedReader fileReader = null;\n try {\n fileReader = new BufferedReader(new FileReader(file));\n StringBuilder sb = new StringBuilder();\n String line;\n while ((line = fileReader.readLine()) != null) {\n sb.append(line);\n sb.append('\\n');\n }\n return sb.toString().trim();\n } catch (Throwable ignored) {\n return null;\n } finally {\n IOUtils.closeSilently(fileReader);\n }\n }\n\n public static boolean deleteDirectory(File directory) {\n try {\n Files.walk(directory.toPath())\n .sorted(Comparator.reverseOrder())\n .map(Path::toFile)\n .forEach(File::delete);\n return true;\n } catch (IOException e) {\n return false;\n }\n }\n}" }, { "identifier": "Installer", "path": "app/src/main/java/io/twoyi/utils/Installer.java", "snippet": "public class Installer {\n\n public interface InstallResult {\n void onSuccess(List<File> files);\n\n void onFail(List<File> files, String msg);\n }\n\n private static final String TAG = \"Installer\";\n\n public static final int REQUEST_INSTALL_APP = 101;\n\n public static void installAsync(Context context, String path, InstallResult callback) {\n installAsync(context, Collections.singletonList(new File(path)), callback);\n }\n\n public static void installAsync(Context context, List<File> files, InstallResult callback) {\n new Thread(() -> install(context, files, callback)).start();\n }\n\n public static void install(Context context, List<File> files, InstallResult callback) {\n\n// Shell.enableVerboseLogging = true;\n\n String nativeLibraryDir = context.getApplicationInfo().nativeLibraryDir;\n String adbPath = nativeLibraryDir + File.separator + \"libadb.so\";\n\n String connectTarget = \"localhost:22122\";\n\n final int ADB_PORT = 9563;\n\n String adbCommand = String.format(Locale.US, \"%s -P %d connect %s\", adbPath, ADB_PORT, connectTarget);\n\n String envPath = context.getCacheDir().getAbsolutePath();\n String envCmd = String.format(\"export TMPDIR=%s;export HOME=%s;\", envPath, envPath);\n\n String adbServerCommand = String.format(Locale.US, \"%s -P %d nodaemon server\", adbPath, ADB_PORT);\n ShellUtil.newSh().newJob().add(envCmd).add(adbServerCommand).submit();\n\n Shell shell = ShellUtil.newSh();\n\n Shell.Result result = shell.newJob().add(envCmd).add(adbCommand).to(new ArrayList<>(), new ArrayList<>()).exec();\n\n String errMsg = Arrays.toString(result.getErr().toArray(new String[0]));\n String outMsg = Arrays.toString(result.getOut().toArray(new String[0]));\n\n Log.w(TAG, \"success: \" + result.isSuccess() + \" err: \" + errMsg + \" out: \" + outMsg);\n\n boolean connected = false;\n for (String s : result.getOut()) {\n\n // connected to localhost:22122\n // already connected to localhost\n if (s.contains(\"connected to\")) {\n connected = true;\n }\n }\n\n try {\n shell.waitAndClose(1, TimeUnit.SECONDS);\n } catch (Throwable ignored) {\n }\n\n if (!connected) {\n if (callback != null) {\n callback.onFail(files, \"Adb connect failed!\");\n }\n return;\n }\n\n StringBuilder sb = new StringBuilder();\n for (File file : files) {\n sb.append(file.getAbsolutePath()).append(\" \");\n }\n\n String fileArgs = sb.toString();\n\n String installCommand;\n if (files.size() == 1) {\n installCommand = String.format(Locale.US, \"%s -P %d -s %s install -t -r %s\", adbPath, ADB_PORT, connectTarget, fileArgs);\n } else {\n // http://aospxref.com/android-10.0.0_r47/xref/system/core/adb/client/adb_install.cpp#447\n installCommand = String.format(Locale.US, \"%s -P %d -s %s install-multiple -t -r %s\", adbPath, ADB_PORT, connectTarget, fileArgs);\n }\n\n Log.w(TAG, \"installCommand: \" + installCommand);\n\n Shell installShell = ShellUtil.newSh();\n\n installShell.newJob().add(envCmd).add(installCommand).to(new ArrayList<>(), new ArrayList<>()).submit(out1 -> {\n Log.w(TAG, \"install result: \" + out1.isSuccess());\n\n if (callback == null) {\n return;\n }\n if (out1.isSuccess()) {\n callback.onSuccess(files);\n } else {\n String msg = Arrays.toString(out1.getErr().toArray(new String[0]));\n Log.w(TAG, \"msg: \" + msg);\n\n callback.onFail(files, msg);\n }\n });\n }\n\n public static boolean checkFile(Context context, List<File> files) {\n boolean valid = true;\n for (File file : files) {\n if (!checkFile(context, file.getAbsolutePath())) {\n valid = false;\n break;\n }\n }\n\n return valid;\n }\n\n public static boolean checkFile(Context context, String path) {\n if (path == null) {\n return false;\n }\n\n PackageManager pm = context.getPackageManager();\n if (pm == null) {\n return false;\n }\n\n PackageInfo packageInfo = pm.getPackageArchiveInfo(path, 0);\n\n if (packageInfo == null) {\n Toast.makeText(context.getApplicationContext(), R.string.check_file_invlid_apk, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n String packageName = packageInfo.packageName;\n\n if (TextUtils.equals(packageName, context.getPackageName())) {\n Toast.makeText(context.getApplicationContext(), R.string.check_file_create_self_tip, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n return true;\n }\n}" }, { "identifier": "UIHelper", "path": "app/src/main/java/io/twoyi/utils/UIHelper.java", "snippet": "public class UIHelper {\n private static final AndroidDeferredManager gDM = new AndroidDeferredManager();\n\n public static ExecutorService GLOBAL_EXECUTOR = Executors.newCachedThreadPool();\n\n public static AndroidDeferredManager defer() {\n return gDM;\n }\n\n public static void dismiss(Dialog dialog) {\n if (dialog == null) {\n return;\n }\n\n try {\n dialog.dismiss();\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static void openWeiXin(Context context, String weixin) {\n try {\n // 获取剪贴板管理服务\n ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n if (cm == null) {\n return;\n }\n cm.setText(weixin);\n\n Intent intent = new Intent(Intent.ACTION_MAIN);\n ComponentName cmp = new ComponentName(\"com.tencent.mm\", \"com.tencent.mm.ui.LauncherUI\");\n intent.addCategory(Intent.CATEGORY_LAUNCHER);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.setComponent(cmp);\n\n context.startActivity(intent);\n Toast.makeText(context, R.string.wechat_public_account_tips, Toast.LENGTH_LONG).show();\n } catch (Throwable e) {\n Toast.makeText(context, \"WeChat is not installed.\", Toast.LENGTH_SHORT).show();\n }\n }\n\n public static void show(Dialog dialog) {\n if (dialog == null) {\n return;\n }\n\n try {\n dialog.show();\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static AlertDialog.Builder getDialogBuilder(Context context) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context, com.google.android.material.R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog);\n builder.setIcon(R.mipmap.ic_launcher);\n return builder;\n }\n\n public static AlertDialog.Builder getWebViewBuilder(Context context, String title, String url) {\n AlertDialog.Builder dialogBuilder = getDialogBuilder(context);\n if (!TextUtils.isEmpty(title)) {\n dialogBuilder.setTitle(title);\n }\n WebView webView = new WebView(context);\n webView.loadUrl(url);\n dialogBuilder.setView(webView);\n dialogBuilder.setPositiveButton(R.string.i_know_it, null);\n return dialogBuilder;\n }\n\n public static ProgressDialog getProgressDialog(Context context) {\n ProgressDialog dialog = new ProgressDialog(context);\n dialog.setIcon(R.mipmap.ic_launcher);\n dialog.setTitle(R.string.progress_dialog_title);\n return dialog;\n }\n\n public static MaterialDialog getNumberProgressDialog(Context context) {\n return new MaterialDialog.Builder(context)\n .title(R.string.progress_dialog_title)\n .iconRes(R.mipmap.ic_launcher)\n .progress(false, 0, true)\n .build();\n }\n\n public static void showPrivacy(Context context) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n intent.setData(Uri.parse(\"https://twoyi.app/privacy\"));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n public static void showFAQ(Context context) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n intent.setData(Uri.parse(\"https://twoyi.app/guide\"));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static void goWebsite(Context context) {\n visitSite(context, \"https://twoyi.app\");\n }\n\n public static void goTelegram(Context context) {\n visitSite(context, \"https://t.me/twoyi\");\n }\n\n public static void visitSite(Context context, String url) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.setData(Uri.parse(url));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n public static int dpToPx(Context context, int dp) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,\n context.getResources().getDisplayMetrics());\n }\n\n public static List<ApplicationInfo> getInstalledApplications(PackageManager packageManager) {\n if (packageManager == null) {\n return Collections.emptyList();\n }\n\n @SuppressLint(\"WrongConstant\")\n List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES\n | PackageManager.GET_DISABLED_COMPONENTS);\n int userApp = 0;\n for (ApplicationInfo installedApplication : installedApplications) {\n if ((installedApplication.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n if (userApp++ > 3) {\n return installedApplications;\n }\n }\n }\n\n List<ApplicationInfo> applicationInfos = new ArrayList<>();\n for (int uid = 0; uid <= Process.LAST_APPLICATION_UID; uid++) {\n String[] packagesForUid = packageManager.getPackagesForUid(uid);\n if (packagesForUid == null || packagesForUid.length == 0) {\n continue;\n }\n for (String pkg : packagesForUid) {\n try {\n ApplicationInfo applicationInfo = packageManager.getApplicationInfo(pkg, 0);\n applicationInfos.add(applicationInfo);\n } catch (PackageManager.NameNotFoundException ignored) {\n }\n }\n }\n\n return applicationInfos;\n }\n\n public static String toModuleScope(Set<String> scopes) {\n if (scopes == null || scopes.isEmpty()) {\n return \"\";\n }\n\n StringBuilder sb = new StringBuilder();\n int size = scopes.size();\n\n int i = 0;\n for (String scope : scopes) {\n sb.append(scope);\n\n if (i++ < size - 1) {\n sb.append(',');\n }\n\n }\n return sb.toString();\n }\n\n public static void shareText(Context context, @StringRes int shareTitle, String extraText) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"text/plain\");\n intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(shareTitle));\n intent.putExtra(Intent.EXTRA_TEXT, extraText);//extraText为文本的内容\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//为Activity新建一个任务栈\n context.startActivity(\n Intent.createChooser(intent, context.getString(shareTitle)));\n }\n\n public static String paste(Context context) {\n ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n if (manager == null) {\n return null;\n }\n boolean hasPrimaryClip = manager.hasPrimaryClip();\n if (!hasPrimaryClip) {\n return null;\n }\n ClipData primaryClip = manager.getPrimaryClip();\n if (primaryClip == null) {\n return null;\n }\n if (primaryClip.getItemCount() <= 0) {\n return null;\n }\n CharSequence addedText = primaryClip.getItemAt(0).getText();\n return String.valueOf(addedText);\n }\n\n public static void startActivity(Context context, Class<?> clazz) {\n if (context == null) {\n return;\n }\n\n Intent intent = new Intent(context, clazz);\n\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n\n try {\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n private static boolean isVM64(Set<String> supportedABIs) {\n if (Build.SUPPORTED_64_BIT_ABIS.length == 0) {\n return false;\n }\n\n if (supportedABIs == null || supportedABIs.isEmpty()) {\n return true;\n }\n\n for (String supportedAbi : supportedABIs) {\n if (\"arm64-v8a\".endsWith(supportedAbi) || \"x86_64\".equals(supportedAbi) || \"mips64\".equals(supportedAbi)) {\n return true;\n }\n }\n\n return false;\n }\n\n private static Set<String> getABIsFromApk(String apk) {\n try (ZipFile apkFile = new ZipFile(apk)) {\n Enumeration<? extends ZipEntry> entries = apkFile.entries();\n Set<String> supportedABIs = new HashSet<String>();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (name.contains(\"../\")) {\n continue;\n }\n if (name.startsWith(\"lib/\") && !entry.isDirectory() && name.endsWith(\".so\")) {\n String supportedAbi = name.substring(name.indexOf(\"/\") + 1, name.lastIndexOf(\"/\"));\n supportedABIs.add(supportedAbi);\n }\n }\n return supportedABIs;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static boolean isApk64(String apk) {\n long start = SystemClock.elapsedRealtime();\n Set<String> abIsFromApk = getABIsFromApk(apk);\n return isVM64(abIsFromApk);\n }\n\n @SuppressWarnings(\"JavaReflectionMemberAccess\")\n @SuppressLint(\"DiscouragedPrivateApi\")\n public static boolean isAppSupport64bit(ApplicationInfo info) {\n try {\n // fast path, the isApk64 is too heavy!\n Field primaryCpuAbiField = ApplicationInfo.class.getDeclaredField(\"primaryCpuAbi\");\n String primaryCpuAbi = (String) primaryCpuAbiField.get(info);\n if (primaryCpuAbi == null) {\n // no native libs, support!\n return true;\n }\n\n return Arrays.asList(\"arm64-v8a\", \"x86_64\").contains(primaryCpuAbi.toLowerCase());\n } catch (Throwable e) {\n return isApk64(info.sourceDir);\n }\n }\n}" }, { "identifier": "GlideModule", "path": "app/src/main/java/io/twoyi/utils/image/GlideModule.java", "snippet": "@com.bumptech.glide.annotation.GlideModule\npublic class GlideModule extends AppGlideModule {\n\n @Override\n public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {\n registry.prepend(ApplicationInfo.class, Drawable.class, new DrawableModelLoaderFactory(context));\n }\n\n public static void loadApplicationIcon(Context context, ApplicationInfo applicationInfo, ImageView view) {\n GlideApp.with(context)\n .load(applicationInfo)\n .into(view);\n }\n}" } ]
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;
6,575
/* * 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; }
/* * 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);
4
2023-11-11 22:08:20+00:00
8k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/server/core/Core.java
[ { "identifier": "EventManager", "path": "src/main/java/io/xlorey/FluxLoader/shared/EventManager.java", "snippet": "@UtilityClass\npublic class EventManager {\n /**\n * Event Listeners\n */\n private static final ArrayList<Object> listeners = new ArrayList<>();\n\n /**\n * Subscribing a listener class to events\n * @param listener - Object listener\n */\n public static void subscribe(Object listener) {\n if (!isUniqueSingleEvents(listener)) {\n return;\n }\n\n listeners.add(listener);\n }\n\n /**\n * Returns a set of unique event names marked with the SubscribeSingleEvent annotation.\n * found in the methods of the specified listener object.\n *\n * @param listener A listener object whose methods search for event names.\n * @return Set of unique event names.\n */\n private static HashSet<String> getSingleEventNames(Object listener) {\n HashSet<String> eventNames = new HashSet<>();\n for (Method method : listener.getClass().getDeclaredMethods()) {\n if (method.isAnnotationPresent(SubscribeSingleEvent.class)) {\n SubscribeSingleEvent annotation = method.getAnnotation(SubscribeSingleEvent.class);\n eventNames.add(annotation.eventName());\n }\n }\n return eventNames;\n }\n\n /**\n * Checks whether the listener object contains methods with the same event names,\n * marked with the SubscribeSingleEvent annotation, which are already registered in the system.\n *\n * @param newListener The listener object to test.\n * @return true if there are no conflicting event names in the new listener, false otherwise.\n */\n private static boolean isUniqueSingleEvents(Object newListener) {\n HashSet<String> newListenerEvents = getSingleEventNames(newListener);\n\n for (Object registeredListener : listeners) {\n HashSet<String> registeredListenerEvents = getSingleEventNames(registeredListener);\n for (String eventName : newListenerEvents) {\n if (registeredListenerEvents.contains(eventName)) {\n Logger.printLog(String.format(\"Error subscribing class to events! Duplicate single event '%s' detected in '%s'! Skipping...\",\n eventName,\n newListener.getClass().getName()));\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Calls a method marked with the SubscribeSingleEvent annotation that matches the given event name.\n * The method must be compatible with the arguments provided. Returns the result of a method call.\n *\n * @param eventName The name of the event to raise.\n * @return The result of calling the event method. Returns null if no matching method is found.\n */\n public static Object invokeSingleEventAndReturn(String eventName) {\n return invokeSingleEventAndReturn(eventName, (Object[]) null);\n }\n\n /**\n * Calls a method marked with the SubscribeSingleEvent annotation that matches the given event name.\n * The method must be compatible with the arguments provided. Returns the result of a method call.\n *\n * @param eventName The name of the event to raise.\n * @param args Arguments passed to the event method.\n * @return The result of calling the event method. Returns null if no matching method is found.\n */\n public static Object invokeSingleEventAndReturn(String eventName, Object... args) {\n for (Object listener : listeners) {\n for (Method method : listener.getClass().getDeclaredMethods()) {\n if (method.isAnnotationPresent(SubscribeSingleEvent.class)) {\n SubscribeSingleEvent annotation = method.getAnnotation(SubscribeSingleEvent.class);\n if (annotation.eventName().equals(eventName) && isMethodCompatible(method, eventName, args)) {\n try {\n method.setAccessible(true);\n return method.invoke(listener, args);\n } catch (InvocationTargetException e) {\n Throwable cause = e.getCause();\n String className = listener.getClass().getName();\n String methodName = method.getName();\n Logger.printLog(String.format(\"Error invoking single event '%s' method '%s' in class '%s': %s\", eventName, methodName, className, Arrays.toString(cause.getStackTrace())));\n } catch (IllegalAccessException e) {\n Logger.printLog(String.format(\"Illegal access when invoking single event '%s' in class '%s': %s\", eventName, listener.getClass().getName(), Arrays.toString(e.getStackTrace())));\n }\n }\n }\n }\n }\n return null;\n }\n\n /**\n * Send an event to all listeners\n * @param eventName event name\n */\n public static void invokeEvent(String eventName) {\n invokeEvent(eventName, (Object[])null);\n }\n\n /**\n * Send an event to all listeners\n * @param eventName event name\n * @param args event arguments\n */\n public static void invokeEvent(String eventName, Object... args) {\n for (Object listener : listeners) {\n for (Method method : listener.getClass().getDeclaredMethods()) {\n if (method.isAnnotationPresent(SubscribeEvent.class)) {\n SubscribeEvent annotation = method.getAnnotation(SubscribeEvent.class);\n if (annotation.eventName().equals(eventName) && isMethodCompatible(method, eventName, args)) {\n try {\n method.setAccessible(true);\n method.invoke(listener, args);\n } catch (InvocationTargetException e) {\n Throwable cause = e.getCause();\n String className = listener.getClass().getName();\n String methodName = method.getName();\n Logger.printLog(String.format(\"Error invoking event '%s' method '%s' in class '%s': %s\", eventName, methodName, className, Arrays.toString(cause.getStackTrace())));\n } catch (IllegalAccessException e) {\n Logger.printLog(String.format(\"Illegal access when invoking event '%s' in class '%s': %s\", eventName, listener.getClass().getName(), Arrays.toString(e.getStackTrace())));\n }\n }\n }\n }\n }\n }\n\n /**\n * Checking the called method to ensure that the arguments and their types match correctly\n * @param method called method\n * @param eventName event name\n * @param args event arguments\n * @return true - check passed, false - check failed\n */\n private static boolean isMethodCompatible(Method method, String eventName, Object[] args) {\n if (args == null || args.length == 0) {\n return method.getParameterCount() == 0;\n }\n\n if (method.getParameterCount() != args.length) {\n Logger.printLog(String.format(\"Number of arguments mismatch when calling event '%s' in method '%s' (class '%s')\",\n eventName, method.getName(), method.getDeclaringClass().getSimpleName()));\n return false;\n }\n\n Class<?>[] parameterTypes = method.getParameterTypes();\n for (int i = 0; i < parameterTypes.length; i++) {\n if (!parameterTypes[i].isInstance(args[i])) {\n String expectedTypeName = parameterTypes[i].getName();\n String receivedTypeName = args[i] == null ? \"null\" : args[i].getClass().getName();\n\n Logger.printLog(String.format(\"Mismatch of passed and received argument types when calling event '%s' in method '%s' (class '%s'). Expected '%s', but got '%s'\",\n eventName, method.getName(), method.getDeclaringClass().getSimpleName(), expectedTypeName, receivedTypeName));\n return false;\n }\n }\n\n return true;\n }\n}" }, { "identifier": "PluginManager", "path": "src/main/java/io/xlorey/FluxLoader/shared/PluginManager.java", "snippet": "@UtilityClass\npublic class PluginManager {\n /**\n * General plugin loader\n */\n private static PluginClassLoader pluginClassLoader;\n\n /**\n * All loaded information about plugins\n * Key: plugin file\n * Value: information about the plugin\n */\n private static final HashMap<File, Metadata> pluginsInfoRegistry = new HashMap<>();\n\n /**\n * Registry of icons of loaded plugins\n * Key: plugin id\n *Value: texture object\n */\n private static final HashMap<String, Texture> pluginIconRegistry = new HashMap<>();\n\n /**\n * Register of loaded plugin controls\n * Key: plugin id\n * Value: Controls widget\n */\n private static final HashMap<String, IControlsWidget> pluginControlsRegistry = new HashMap<>();\n\n /**\n * Register of all loaded client plugins\n * Key: \"entryPoint:ID:Version\"\n * Value: plugin instance\n */\n private static final HashMap<String, Plugin> clientPluginsRegistry = new HashMap<>();\n\n /**\n * Register of all loaded server plugins\n * Key: \"entryPoint:ID:Version\"\n * Value: plugin instance\n */\n private static final HashMap<String, Plugin> serverPluginsRegistry = new HashMap<>();\n\n /**\n * Retrieves the list of loaded client plugins controls\n * @return HashMap containing information about loaded client plugin icons, where the key is the plugin ID.\n * and the value is the corresponding ControlsWidget instance.\n */\n public static HashMap<String, IControlsWidget> getPluginControlsRegistry() {\n return pluginControlsRegistry;\n }\n\n /**\n * Retrieves the list of loaded client plugins icons\n * @return HashMap containing information about loaded client plugin icons, where the key is the plugin ID.\n * and the value is the corresponding texture instance.\n */\n public static HashMap<String, Texture> getPluginIconRegistry() {\n return pluginIconRegistry;\n }\n\n /**\n * Retrieves the list of loaded client plugins\n * @return A HashMap containing information about loaded client plugins, where the key is \"entryPoint:ID:Version\"\n * and the value is the corresponding Plugin instance.\n */\n public static HashMap<String, Plugin> getLoadedClientPlugins() {\n return clientPluginsRegistry;\n }\n /**\n * Retrieves the list of loaded server plugins\n * @return A HashMap containing information about loaded server plugins, where the key is \"entryPoint:ID:Version\"\n * and the value is the corresponding Plugin instance.\n */\n public static HashMap<String, Plugin> getLoadedServerPlugins() {\n return serverPluginsRegistry;\n }\n\n /**\n * Initializing the class loader\n */\n public static void initializePluginClassLoader() {\n List<URL> urls = new ArrayList<>();\n pluginClassLoader = new PluginClassLoader(urls.toArray(new URL[0]), PluginManager.class.getClassLoader());\n }\n\n /**\n * Starts the execution of all plugins specified in the past registry.\n * This method iterates through all the plugins in the provided registry and calls their onExecute method.\n * During the execution of each plugin, messages about the start and successful completion are logged.\n * If exceptions occur during plugin execution, the method also logs the corresponding errors.\n * @param pluginsRegistry A registry of plugins, each of which will be executed.\n */\n public static void executePlugins(HashMap<String, Plugin> pluginsRegistry) {\n for (Map.Entry<String, Plugin> entry : pluginsRegistry.entrySet()) {\n Plugin pluginInstance = entry.getValue();\n String pluginId = pluginInstance.getMetadata().getId();\n\n Logger.printLog(String.format(\"Plugin '%s' started trying to execute...\", pluginId));\n\n try {\n pluginInstance.onExecute();\n } catch (Exception e) {\n Logger.printLog(String.format(\"Plugin '%s' failed to execute correctly due to: %s\", pluginId, e));\n }\n\n Logger.printLog(String.format(\"Plugin '%s' has been successfully executed. All internal processes have been successfully launched.\", pluginId));\n }\n }\n\n /**\n * Stops all plugins specified in the past registry.\n * This method iterates through all the plugins in the provided registry and calls their onTerminate method.\n * During the process of stopping each plugin, messages about the start and successful completion are logged.\n * If exceptions occur when stopping the plugin, the method also logs the corresponding errors.\n * @param pluginsRegistry A registry of plugins, each of which will be stopped.\n */\n public static void terminatePlugins(HashMap<String, Plugin> pluginsRegistry) {\n for (Map.Entry<String, Plugin> entry : pluginsRegistry.entrySet()) {\n Plugin pluginInstance = entry.getValue();\n String pluginId = pluginInstance.getMetadata().getId();\n\n Logger.printLog(String.format(\"Plugin '%s' is starting to shut down...\", pluginId));\n\n try {\n pluginInstance.onTerminate();\n } catch (Exception e) {\n Logger.printLog(String.format(\"Plugin '%s' failed to shut down correctly due to: %s\", pluginId, e));\n }\n\n Logger.printLog(String.format(\"Plugin '%s' has been successfully terminated. All internal processes have been completed.\", pluginId));\n }\n }\n\n /**\n * Loading plugins into the game context\n * @param isClient flag indicating whether loading occurs on the client side\n * @throws IOException in cases of input/output problems\n */\n public static void loadPlugins(boolean isClient) throws Exception {\n Logger.printLog(\"Loading plugins into the environment...\");\n\n /*\n Checking the presence of a folder for plugins and validating it\n */\n checkPluginFolder();\n\n /*\n Getting a list of plugins\n */\n ArrayList<File> pluginFiles = getPluginFiles();\n\n /*\n Searching for plugins in a directory\n */\n for (File plugin : pluginFiles) {\n Metadata metadata = Metadata.getInfoFromFile(plugin);\n\n if (metadata == null) {\n Logger.printLog(String.format(\"No metadata found for potential plugin '%s'. Skipping...\", plugin.getName()));\n continue;\n }\n pluginsInfoRegistry.put(plugin, metadata);\n }\n\n /*\n Checking for dependency availability and versions\n */\n dependencyVerification();\n\n /*\n Sorting plugins by load order and Circular dependency check\n */\n ArrayList<File> sortedOrder = sortPluginsByLoadOrder();\n\n /*\n Loading the plugin\n */\n for (File plugin : sortedOrder) {\n Metadata metadata = pluginsInfoRegistry.get(plugin);\n\n List<String> clientEntryPoints = metadata.getEntrypoints().get(\"client\");\n List<String> serverEntryPoints = metadata.getEntrypoints().get(\"server\");\n\n // Checking for empty entry points\n if (!isValidEntryPoints(clientEntryPoints, \"client\", metadata) || !isValidEntryPoints(serverEntryPoints, \"server\", metadata)) {\n continue;\n }\n\n // creating a folder for configs\n File configFolder = metadata.getConfigFolder();\n if (!configFolder.exists()) {\n try {\n configFolder.mkdir();\n } catch (Exception e) {\n e.printStackTrace();\n Logger.printLog(String.format(\"An error occurred while creating the config folder for plugin '%s'\", metadata.getId()));\n }\n }\n\n initializePluginClassLoader();\n\n // Creating a URL for the plugin\n URL pluginUrl = plugin.toURI().toURL();\n PluginClassLoader classLoader = new PluginClassLoader(new URL[]{pluginUrl}, pluginClassLoader);\n\n loadEntryPoints(true, clientEntryPoints, clientPluginsRegistry, metadata, classLoader);\n loadEntryPoints(false, serverEntryPoints, serverPluginsRegistry, metadata, classLoader);\n\n if (isClient) {\n String controlsClassName = metadata.getControlsEntrypoint();\n if (controlsClassName != null && !controlsClassName.isEmpty()) {\n Class<?> controlsClass = Class.forName(controlsClassName, true, classLoader);\n IControlsWidget controlsInstance = (IControlsWidget) controlsClass.getDeclaredConstructor().newInstance();\n\n pluginControlsRegistry.put(metadata.getId(), controlsInstance);\n }\n\n String iconPath = metadata.getIcon();\n URL iconUrl = classLoader.getResource(iconPath);\n\n if (iconUrl != null) {\n try (BufferedInputStream bis = new BufferedInputStream(iconUrl.openStream())) {\n Texture texture = new Texture(iconPath, bis, true);\n pluginIconRegistry.put(metadata.getId(), texture);\n } catch (IOException e) {\n e.printStackTrace();\n throw new Exception(String.format(\"Failed to load plugin '%s' icon texture\", metadata.getId()));\n }\n }\n }\n }\n }\n\n /**\n * Loads plugin input points using the provided class loader.\n * This method is designed to load and initialize plugin classes based on lists of input points.\n * For each input point in the list, the method tries to load the corresponding class, create an instance\n * plugin and add it to the specified plugin registry. In case of errors during class loading process\n * or creating instances, the method throws an exception.\n * @param isClient flag indicating whether client or server entry points are loaded\n * @param entryPoints List of string identifiers of the plugin classes' entry points.\n * @param targetRegistry The registry to which loaded plugin instances should be added.\n * @param metadata Plugin information used to log and associate instances with plugin data.\n * @param classLoader {@link PluginClassLoader} for loading plugin classes.\n * @throws Exception If errors occur while loading classes or creating instances.\n */\n private static void loadEntryPoints(boolean isClient, List<String> entryPoints, HashMap<String, Plugin> targetRegistry, Metadata metadata, PluginClassLoader classLoader) throws Exception {\n String pluginType = isClient ? \"client\" : \"server\";\n\n if (entryPoints == null || entryPoints.isEmpty()) {\n Logger.printLog(String.format(\"There are no %s entry points for plugin '%s'\", pluginType, metadata.getId()));\n return;\n }\n\n int totalEntryPoints = entryPoints.size();\n int currentEntryPointIndex = 0;\n\n for (String entryPoint : entryPoints) {\n currentEntryPointIndex++;\n\n Class<?> pluginClass = Class.forName(entryPoint, true, classLoader);\n Plugin pluginInstance = (Plugin) pluginClass.getDeclaredConstructor().newInstance();\n\n pluginInstance.setMetadata(metadata);\n\n Logger.printLog(String.format(\"Loading %s plugin entry point %d/%d: '%s'(ID: '%s', Version: %s)...\",\n pluginType, currentEntryPointIndex, totalEntryPoints, metadata.getName(), metadata.getId(), metadata.getVersion()));\n\n pluginInstance.onInitialize();\n\n String registryKey = String.format(\"%s:%s:%s\", entryPoint, metadata.getId(), metadata.getVersion());\n\n if (!targetRegistry.containsKey(registryKey)) {\n targetRegistry.put(registryKey, pluginInstance);\n }\n\n EventManager.subscribe(pluginInstance);\n }\n }\n\n /**\n * Checks for the presence of a list of entry points for the plugin.\n * This method is used to check if entry points are defined for a plugin.\n * If the list of entry points is null, the method writes a message about skipping loading the plugin\n * and returns false. An empty list is considered valid.\n *\n * @param entryPoints List of plugin entry points. Can be null.\n * @param type The type of entry points (e.g. \"client\" or \"server\").\n * @param metadata Plugin information used for logging.\n * @return true if the list of entry points is not null, false otherwise.\n */\n private static boolean isValidEntryPoints(List<String> entryPoints, String type, Metadata metadata) {\n if (entryPoints == null) {\n Logger.printLog(String.format(\"Entry points list is null for %s plugin '%s' (ID: '%s', Version: %s). Skipping...\",\n type, metadata.getName(), metadata.getId(), metadata.getVersion()));\n return false;\n }\n return true;\n }\n\n /**\n * Sorts plugins by load order using topological sorting.\n * This method takes into account the dependencies between plugins and arranges them in such a way\n * so that each plugin is loaded after all the plugins it depends on have been loaded.\n *\n * @return List of plugin files, sorted in download order.\n * @throws Exception in case a cyclic dependency or other error is detected.\n */\n private static ArrayList<File> sortPluginsByLoadOrder() throws Exception {\n HashMap<String, List<String>> graph = new HashMap<>();\n HashMap<String, Integer> state = new HashMap<>();\n ArrayList<String> sortedOrder = new ArrayList<>();\n HashMap<String, File> pluginFilesMap = new HashMap<>();\n\n // Initializing the graph and states\n for (Map.Entry<File, Metadata> entry : pluginsInfoRegistry.entrySet()) {\n String pluginId = entry.getValue().getId();\n pluginFilesMap.put(pluginId, entry.getKey());\n state.put(pluginId, 0); // 0 - not visited, 1 - on the stack, 2 - visited\n\n if (!pluginId.equals(\"project-zomboid\") && !pluginId.equals(\"flux-loader\")) {\n graph.putIfAbsent(pluginId, new ArrayList<>());\n\n for (String dependency : entry.getValue().getDependencies().keySet()) {\n if (!dependency.equals(\"project-zomboid\") && !dependency.equals(\"flux-loader\")) {\n graph.putIfAbsent(dependency, new ArrayList<>());\n graph.get(dependency).add(pluginId);\n }\n }\n }\n }\n\n // Topological sorting and checking for cyclic dependencies\n for (String pluginId : graph.keySet()) {\n if (state.get(pluginId) == 0 && topologicalSortDFS(pluginId, graph, state, sortedOrder)) {\n throw new Exception(\"Cyclic dependency detected: \" + pluginId);\n }\n }\n\n // Convert to file list\n ArrayList<File> sortedPluginFiles = new ArrayList<>();\n for (String pluginId : sortedOrder) {\n sortedPluginFiles.add(pluginFilesMap.get(pluginId));\n }\n\n return sortedPluginFiles;\n }\n\n /**\n * Helps perform topological sorting using the DFS algorithm.\n * This method also checks for circular dependencies between plugins.\n *\n * @param current The current node being processed (plugin ID).\n * @param graph Dependency graph, where the key is the plugin identifier and the value is a list of dependencies.\n * @param state A dictionary to keep track of the state of each node during the traversal process.\n * @param sortedOrder A list to store the sorted order of nodes.\n * @return Returns `true` if no circular dependencies are found, `false` otherwise.\n */\n private static boolean topologicalSortDFS(String current, HashMap<String, List<String>> graph, HashMap<String, Integer> state, ArrayList<String> sortedOrder) {\n if (state.get(current) == 1) {\n return true; // Cyclic dependency detected\n }\n if (state.get(current) == 2) {\n return false; // Already visited\n }\n\n state.put(current, 1); // Mark the node as in the stack\n for (String neighbour : graph.getOrDefault(current, new ArrayList<>())) {\n if (topologicalSortDFS(neighbour, graph, state, sortedOrder)) {\n return true;\n }\n }\n state.put(current, 2); // Mark the node as visited\n sortedOrder.add(0, current);\n\n return false;\n }\n\n /**\n * Checking plugins for their dependencies and ensuring that their versions meet the requirements\n * @throws Exception in case the dependent plugin is not found among those found or its version does not meet the requirements\n */\n private static void dependencyVerification() throws Exception {\n for (Map.Entry<File, Metadata> entry : pluginsInfoRegistry.entrySet()) {\n Map<String, String> dependencies = entry.getValue().getDependencies();\n\n for (Map.Entry<String, String> depEntry : dependencies.entrySet()) {\n String depId = depEntry.getKey();\n String depVersion = depEntry.getValue();\n\n switch (depId) {\n case \"project-zomboid\" -> {\n if (!VersionChecker.isVersionCompatible(depVersion, Core.getInstance().getVersion())) {\n throw new Exception(String.format(\"Incompatible game version for plugin id '%s'\", entry.getValue().getId()));\n }\n }\n case \"flux-loader\" -> {\n if (!VersionChecker.isVersionCompatible(depVersion, Constants.FLUX_VERSION)) {\n throw new Exception(String.format(\"Incompatible flux-loader version for plugin id '%s'\", entry.getValue().getId()));\n }\n }\n default -> {\n // Checking the presence of the plugin in the directory\n boolean hasPlugin = false;\n\n for (Map.Entry<File, Metadata> checkEntry : pluginsInfoRegistry.entrySet()) {\n String id = checkEntry.getValue().getId();\n String version = checkEntry.getValue().getVersion();\n\n if (depId.equals(id) && VersionChecker.isVersionCompatible(depVersion, version)){\n hasPlugin = true;\n break;\n }\n }\n\n if (!hasPlugin) {\n throw new Exception(String.format(\"Plugin '%s' does not have a dependent plugin '%s' or its version does not meet the requirements\",\n entry.getValue().getId(),\n depId\n ));\n }\n }\n }\n }\n }\n }\n\n /**\n * Finds all JAR plugins in the specified directory.\n * @return List of JAR files.\n */\n public static ArrayList<File> getPluginFiles() {\n ArrayList<File> jarFiles = new ArrayList<>();\n File folder = getPluginsDirectory();\n\n File[] files = folder.listFiles((File pathname) -> pathname.isFile() && pathname.getName().endsWith(\".jar\"));\n if (files != null) {\n Collections.addAll(jarFiles, files);\n }\n\n return jarFiles;\n }\n\n /**\n * Gets the directory for plugins.\n * This method creates and returns a File object that points to the directory\n * defined in the constant Constants.PLUGINS_FOLDER_NAME. Directory in use\n * for storing plugins. The method does not check whether the directory exists or is\n * it is a valid directory; it simply returns a File object with the corresponding path.\n * The folder is checked and validated when loading plugins.\n * @return A File object representing the plugins folder.\n */\n public static File getPluginsDirectory() {\n return new File(Constants.PLUGINS_FOLDER_NAME);\n }\n\n /**\n * Checking for availability and creating a folder for plugins\n * @throws IOException in cases of input/output problems\n */\n private static void checkPluginFolder() throws IOException {\n Logger.printLog(\"Checking for plugins folder...\");\n\n File folder = getPluginsDirectory();\n\n if (!folder.exists()) {\n if (!folder.mkdir()) {\n Logger.printLog(\"Failed to create folder...\");\n }\n }\n\n if (!folder.isDirectory()) {\n throw new IOException(\"Path is not a directory: \" + folder.getPath());\n }\n }\n}" }, { "identifier": "Logger", "path": "src/main/java/io/xlorey/FluxLoader/utils/Logger.java", "snippet": "@UtilityClass\npublic class Logger {\n /**\n * Outputting a message to the console installer\n * @param text message\n */\n public static void printSystem(String text) {\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm:ss\");\n String time = LocalDateTime.now().format(formatter);\n System.out.println(String.format(\"<%s> [%s]: %s\", time, Constants.FLUX_NAME, text));\n }\n\n /**\n * Outputting a message to the console/logs\n * @param text message\n */\n public static void printLog(String text) {\n ZLogger fluxLogger = LoggerManager.getLogger(GameServer.bServer ? \"FluxLog-server\" : \"FluxLog-client\");\n fluxLogger.write(text, \"FluxLogger\");\n }\n\n /**\n * Outputting a message to the console/logs\n * @param logger custom logger\n * @param text message\n */\n public static void printLog(ZLogger logger, String text) {\n logger.write(text);\n }\n\n /**\n * Displaying basic information about the project\n */\n public static void printCredits() {\n int width = 50;\n char symbol = '#';\n printFilledLine(symbol, width);\n printCenteredText(symbol, width, \"\", true);\n printCenteredText(symbol, width, Constants.FLUX_NAME, true);\n printCenteredText(symbol, width, String.format(\"v%s\",Constants.FLUX_VERSION), true);\n printCenteredText(symbol, width, \"\", true);\n printCenteredText(symbol, width, Constants.GITHUB_LINK, true);\n printCenteredText(symbol, width, Constants.DISCORD_LINK, true);\n printCenteredText(symbol, width, \"\", true);\n printFilledLine(symbol, width);\n\n System.out.println();\n }\n\n /**\n * Display a message in the middle with a given line width\n * @param symbol border symbol\n * @param width line width\n * @param text message\n * @param isBordered use boundaries\n */\n public static void printCenteredText(char symbol, int width, String text, boolean isBordered) {\n String border = isBordered ? String.valueOf(symbol) : \"\";\n int textWidth = text.length() + (isBordered ? 2 : 0);\n int leftPadding = (width - textWidth) / 2;\n int rightPadding = width - leftPadding - textWidth;\n\n String paddedString = String.format(\"%s%\" + leftPadding + \"s%s%\" + rightPadding + \"s%s\", border, \"\", text, \"\", border);\n System.out.println(paddedString);\n }\n\n /**\n * Outputting the completed line to the console\n * @param symbol fill character\n * @param width fill width\n */\n public static void printFilledLine(char symbol, int width) {\n System.out.println(symbol + String.format(\"%\" + (width - 2) + \"s\", \"\").replace(' ', symbol) + symbol);\n }\n}" } ]
import io.xlorey.FluxLoader.shared.EventManager; import io.xlorey.FluxLoader.shared.PluginManager; import io.xlorey.FluxLoader.utils.Logger;
7,142
package io.xlorey.FluxLoader.server.core; /** * FluxLoader Core */ public class Core { /** * Initializing the loader * @param serverArgs server boot arguments * @exception Exception in cases of unsuccessful core initialization */ public static void init(String[] serverArgs) throws Exception { boolean isCoop = false; for (String serverArg : serverArgs) { if (serverArg != null) { if (serverArg.equals("-coop")) { Logger.printLog("Launching a co-op server..."); isCoop = true; break; } } } if (!isCoop) Logger.printCredits(); Logger.printLog("FluxLoader Core initialization for the server.."); EventManager.subscribe(new EventsHandler());
package io.xlorey.FluxLoader.server.core; /** * FluxLoader Core */ public class Core { /** * Initializing the loader * @param serverArgs server boot arguments * @exception Exception in cases of unsuccessful core initialization */ public static void init(String[] serverArgs) throws Exception { boolean isCoop = false; for (String serverArg : serverArgs) { if (serverArg != null) { if (serverArg.equals("-coop")) { Logger.printLog("Launching a co-op server..."); isCoop = true; break; } } } if (!isCoop) Logger.printCredits(); Logger.printLog("FluxLoader Core initialization for the server.."); EventManager.subscribe(new EventsHandler());
PluginManager.loadPlugins(false);
1
2023-11-16 09:05:44+00:00
8k
EmonerRobotics/2023Robot
src/main/java/frc/robot/subsystems/drivetrain/Drivetrain.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 double GROUNDH = 0;\n public static final double MIDH = 0.46; \n public static final double TOPH = 1.45;\n public static final double HUMANPH = 1.37;\n public static final double LiftAllowedError = 0.005;\n }\n\n public final class IntakeMeasurements{\n public static final double IntakeClosedD = 0;\n public static final double IntakeHalfOpenD = 3.5;\n public static final double IntakeStraightOpenD = 7.6;\n public static final double IntakeStraightOpenHD = 8;\n public static final double IntakeAllowedError = 0.05;\n }\n\n public final class Limelight{\n public static final double BetweenHuman = 0.85;\n }\n\n public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb ports\n \n //pinomatik aç-kapat kontrolleri\n public static final int SolenoidOnB = 6; //LB\n public static final int SolenoidOffB = 5; //RB\n \n //asansor motor pwm\n public static final int LiftRedline1 = 0;\n \n //asansör motor analog kontrolü\n public static final int LiftControllerC = 5; //sağ yukarı asagı ters cevir\n \n //acili mekanizma neo500 id\n public static final int AngleMechanismId = 9;\n\n //üst sistem mekanizma pozisyon kontrolleri\n public static final int GroundLevelB = 1; //A\n public static final int FirstLevelB = 3; //X\n public static final int HumanPB = 2; //B\n public static final int TopLevelB = 4; //Y\n public static final int MoveLevelB = 9; //sol analog butonu\n\n //açılı intake kontrolleri\n public static final int AngleController = 1; //sol yukarı aşagı \n }\n\n\n public static final class DriveConstants {\n // Driving Parameters - Note that these are not the maximum capable speeds of\n // the robot, rather the allowed maximum speeds\n public static final double MAX_SPEED_METERS_PER_SECOND = 4.8;\n public static final double MAX_ANGULAR_SPEED = 2 * Math.PI; // radians per second\n\n // Chassis configuration\n public static final double TRACK_WIDTH = Units.inchesToMeters(22.5);\n // Distance between centers of right and left wheels on robot\n public static final double WHEEL_BASE = Units.inchesToMeters(24.5);\n // Distance between front and back wheels on robot\n public static final SwerveDriveKinematics DRIVE_KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(WHEEL_BASE / 2, -TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, -TRACK_WIDTH / 2));\n\n // Angular offsets of the modules relative to the chassis in radians\n public static final double FRONT_LEFT_CHASSIS_ANGULAR_OFFSET = -Math.PI / 2;\n public static final double FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET = 0;\n public static final double REAR_LEFT_CHASSIS_ANGULAR_OFFSET = Math.PI;\n public static final double REAR_RIGHT_CHASSIS_ANGULAR_OFFSET = Math.PI / 2;\n\n // Charge Station Constants\n public static final double CHARGE_TIPPING_ANGLE= Math.toRadians(12);\n public static final double CHARGE_TOLERANCE = Math.toRadians(2.5);\n public static final double CHARGE_MAX_SPEED = 0.8;\n public static final double CHARGE_REDUCED_SPEED = 0.70;\n\n // Delay between reading the gyro and using the value used to aproximate exact angle while spinning (0.02 is one loop)\n public static final double GYRO_READ_DELAY = 0.02;\n\n // SPARK MAX CAN IDs\n public static final int FRONT_LEFT_DRIVING_CAN_ID = 7; //7\n public static final int REAR_LEFT_DRIVING_CAN_ID = 4; //4\n public static final int FRONT_RIGHT_DRIVING_CAN_ID = 10; //10\n public static final int REAR_RIGHT_DRIVING_CAN_ID = 8; //8\n\n public static final int FRONT_LEFT_TURNING_CAN_ID = 2; //2\n public static final int REAR_LEFT_TURNING_CAN_ID = 1; //1\n public static final int FRONT_RIGHT_TURNING_CAN_ID = 3; //3\n public static final int REAR_RIGHT_TURNING_CAN_ID = 6; //6\n\n public static final boolean GYRO_REVERSED = false;\n public static final Rotation3d GYRO_ROTATION = new Rotation3d(0, 0, - Math.PI / 2);\n\n public static final Vector<N3> ODOMETRY_STD_DEV = VecBuilder.fill(0.05, 0.05, 0.01);\n }\n\n\n public static final class ModuleConstants {\n // The MAXSwerve module can be configured with one of three pinion gears: 12T, 13T, or 14T.\n // This changes the drive speed of the module (a pinion gear with more teeth will result in a\n // robot that drives faster).\n public static final int DRIVING_MOTOR_PINION_TEETH = 12;\n\n // Invert the turning encoder, since the output shaft rotates in the opposite direction of\n // the steering motor in the MAXSwerve Module.\n public static final boolean TURNING_ENCODER_INVERTED = true;\n\n // Calculations required for driving motor conversion factors and feed forward\n public static final double DRIVING_MOTOR_FREE_SPEED_RPS = NeoMotorConstants.FREE_SPEED_RPM / 60;\n public static final double WHEEL_DIAMETER_METERS = Units.inchesToMeters(3);\n public static final double WHEEL_CIRCUMFERENCE_METERS = WHEEL_DIAMETER_METERS * Math.PI;\n // 45 teeth on the wheel's bevel gear, 22 teeth on the first-stage spur gear, 15 teeth on the bevel pinion\n public static final double DRIVING_MOTOR_REDUCTION = (45.0 * 22) / (DRIVING_MOTOR_PINION_TEETH * 15);\n public static final double DRIVE_WHEEL_FREE_SPEED_RPS = (DRIVING_MOTOR_FREE_SPEED_RPS * WHEEL_CIRCUMFERENCE_METERS)\n / DRIVING_MOTOR_REDUCTION;\n\n public static final double DRIVING_ENCODER_POSITION_FACTOR = WHEEL_CIRCUMFERENCE_METERS\n / DRIVING_MOTOR_REDUCTION; // meters\n public static final double DRIVING_ENCODER_VELOCITY_FACTOR = (WHEEL_CIRCUMFERENCE_METERS\n / DRIVING_MOTOR_REDUCTION) / 60.0; // meters per second\n\n public static final double TURNING_ENCODER_POSITION_FACTOR = (2 * Math.PI); // radians\n public static final double TURNING_ENCODER_VELOCITY_FACTOR = (2 * Math.PI) / 60.0; // radians per second\n\n public static final double TURNING_ENCODER_POSITION_PID_MIN_INPUT = 0; // radians\n public static final double TURNING_ENCODER_POSITION_PID_MAX_INPUT = TURNING_ENCODER_POSITION_FACTOR; // radians\n\n public static final double DRIVING_P = 0.04;\n public static final double DRIVING_I = 0;\n public static final double DRIVING_D = 0;\n public static final double DRIVING_FF = 1 / DRIVE_WHEEL_FREE_SPEED_RPS;\n public static final double DRIVING_MIN_OUTPUT = -1;\n public static final double DRIVING_MAX_OUTPUT = 1;\n\n public static final double TURNING_P = 2;\n public static final double TURNING_I = 0;\n public static final double TURNING_D = 0;\n public static final double TURNING_FF = 0;\n public static final double TURNING_MIN_OUTPUT = -1;\n public static final double TURNING_MAX_OUTPUT = 1;\n\n public static final CANSparkMax.IdleMode DRIVING_MOTOR_IDLE_MODE = CANSparkMax.IdleMode.kBrake;\n public static final CANSparkMax.IdleMode TURNING_MOTOR_IDLE_MODE = CANSparkMax.IdleMode.kBrake;\n\n public static final int DRIVING_MOTOR_CURRENT_LIMIT = 20; // amps\n public static final int TURNING_MOTOR_CURRENT_LIMIT = 15; // amps\n }\n\n public static final class NeoMotorConstants {\n public static final double FREE_SPEED_RPM = 5676;\n }\n\n public static class FieldConstants {\n public static final double fieldLength = Units.inchesToMeters(651.25);\n public static final double fieldWidth = Units.inchesToMeters(315.5);\n public static final double tapeWidth = Units.inchesToMeters(2.0);\n public static final double aprilTagWidth = Units.inchesToMeters(6.0);\n }\n \n public static class VisionConstants {\n // FIXME: actually measure these constants\n\n public static final Transform3d PHOTONVISION_TRANSFORM = new Transform3d(\n new Translation3d(0.205697, -0.244475, 0.267365),\n new Rotation3d(0, Units.degreesToRadians(15), 0)\n );\n\n public static final Vector<N3> PHOTONVISION_STD_DEV = VecBuilder.fill(0.7, 0.7, 0.5);\n\n public static final Vector<N3> LIMELIGHT_STD_DEV = VecBuilder.fill(0.9, 0.9, 0.9);\n\n public static final double AMBIGUITY_FILTER = 0.05;\n }\n\n public static final class AutoConstants {\n public static final HashMap<String, Command> autoEventMap = new HashMap<>();\n public static final double MAX_SPEED_METERS_PER_SECOND = 3;\n public static final double MAX_ACCELERATION_METERS_PER_SECOND_SQUARED = 2;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND = Math.PI * 2;\n public static final double MAX_ANGULAR_SPEED_RADIANS_PER_SECOND_SQUARED = Math.PI * 2;\n\n public static final double P_TRANSLATION_PATH_CONTROLLER = 1;\n public static final double P_THETA_PATH_CONTROLLER = 1;\n\n public static final double P_TRANSLATION_POINT_CONTROLLER = 4;\n public static final double P_THETA_POINT_CONTROLLER = 6;\n\n public static final double TRANSLATION_TOLERANCE = 0.02;\n public static final Rotation2d THETA_TOLERANCE = Rotation2d.fromDegrees(1);\n\n // Constraint for the motion profiled robot angle controller\n public static final TrapezoidProfile.Constraints THETA_CONTROLLER_CONSTRAINTS = new TrapezoidProfile.Constraints(\n MAX_ANGULAR_SPEED_RADIANS_PER_SECOND, MAX_ANGULAR_SPEED_RADIANS_PER_SECOND_SQUARED);\n\n public static final Transform2d NODE_HIGH_TRANSFORM = new Transform2d(\n new Translation2d(-1, 0),\n Rotation2d.fromRadians(Math.PI)\n );\n}\n}" }, { "identifier": "DriveConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static final class DriveConstants {\n // Driving Parameters - Note that these are not the maximum capable speeds of\n // the robot, rather the allowed maximum speeds\n public static final double MAX_SPEED_METERS_PER_SECOND = 4.8;\n public static final double MAX_ANGULAR_SPEED = 2 * Math.PI; // radians per second\n\n // Chassis configuration\n public static final double TRACK_WIDTH = Units.inchesToMeters(22.5);\n // Distance between centers of right and left wheels on robot\n public static final double WHEEL_BASE = Units.inchesToMeters(24.5);\n // Distance between front and back wheels on robot\n public static final SwerveDriveKinematics DRIVE_KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(WHEEL_BASE / 2, -TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, TRACK_WIDTH / 2),\n new Translation2d(-WHEEL_BASE / 2, -TRACK_WIDTH / 2));\n\n // Angular offsets of the modules relative to the chassis in radians\n public static final double FRONT_LEFT_CHASSIS_ANGULAR_OFFSET = -Math.PI / 2;\n public static final double FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET = 0;\n public static final double REAR_LEFT_CHASSIS_ANGULAR_OFFSET = Math.PI;\n public static final double REAR_RIGHT_CHASSIS_ANGULAR_OFFSET = Math.PI / 2;\n\n // Charge Station Constants\n public static final double CHARGE_TIPPING_ANGLE= Math.toRadians(12);\n public static final double CHARGE_TOLERANCE = Math.toRadians(2.5);\n public static final double CHARGE_MAX_SPEED = 0.8;\n public static final double CHARGE_REDUCED_SPEED = 0.70;\n\n // Delay between reading the gyro and using the value used to aproximate exact angle while spinning (0.02 is one loop)\n public static final double GYRO_READ_DELAY = 0.02;\n\n // SPARK MAX CAN IDs\n public static final int FRONT_LEFT_DRIVING_CAN_ID = 7; //7\n public static final int REAR_LEFT_DRIVING_CAN_ID = 4; //4\n public static final int FRONT_RIGHT_DRIVING_CAN_ID = 10; //10\n public static final int REAR_RIGHT_DRIVING_CAN_ID = 8; //8\n\n public static final int FRONT_LEFT_TURNING_CAN_ID = 2; //2\n public static final int REAR_LEFT_TURNING_CAN_ID = 1; //1\n public static final int FRONT_RIGHT_TURNING_CAN_ID = 3; //3\n public static final int REAR_RIGHT_TURNING_CAN_ID = 6; //6\n\n public static final boolean GYRO_REVERSED = false;\n public static final Rotation3d GYRO_ROTATION = new Rotation3d(0, 0, - Math.PI / 2);\n\n public static final Vector<N3> ODOMETRY_STD_DEV = VecBuilder.fill(0.05, 0.05, 0.01);\n}" }, { "identifier": "RobotContainer", "path": "src/main/java/frc/robot/RobotContainer.java", "snippet": "public class RobotContainer {\n\n //Limelight\n public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem();\n //Intake\n public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem();\n\n //Pneumatic\n public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem();\n\n //Lift\n public static final LiftSubsystem liftSubsystem = new LiftSubsystem();\n\n\n public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab(\"Drive Settings\");\n public static final ShuffleboardTab autoTab = Shuffleboard.getTab(\"Auto\");\n public static final ShuffleboardTab swerveTab = Shuffleboard.getTab(\"Swerve\");\n public static final Joystick joystick1 = new Joystick(0);\n public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController);\n \n public static final Drivetrain drivetrain = new Drivetrain();\n\n public static final PoseEstimation poseEstimation = new PoseEstimation();\n\n public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>();\n\n public static Field2d field = new Field2d();\n public static Field2d nodeSelector = new Field2d();\n\n private final FieldObject2d startingPosition = field.getObject(\"Starting Position\");\n private final FieldObject2d autoBalanceStartingPosition = field.getObject(\"Auto Balance Starting Position\");\n\n private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1);\n private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain);\n \n public static SendableChooser<String> autoSelector;\n\n //private static AutoElevator autoElevator;\n \n\n /** The container for the robot. Contains subsystems, OI devices, and commands. */\n public RobotContainer() {\n\n //autoElevator = new AutoElevator(liftSubsystem, 0);\n //Intake\n intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, \n () -> -joystick2.getRawAxis(IntakeConstants.AngleController)));\n\n //Pneumatic\n //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true));\n\n //Lift\n liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5)));\n\n\n if (!DriverStation.isFMSAttached()) {\n PathPlannerServer.startServer(5811);\n }\n\n drivetrain.setDefaultCommand(driveCommand);\n\n if (autoBalanceStartingPosition.getPoses().isEmpty()) {\n autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d())));\n }\n\n configureBindings();\n\n autoSelector = new SendableChooser<>();\n\n autoSelector.setDefaultOption(\"grid1\", \"grid1\"); // 1 kup en yukari kisa taxi\n //autoSelector.setDefaultOption(\"grid2\", \"grid2\"); // 1 kup en yukari kisa taxi denge\n\n //autoSelector.setDefaultOption(\"grid3\", \"grid3\"); // 1 kup en yukari ortadan denge\n //autoSelector.setDefaultOption(\"grid4\", \"grid4\"); //1 kup en yukari uzun taxi denge\n //autoSelector.setDefaultOption(\"grid5\", \"grid5\"); //1 kup en yukari uzun taxi \n }\n\n \n\n \n\n /**\n * Use this method to define your trigger->command mappings. Triggers can be created via the\n * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary\n * predicate, or via the named factories in {@link\n * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link\n * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller\n * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight\n * joysticks}.\n */\n private void configureBindings() {\n\n //setPoint type is inches\n //limelight sets 111 cm\n new JoystickButton(joystick1, 2).\n whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive));\n\n \n //with Y or 4 button goes to the top\n new JoystickButton(joystick2, IntakeConstants.TopLevelB).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT)));\n\n //with B or 2 button goes to the human closes intake and goes to down\n new JoystickButton(joystick2, IntakeConstants.HumanPB).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.HUMANPH , ElevatorPosition.HUMANP),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenHD, IntakePosition.STRAIGHTHD),\n new PneumaticCommand(pneumaticSubsystem, true, false),\n new WaitCommand(1),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED),\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH , ElevatorPosition.GROUND)));\n\n //with A or 1 button goes to the down\n new JoystickButton(joystick2, IntakeConstants.GroundLevelB).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED),\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND)\n ));\n\n new JoystickButton(joystick2, 3).\n toggleOnTrue(new SequentialCommandGroup(\n new AutoElevator(liftSubsystem, Constants.LiftMeasurements.MIDH, ElevatorPosition.MIDDLE),\n new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeHalfOpenD, IntakePosition.HALF)\n ));\n\n\n\n\n //Pneumatic\n new JoystickButton(joystick2, IntakeConstants.SolenoidOnB).\n onTrue(new PneumaticCommand(pneumaticSubsystem, true, false)); //aciyor\n\n new JoystickButton(joystick2, IntakeConstants.SolenoidOffB).\n onTrue(new PneumaticCommand(pneumaticSubsystem, false, true)); //kapatiyor\n\n // Pose Estimation\n \n new JoystickButton(joystick1, 6)\n .onTrue(new InstantCommand(driveCommand::resetFieldOrientation));\n new JoystickButton(joystick1, 7)\n .onTrue(new InstantCommand(() -> poseEstimation.resetPose(\n new Pose2d(\n poseEstimation.getEstimatedPose().getTranslation(),\n new Rotation2d())))); \n\n // Driving \n \n new JoystickButton(joystick1, 1)\n .whileTrue(new RunCommand(\n drivetrain::setX,\n drivetrain)); \n\n\n new JoystickButton(joystick1, 3)\n .whileTrue(autoBalanceCommand);\n \n }\n\n public Command getAutonomousCommand() {\n Pose2d startingPose = startingPosition.getPose();\n return new SequentialCommandGroup(\n new InstantCommand(() -> poseEstimation.resetPose(startingPose)),\n new OnePieceCharge(),\n AutoCommand.makeAutoCommand(drivetrain, poseEstimation, autoSelector.getSelected()),\n new InstantCommand(() -> poseEstimation.resetPose(startingPose))\n );\n }\n\n public static Drivetrain getSwerveSubsystem() {\n return drivetrain;\n }\n\n public static LiftSubsystem getLiftSubsystem(){\n return liftSubsystem;\n }\n\n public static IntakeSubsystem getIntakeSubsystem(){\n return intakeSubsystem;\n }\n\n public static PneumaticSubsystem getPneumaticSubsystem(){\n return pneumaticSubsystem;\n }\n}" } ]
import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Rotation3d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.wpilibj.RobotBase; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.Constants.DriveConstants; import frc.robot.RobotContainer; import java.util.ArrayList; import java.util.List;
6,490
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems.drivetrain; public class Drivetrain extends SubsystemBase { // Create MAXSwerveModules private final SwerveModules swerveModules; // The gyro sensor private final Gyro gyro; /** * Creates a new DriveSubsystem. */ public Drivetrain() { if (RobotBase.isSimulation()) { this.swerveModules = new SwerveModules( new SIMSwerveModule(DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET), new SIMSwerveModule(DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET), new SIMSwerveModule(DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET), new SIMSwerveModule(DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET) ); } else { this.swerveModules = new SwerveModules( new MAXSwerveModule( DriveConstants.FRONT_LEFT_DRIVING_CAN_ID, DriveConstants.FRONT_LEFT_TURNING_CAN_ID, DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET ), new MAXSwerveModule( DriveConstants.FRONT_RIGHT_DRIVING_CAN_ID, DriveConstants.FRONT_RIGHT_TURNING_CAN_ID, DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET ), new MAXSwerveModule( DriveConstants.REAR_LEFT_DRIVING_CAN_ID, DriveConstants.REAR_LEFT_TURNING_CAN_ID, DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET ), new MAXSwerveModule( DriveConstants.REAR_RIGHT_DRIVING_CAN_ID, DriveConstants.REAR_RIGHT_TURNING_CAN_ID, DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET ) ); } gyro = (RobotBase.isReal() ? new NavXGyro() : new SIMGyro(swerveModules)); //RobotContainer.swerveTab.addNumber("Front Left", swerveModules.frontLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Front Right", swerveModules.frontRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Back Left", swerveModules.rearLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Back Right", swerveModules.rearRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Gyro", () -> gyro.getAngle().getRadians()).withWidget(BuiltInWidgets.kGraph); } @Override public void periodic() { RobotContainer.poseEstimation.updateOdometry( getRotation(), getModulePositions() ); gyro.update(); swerveModules.update(); logModuleStates("Swerve State", swerveModules.getStates().asArray()); logModuleStates("Swerve Set State", new SwerveModuleState[]{ swerveModules.frontLeft.getSetState(), swerveModules.frontRight.getSetState(), swerveModules.rearLeft.getSetState(), swerveModules.rearRight.getSetState() }); SmartDashboard.putNumberArray("Swerve Module Distance", new double[] {
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems.drivetrain; public class Drivetrain extends SubsystemBase { // Create MAXSwerveModules private final SwerveModules swerveModules; // The gyro sensor private final Gyro gyro; /** * Creates a new DriveSubsystem. */ public Drivetrain() { if (RobotBase.isSimulation()) { this.swerveModules = new SwerveModules( new SIMSwerveModule(DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET), new SIMSwerveModule(DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET), new SIMSwerveModule(DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET), new SIMSwerveModule(DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET) ); } else { this.swerveModules = new SwerveModules( new MAXSwerveModule( DriveConstants.FRONT_LEFT_DRIVING_CAN_ID, DriveConstants.FRONT_LEFT_TURNING_CAN_ID, DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET ), new MAXSwerveModule( DriveConstants.FRONT_RIGHT_DRIVING_CAN_ID, DriveConstants.FRONT_RIGHT_TURNING_CAN_ID, DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET ), new MAXSwerveModule( DriveConstants.REAR_LEFT_DRIVING_CAN_ID, DriveConstants.REAR_LEFT_TURNING_CAN_ID, DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET ), new MAXSwerveModule( DriveConstants.REAR_RIGHT_DRIVING_CAN_ID, DriveConstants.REAR_RIGHT_TURNING_CAN_ID, DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET ) ); } gyro = (RobotBase.isReal() ? new NavXGyro() : new SIMGyro(swerveModules)); //RobotContainer.swerveTab.addNumber("Front Left", swerveModules.frontLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Front Right", swerveModules.frontRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Back Left", swerveModules.rearLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Back Right", swerveModules.rearRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph); //RobotContainer.swerveTab.addNumber("Gyro", () -> gyro.getAngle().getRadians()).withWidget(BuiltInWidgets.kGraph); } @Override public void periodic() { RobotContainer.poseEstimation.updateOdometry( getRotation(), getModulePositions() ); gyro.update(); swerveModules.update(); logModuleStates("Swerve State", swerveModules.getStates().asArray()); logModuleStates("Swerve Set State", new SwerveModuleState[]{ swerveModules.frontLeft.getSetState(), swerveModules.frontRight.getSetState(), swerveModules.rearLeft.getSetState(), swerveModules.rearRight.getSetState() }); SmartDashboard.putNumberArray("Swerve Module Distance", new double[] {
swerveModules.frontLeft.getPosition().distanceMeters / Constants.ModuleConstants.WHEEL_CIRCUMFERENCE_METERS,
0
2023-11-18 14:02:20+00:00
8k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/mobs/builder/dragons/abilities/RushAbility.java
[ { "identifier": "EntityHelper", "path": "src/main/java/com/sweattypalms/skyblock/core/helpers/EntityHelper.java", "snippet": "public class EntityHelper {\n\n public static void equipArmor(EntityLiving entityLiving, SkyblockItemType[] armorSlots, Material armor) {\n LivingEntity entity = (LivingEntity) entityLiving.getBukkitEntity();\n EntityEquipment equipment = entity.getEquipment();\n assert equipment != null;\n\n for (SkyblockItemType armorSlot : armorSlots) {\n Material specificArmorMaterial = getArmorMaterial(armor, armorSlot);\n ItemStack armorPiece = new ItemStack(specificArmorMaterial);\n\n switch (armorSlot) {\n case HELMET -> equipment.setHelmet(armorPiece);\n case CHESTPLATE -> equipment.setChestplate(armorPiece);\n case LEGGINGS -> equipment.setLeggings(armorPiece);\n case BOOTS -> equipment.setBoots(armorPiece);\n }\n }\n }\n\n public static void equipAllArmor(EntityLiving entityLiving, Material armor) {\n equipArmor(entityLiving, new SkyblockItemType[]{SkyblockItemType.HELMET, SkyblockItemType.CHESTPLATE, SkyblockItemType.LEGGINGS, SkyblockItemType.BOOTS}, armor);\n }\n\n public static Material getArmorMaterial(Material baseMaterial, SkyblockItemType armorType) {\n String baseMaterialName = baseMaterial.name().split(\"_\")[0];\n return Material.valueOf(baseMaterialName + \"_\" + armorType.name());\n }\n\n public static void equipItem(LivingEntity entity, SkyblockItemType armorSlot, ItemStack item) {\n EntityEquipment equipment = entity.getEquipment();\n assert equipment != null;\n\n switch (armorSlot) {\n case HELMET -> equipment.setHelmet(item);\n case CHESTPLATE -> equipment.setChestplate(item);\n case LEGGINGS -> equipment.setLeggings(item);\n case BOOTS -> equipment.setBoots(item);\n default -> equipment.setItemInHand(item);\n }\n }\n\n public static void equipItem(EntityLiving entity, SkyblockItemType armorSlot, ItemStack item) {\n equipItem((LivingEntity) entity.getBukkitEntity(), armorSlot, item);\n }\n\n /**\n * <h3>Make sure to null check.</h3>\n *\n * @param livingEnt The entity for which u want the closest player.\n * @return The closest player or null if no player was found.\n */\n public static Player getClosestPlayer(Entity livingEnt) {\n final double[] distance = {Double.MAX_VALUE};\n Player[] target = {null};\n List<Player> possibleTarget = livingEnt.getWorld()\n .getEntitiesByClass(Player.class).stream().toList();\n\n possibleTarget.forEach(player -> {\n if (livingEnt.getLocation().distance(player.getLocation()) < distance[0]) { // player.getGameMode().equals(GameMode.SURVIVAL) &&\n distance[0] = livingEnt.getLocation().distance(player.getLocation());\n target[0] = player;\n }\n });\n return target[0];\n }\n}" }, { "identifier": "MathHelper", "path": "src/main/java/com/sweattypalms/skyblock/core/helpers/MathHelper.java", "snippet": "public class MathHelper {\n\n /**\n * Lerp between two locations\n *\n * @param start Start location\n * @param end End location\n * @param t % between start and end\n * @return Vector of the lerped location\n */\n public static Vector linearInterpolation(Vector start, Vector end, double t) {\n double x = start.getX() + t * (end.getX() - start.getX());\n double y = start.getY() + t * (end.getY() - start.getY());\n double z = start.getZ() + t * (end.getZ() - start.getZ());\n return new Vector(x, y, z);\n }\n\n public static void spiralParticles(LivingEntity entity, double f, double delta, ParticleEffect particle) {\n Location eyeLocation = entity.getEyeLocation();\n\n new BukkitRunnable() {\n final int stepsPerTick = 5;\n int step = 0;\n\n @Override\n public void run() {\n for (int i = 0; i < stepsPerTick; i++) {\n if (step >= 60) {\n this.cancel();\n return;\n }\n\n double angle = step * 6;\n double radius = f + (delta / 60) * step;\n double forward = (4 / 60f) * step;\n\n double x = radius * Math.cos(angle);\n double z = radius * Math.sin(angle);\n\n Vector v = new Vector(x, 0, z);\n rotateAroundAxisX(v, eyeLocation.getPitch() - 90);\n Vector v2 = new Vector(v.getX(), v.getY(), v.getZ());\n rotateAroundAxisY(v2, eyeLocation.getYaw());\n\n Location loc = eyeLocation.clone().add(v2.getX(), v2.getY(), v2.getZ()).add(eyeLocation.clone().getDirection().multiply(0.5));\n loc = loc.add(loc.getDirection().multiply(forward));\n particle.display(0,0,0,0,0,loc,loc.getWorld().getPlayers());\n\n step++;\n }\n }\n }.runTaskTimerAsynchronously(SkyBlock.getInstance(), 0L, 1L);\n }\n\n private static Vector rotateAroundAxisX(Vector v, double angle) {\n angle = Math.toRadians(angle);\n double y, z, cos, sin;\n cos = Math.cos(angle);\n sin = Math.sin(angle);\n y = v.getY() * cos - v.getZ() * sin;\n z = v.getY() * sin + v.getZ() * cos;\n return v.setY(y).setZ(z);\n }\n\n private static Vector rotateAroundAxisY(Vector v, double angle) {\n angle = -angle;\n angle = Math.toRadians(angle);\n double x, z, cos, sin;\n cos = Math.cos(angle);\n sin = Math.sin(angle);\n x = v.getX() * cos + v.getZ() * sin;\n z = v.getX() * -sin + v.getZ() * cos;\n return v.setX(x).setZ(z);\n }\n}" }, { "identifier": "PlaceholderFormatter", "path": "src/main/java/com/sweattypalms/skyblock/core/helpers/PlaceholderFormatter.java", "snippet": "public class PlaceholderFormatter {\n private static final DecimalFormat decimalFormat = new DecimalFormat(\"#,###\");\n\n /**\n * Formats all the placeholders in a string.\n * ex. \"$cHello\" -> \"§cHello\"\n * @param s string to format\n * @return formatted string\n */\n public static String format(String s) {\n return s.replace(\"$\", \"§\");\n }\n public static List<String> format(List<String> s) {\n s = new ArrayList<>(s); // Create mutable copy\n s.replaceAll(PlaceholderFormatter::format);\n return s;\n }\n public static String capitalize(String s) {\n return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();\n }\n\n /**\n * Formats a double to a string with 1 decimal place.\n * ex) 1.97349873 -> \"1.9\n * @param v1 double to format\n * @return formatted string\n */\n public static String formatDouble(double v1) {\n return formatDouble(v1, 1);\n }\n\n /**\n * Formats a double to a string with a specified number of decimal places.\n * ex) 1.97349873, 3 -> \"1.973\"\n * @param v1 double to format\n * @param decimalPlaces number of decimal places\n * @return formatted string\n */\n public static String formatDouble(double v1, int decimalPlaces) {\n String format = \"%.\" + decimalPlaces + \"f\";\n return String.format(format, v1).replace(\".0\", \"\");\n }\n\n public static String formatDecimalCSV(double v1) {\n return decimalFormat.format(v1);\n }\n\n public static String compactNumber(int var1) {\n String[] units = {\"\", \"K\", \"M\", \"B\"};\n int unitIndex = 0;\n\n double value = var1;\n while (value >= 1000 && unitIndex < units.length - 1) {\n value /= 1000;\n unitIndex++;\n }\n\n BigDecimal numberBigDecimal = new BigDecimal(value);\n numberBigDecimal = numberBigDecimal.setScale(1, RoundingMode.HALF_EVEN);\n String formattedValue = numberBigDecimal.stripTrailingZeros().toPlainString();\n\n return formattedValue + units[unitIndex];\n }\n\n /**\n * Formats a time in seconds to a string in the format \"mm:ss\"\n * ex) xxx -> \"02:03\"\n * @param time time in seconds\n * @return formatted time string\n */\n public static String formatTime(long time) {\n long minutes = time / 60;\n long seconds = time % 60;\n return String.format(\"%02d:%02d\", minutes, seconds);\n }\n\n public static String toRomanNumeral(int num) {\n if (num <= 0 || num > 3999) {\n throw new IllegalArgumentException(\"Number out of range for Roman numerals\");\n }\n\n String[] M = {\"\", \"M\", \"MM\", \"MMM\"};\n String[] C = {\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"};\n String[] X = {\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"};\n String[] I = {\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"};\n\n return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10];\n }\n\n}" }, { "identifier": "DragonStage", "path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/dragons/DragonStage.java", "snippet": "public class DragonStage {\n\n final List<Vector> path;\n final double speed;\n\n public DragonStage(List<Vector> path, double speed) {\n if(path.size() != 4 && path.size() != 2) throw new IllegalArgumentException(\"Path must be 2 or 4 points\");\n this.path = path;\n this.speed = speed;\n }\n\n public Vector getPoint(double t) {\n\n if (path.size() == 2){\n return MathHelper.linearInterpolation(path.get(0), path.get(1), t);\n }\n\n double u = 1 - t;\n double tt = t * t;\n double uu = u * u;\n double uuu = uu * u;\n double ttt = tt * t;\n\n Vector p = path.get(0).clone().multiply(uuu);\n p.add(path.get(1).clone().multiply(3 * uu * t));\n p.add(path.get(2).clone().multiply(3 * u * tt));\n p.add(path.get(3).clone().multiply(ttt));\n\n return p;\n }\n}" }, { "identifier": "EnderDragon", "path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/dragons/EnderDragon.java", "snippet": "public abstract class EnderDragon extends EntityEnderDragon implements ISkyblockMob, IRegionEntity, IEndDragon {\n private final SkyblockMob skyblockMob;\n private final List<DragonStage> stages;\n\n @Getter\n @Setter\n private boolean moving = true;\n private double visualizePathTick = 0;\n @Setter\n private double t = 0.0; // 0 ~ 1, to control the linear motion\n @Getter\n @Setter\n private int currentStageIndex = 0;\n @Getter\n @Setter\n private DragonStage currentStage;\n\n @Getter\n private final Random random = new Random();\n\n @Setter\n private IDragonAbility ability = null;\n private final List<IDragonAbility> abilities = List.of(\n new FireballAbility(this),\n new RushAbility(this)\n );\n\n public EnderDragon(Location location, SkyblockMob skyblockMob) {\n super(((CraftWorld) location.getWorld()).getHandle());\n this.skyblockMob = skyblockMob;\n this.skyblockMob\n .setMaxHealth(getMaxDragonHealth())\n .setDamage(getDragonDamage())\n .setCustomName(getDragonName())\n ;\n\n this.skyblockMob.setCustomNameVisible(false);\n\n this.stages = getDragonStages();\n if (stages.isEmpty()) throw new IllegalStateException(\"No stages found for dragon \" + getDragonName());\n currentStage = stages.get(0);\n }\n\n public void visualizePath() {\n visualizePathTick++;\n if (visualizePathTick % 20 != 0) return;\n visualizePathTick = 0;\n\n for (DragonStage stage : stages) {\n for (double t = 0; t <= 1; t += 0.005) {\n Vector position = stage.getPoint(t);\n Location loc = new Location(getBukkitEntity().getWorld(), position.getX(), position.getY(), position.getZ());\n ParticleEffect effect = ParticleEffect.FLAME;\n Bukkit.getOnlinePlayers().forEach(player -> effect.display(0, 0, 0, 0, 0, loc, player));\n }\n }\n }\n\n @Override\n public void t_() {\n super.t_();\n\n if (this.ability != null) {\n try {\n this.ability.tick();\n } catch (NullPointerException ex) {\n this.ability = null;\n }\n return;\n }\n\n for (IDragonAbility ability : this.abilities) {\n if (ability.shouldActivate()) {\n this.ability = ability;\n this.ability.start();\n break;\n }\n }\n moveAlongPath();\n// visualizePath(); (Will show path for the dragon with Fire particles until the dragon is dead)\n }\n\n public void moveAlongPath() {\n if (!this.moving || stages.isEmpty()) {\n return;\n }\n\n DragonStage stage = currentStage;\n Vector position = stage.getPoint(t);\n Location loc = new Location(this.getBukkitEntity().getWorld(), position.getX(), position.getY(), position.getZ());\n\n // Look in the direction of motion\n if (t + stage.speed < 1.0) {\n Vector nextPosition = stage.getPoint(t + stage.speed);\n loc.setDirection(nextPosition.subtract(position));\n }\n\n this.setPositionRotation(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw() + 180, loc.getPitch());\n\n t += stage.speed;\n if (t > 1.0) {\n t = 0.0;\n currentStageIndex = (currentStageIndex + 1) % stages.size();\n currentStage = stages.get(currentStageIndex);\n }\n }\n\n @Override\n public SkyblockMob getSkyblockMob() {\n return skyblockMob;\n }\n\n @Override\n public EntityLiving getEntityInstance() {\n return this;\n }\n\n @Override\n public Regions getRegion() {\n return Regions.THE_END;\n }\n\n @Override\n public void setHealth(float f) {\n super.setHealth(f);\n if (f <= 0) {\n Bukkit.broadcastMessage(ChatColor.RED + \"Dragon died\");\n DragonManager.getInstance().onEnderDragonDeath();\n }\n }\n}" }, { "identifier": "SkyblockPlayer", "path": "src/main/java/com/sweattypalms/skyblock/core/player/SkyblockPlayer.java", "snippet": "@Getter\npublic class SkyblockPlayer {\n private static final HashMap<UUID, SkyblockPlayer> players = new HashMap<>();\n\n private final Random random = new Random();\n private final StatsManager statsManager;\n private final InventoryManager inventoryManager;\n private final BonusManager bonusManager;\n private final CooldownManager cooldownManager;\n private final ActionBarManager actionBarManager;\n private final ScoreboardManager scoreboardManager;\n private final SlayerManager slayerManager;\n private final SkillManager skillManager;\n private final CurrencyManager currencyManager;\n private final Player player;\n private BukkitTask tickRunnable;\n\n @Getter @Setter\n private Regions lastKnownRegion = null;\n\n /**\n * This is used to get last use time of abilities\n */\n private final Map<String, Long> cooldowns = new HashMap<>();\n\n public SkyblockPlayer(Player player) {\n this.player = player;\n\n this.statsManager = new StatsManager(this);\n this.inventoryManager = new InventoryManager(this);\n this.bonusManager = new BonusManager(this);\n this.cooldownManager = new CooldownManager(this);\n this.actionBarManager = new ActionBarManager(this);\n this.slayerManager = new SlayerManager(this);\n this.skillManager = new SkillManager(this);\n this.currencyManager = new CurrencyManager(this);\n // Should be last because it uses the other managers\n this.scoreboardManager = new ScoreboardManager(this);\n\n players.put(player.getUniqueId(), this);\n init();\n }\n\n public static SkyblockPlayer getSkyblockPlayer(Player player) {\n return players.get(player.getUniqueId());\n }\n\n public static void newPlayer(Player player) {\n new SkyblockPlayer(player);\n }\n\n private void init() {\n\n String displayName = \"$c[OWNER] \" + this.player.getName();\n displayName = PlaceholderFormatter.format(displayName);\n this.player.setDisplayName(displayName);\n\n this.tickRunnable = new BukkitRunnable() {\n @Override\n public void run() {\n tick();\n }\n }.runTaskTimerAsynchronously(SkyBlock.getInstance(), 0, 1);\n\n this.statsManager.initHealth();\n }\n\n private int tickCount = 0;\n private void tick() {\n if (!this.player.isOnline()) {\n SkyblockPlayer.players.remove(this.player.getUniqueId());\n this.tickRunnable.cancel();\n }\n if (this.player.isDead()){\n return;\n }\n this.tickCount++;\n\n if (this.tickCount % 20 != 0) return;\n\n this.bonusManager.cleanupExpiredBonuses();\n this.statsManager.tick();\n this.actionBarManager.tick();\n\n this.scoreboardManager.updateScoreboard();\n RegionManager.updatePlayerRegion(this);\n }\n\n /**\n * Damage the player\n * TODO: Add various damage types\n * @param damage Damage to deal (With reduction)\n */\n public void damage(double damage) {\n if (this.player.getGameMode() != GameMode.SURVIVAL)\n return;\n this.player.setHealth(\n Math.max(\n this.player.getHealth() - damage,\n 0\n )\n );\n }\n\n public void damageWithReduction(double damage){\n double defense = this.statsManager.getMaxStats().get(Stats.DEFENSE);\n double finalDamage = DamageCalculator.calculateDamageReduction(defense, damage);\n this.damage(finalDamage);\n }\n\n /**\n * Send auto formatted message to player\n * @param s Message to send\n */\n public void sendMessage(String s) {\n this.player.sendMessage(PlaceholderFormatter.format(s));\n }\n\n public long getLastUseTime(String key){\n return this.cooldowns.getOrDefault(key, 0L);\n }\n\n public void setLastUseTime(String key, long time){\n this.cooldowns.put(key, time);\n }\n}" } ]
import com.sweattypalms.skyblock.core.helpers.EntityHelper; import com.sweattypalms.skyblock.core.helpers.MathHelper; import com.sweattypalms.skyblock.core.helpers.PlaceholderFormatter; import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonStage; import com.sweattypalms.skyblock.core.mobs.builder.dragons.EnderDragon; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.List;
5,303
package com.sweattypalms.skyblock.core.mobs.builder.dragons.abilities; public class RushAbility implements IDragonAbility{ private final EnderDragon dragon; public RushAbility(EnderDragon dragon) { this.dragon = dragon; } Player target = null; @Override public void start() { this.dragon.setMoving(false); this.target = EntityHelper.getClosestPlayer((LivingEntity) this.dragon.getBukkitEntity()); rushing = true; startRushPosition = this.dragon.getBukkitEntity().getLocation().toVector(); rushProgress = 0.0d; } boolean rushing = false; Vector startRushPosition = null; double rushProgress = 0.0d; @Override public void stop() { dragon.setAbility(null); int tickCount = 0; } @Override public void tick() { if (this.target == null){ throw new NullPointerException("Target not found??? cancelling ability"); } Vector nextPosition = MathHelper.linearInterpolation(startRushPosition, target.getLocation().toVector(), rushProgress); this.dragon.setPositionRotation(nextPosition.getX(), nextPosition.getY(), nextPosition.getZ(), target.getLocation().getYaw(), target.getLocation().getPitch()); rushProgress += 0.025; if(rushProgress >= 1 || this.dragon.getBukkitEntity().getLocation().distance(target.getLocation()) < 3){ String message = "$5☬ $c" + dragon.getDragonName() + " $dused $eRush $don you for $c" + PlaceholderFormatter.formatDecimalCSV(dragon.getDragonDamage()) + " damage!"; message = PlaceholderFormatter.format(message); target.sendMessage(message); SkyblockPlayer.getSkyblockPlayer(target).damageWithReduction(dragon.getDragonDamage()); computeReturnPath(); } } private void computeReturnPath(){ Vector endPosition = dragon.getCurrentStage().getPoint(1); Vector currentDragonPosition = this.dragon.getBukkitEntity().getLocation().toVector();
package com.sweattypalms.skyblock.core.mobs.builder.dragons.abilities; public class RushAbility implements IDragonAbility{ private final EnderDragon dragon; public RushAbility(EnderDragon dragon) { this.dragon = dragon; } Player target = null; @Override public void start() { this.dragon.setMoving(false); this.target = EntityHelper.getClosestPlayer((LivingEntity) this.dragon.getBukkitEntity()); rushing = true; startRushPosition = this.dragon.getBukkitEntity().getLocation().toVector(); rushProgress = 0.0d; } boolean rushing = false; Vector startRushPosition = null; double rushProgress = 0.0d; @Override public void stop() { dragon.setAbility(null); int tickCount = 0; } @Override public void tick() { if (this.target == null){ throw new NullPointerException("Target not found??? cancelling ability"); } Vector nextPosition = MathHelper.linearInterpolation(startRushPosition, target.getLocation().toVector(), rushProgress); this.dragon.setPositionRotation(nextPosition.getX(), nextPosition.getY(), nextPosition.getZ(), target.getLocation().getYaw(), target.getLocation().getPitch()); rushProgress += 0.025; if(rushProgress >= 1 || this.dragon.getBukkitEntity().getLocation().distance(target.getLocation()) < 3){ String message = "$5☬ $c" + dragon.getDragonName() + " $dused $eRush $don you for $c" + PlaceholderFormatter.formatDecimalCSV(dragon.getDragonDamage()) + " damage!"; message = PlaceholderFormatter.format(message); target.sendMessage(message); SkyblockPlayer.getSkyblockPlayer(target).damageWithReduction(dragon.getDragonDamage()); computeReturnPath(); } } private void computeReturnPath(){ Vector endPosition = dragon.getCurrentStage().getPoint(1); Vector currentDragonPosition = this.dragon.getBukkitEntity().getLocation().toVector();
dragon.setCurrentStage(new DragonStage(List.of(currentDragonPosition, endPosition), 0.02));
3
2023-11-15 15:05:58+00:00
8k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/main/java/io/microsphere/i18n/spring/context/I18nConfiguration.java
[ { "identifier": "CompositeServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/CompositeServiceMessageSource.java", "snippet": "public class CompositeServiceMessageSource extends AbstractServiceMessageSource implements SmartInitializingSingleton {\n\n private final ObjectProvider<ServiceMessageSource> serviceMessageSourcesProvider;\n\n private List<ServiceMessageSource> serviceMessageSources;\n\n public CompositeServiceMessageSource(ObjectProvider<ServiceMessageSource> serviceMessageSourcesProvider) {\n super(\"Composite\");\n this.serviceMessageSourcesProvider = serviceMessageSourcesProvider;\n }\n\n @Override\n public void afterSingletonsInstantiated() {\n List<ServiceMessageSource> serviceMessageSources = initServiceMessageSources();\n setServiceMessageSources(serviceMessageSources);\n\n Locale defaultLocale = initDefaultLocale(serviceMessageSources);\n setDefaultLocale(defaultLocale);\n\n List<Locale> supportedLocales = initSupportedLocales(serviceMessageSources);\n setSupportedLocales(supportedLocales);\n }\n\n public void setServiceMessageSources(List<ServiceMessageSource> serviceMessageSources) {\n this.serviceMessageSources = serviceMessageSources;\n logger.debug(\"Source '{}' sets ServiceMessageSource list: {}\", serviceMessageSources);\n }\n\n protected Locale resolveLocale(Locale locale) {\n\n Locale defaultLocale = getDefaultLocale();\n\n if (locale == null || Objects.equals(defaultLocale, locale)) { // If it's the default Locale\n return defaultLocale;\n }\n\n if (supports(locale)) { // If it matches the supported Locale list\n return locale;\n }\n\n Locale resolvedLocale = null;\n\n List<Locale> derivedLocales = resolveDerivedLocales(locale);\n for (Locale derivedLocale : derivedLocales) {\n if (supports(derivedLocale)) {\n resolvedLocale = derivedLocale;\n break;\n }\n }\n\n return resolvedLocale == null ? defaultLocale : resolvedLocale;\n }\n\n @Override\n protected String getInternalMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object... args) {\n String message = null;\n for (ServiceMessageSource serviceMessageSource : serviceMessageSources) {\n message = serviceMessageSource.getMessage(resolvedCode, resolvedLocale, args);\n if (message != null) {\n break;\n }\n }\n\n if (message == null) {\n Locale defaultLocale = getDefaultLocale();\n if (!Objects.equals(defaultLocale, resolvedLocale)) { // Use the default Locale as the bottom pocket\n message = getInternalMessage(resolvedCode, resolvedCode, defaultLocale, defaultLocale, args);\n }\n }\n\n return message;\n }\n\n private Locale initDefaultLocale(List<ServiceMessageSource> serviceMessageSources) {\n return serviceMessageSources.isEmpty() ? super.getDefaultLocale() : serviceMessageSources.get(0).getDefaultLocale();\n }\n\n private List<Locale> initSupportedLocales(List<ServiceMessageSource> serviceMessageSources) {\n List<Locale> allSupportedLocales = new LinkedList<>();\n for (ServiceMessageSource serviceMessageSource : serviceMessageSources) {\n for (Locale supportedLocale : serviceMessageSource.getSupportedLocales()) {\n allSupportedLocales.add(supportedLocale);\n }\n }\n return unmodifiableList(allSupportedLocales);\n }\n\n private List<ServiceMessageSource> initServiceMessageSources() {\n List<ServiceMessageSource> serviceMessageSources = new LinkedList<>();\n for (ServiceMessageSource serviceMessageSource : serviceMessageSourcesProvider) {\n if (serviceMessageSource != this) {\n serviceMessageSources.add(serviceMessageSource);\n }\n }\n AnnotationAwareOrderComparator.sort(serviceMessageSources);\n logger.debug(\"Initializes the ServiceMessageSource Bean list : {}\", serviceMessageSources);\n return unmodifiableList(serviceMessageSources);\n }\n\n @Override\n public String toString() {\n return \"CompositeServiceMessageSource{\" +\n \"serviceMessageSources=\" + serviceMessageSources +\n '}';\n }\n}" }, { "identifier": "ServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/ServiceMessageSource.java", "snippet": "public interface ServiceMessageSource {\n\n /**\n * Common internationalizing message sources\n */\n String COMMON_SOURCE = \"common\";\n\n /**\n * Initialize the life cycle\n */\n void init();\n\n /**\n * Destruction life cycle\n */\n void destroy();\n\n /**\n * Getting international Messages\n *\n * @param code message Code\n * @param locale {@link Locale}\n * @param args the argument of message pattern\n * @return 如果获取到,返回器内容,获取不到,返回 <code>null</code>\n */\n @Nullable\n String getMessage(String code, Locale locale, Object... args);\n\n default String getMessage(String code, Object... args) {\n return getMessage(code, getLocale(), args);\n }\n\n /**\n * Get the runtime {@link Locale}\n *\n * @return {@link Locale}\n */\n @NonNull\n default Locale getLocale() {\n Locale locale = LocaleContextHolder.getLocale();\n return locale == null ? getDefaultLocale() : locale;\n }\n\n /**\n * Get the default {@link Locale}\n *\n * @return {@link Locale#SIMPLIFIED_CHINESE} as default\n */\n @NonNull\n default Locale getDefaultLocale() {\n return Locale.SIMPLIFIED_CHINESE;\n }\n\n /**\n * Gets a list of supported {@link Locale}\n *\n * @return Non-null {@link List}, simplified Chinese and English by default\n */\n @NonNull\n default List<Locale> getSupportedLocales() {\n return asList(getDefaultLocale(), Locale.ENGLISH);\n }\n\n /**\n * Message service source\n *\n * @return The application name or {@link #COMMON_SOURCE}\n */\n default String getSource() {\n return COMMON_SOURCE;\n }\n}" }, { "identifier": "I18nConstants", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/constants/I18nConstants.java", "snippet": "public interface I18nConstants {\n\n String PROPERTY_NAME_PREFIX = \"microsphere.i18n.\";\n\n /**\n * Enabled Configuration Name\n */\n String ENABLED_PROPERTY_NAME = PROPERTY_NAME_PREFIX + \"enabled\";\n\n /**\n * Enabled By Default\n */\n boolean DEFAULT_ENABLED = true;\n\n /**\n * Default {@link Locale} property name\n */\n String DEFAULT_LOCALE_PROPERTY_NAME = PROPERTY_NAME_PREFIX + \"default-locale\";\n\n /**\n * Supported {@link Locale} list property names\n */\n String SUPPORTED_LOCALES_PROPERTY_NAME = PROPERTY_NAME_PREFIX + \"supported-locales\";\n\n /**\n * Message Code pattern prefix\n */\n String MESSAGE_PATTERN_PREFIX = \"{\";\n\n /**\n * Message Code pattern suffix\n */\n String MESSAGE_PATTERN_SUFFIX = \"}\";\n\n /**\n * Generic {@link ServiceMessageSource} bean name\n */\n String COMMON_SERVICE_MESSAGE_SOURCE_BEAN_NAME = \"commonServiceMessageSource\";\n\n /**\n * Generic {@link ServiceMessageSource} Bean Priority\n */\n int COMMON_SERVICE_MESSAGE_SOURCE_ORDER = 500;\n\n /**\n * Primary {@link ServiceMessageSource} Bean\n */\n String SERVICE_MESSAGE_SOURCE_BEAN_NAME = \"serviceMessageSource\";\n}" }, { "identifier": "ServiceMessageSourceFactoryBean", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/spring/beans/factory/ServiceMessageSourceFactoryBean.java", "snippet": "public final class ServiceMessageSourceFactoryBean extends AbstractServiceMessageSource implements FactoryBean<ServiceMessageSource>,\n ApplicationListener<ResourceServiceMessageSourceChangedEvent>, InitializingBean, EnvironmentAware, BeanClassLoaderAware, DisposableBean, Ordered {\n\n private static final Logger logger = LoggerFactory.getLogger(ServiceMessageSourceFactoryBean.class);\n\n private ClassLoader classLoader;\n\n private ConfigurableEnvironment environment;\n\n private List<AbstractServiceMessageSource> serviceMessageSources;\n\n private int order;\n\n public ServiceMessageSourceFactoryBean(String source) {\n super(source);\n }\n\n @Override\n public ServiceMessageSource getObject() throws Exception {\n return this;\n }\n\n @Override\n public Class<?> getObjectType() {\n return ServiceMessageSource.class;\n }\n\n @Override\n public void init() {\n if (this.serviceMessageSources == null) {\n this.serviceMessageSources = loadServiceMessageSources();\n }\n }\n\n @Override\n public void destroy() {\n serviceMessageSources.forEach(ServiceMessageSource::destroy);\n }\n\n @Override\n protected String getInternalMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object... args) {\n String message = null;\n for (AbstractServiceMessageSource serviceMessageSource : serviceMessageSources) {\n message = serviceMessageSource.getMessage(resolvedCode, resolvedLocale, args);\n if (message != null) {\n break;\n }\n }\n if (message == null && logger.isDebugEnabled()) {\n logger.debug(\"Source '{}' Message not found[code : '{}' , resolvedCode : '{}' , locale : '{}' , resolvedLocale : '{}', args : '{}']\",\n source, code, resolvedCode, locale, resolvedLocale, arrayToCommaDelimitedString(args));\n }\n return message;\n }\n\n @Override\n public void afterPropertiesSet() throws Exception {\n init();\n }\n\n @Override\n public void setBeanClassLoader(ClassLoader classLoader) {\n this.classLoader = classLoader;\n }\n\n @Override\n public void setEnvironment(Environment environment) {\n Assert.isInstanceOf(ConfigurableEnvironment.class, environment, \"The 'environment' parameter must be of type ConfigurableEnvironment\");\n this.environment = (ConfigurableEnvironment) environment;\n }\n\n @Override\n public int getOrder() {\n return order;\n }\n\n public void setOrder(int order) {\n this.order = order;\n }\n\n private List<AbstractServiceMessageSource> loadServiceMessageSources() {\n List<String> factoryNames = SpringFactoriesLoader.loadFactoryNames(AbstractServiceMessageSource.class, classLoader);\n\n Locale defaultLocale = initDefaultLocale(environment);\n List<Locale> supportedLocales = initSupportedLocales(environment);\n\n setDefaultLocale(defaultLocale);\n setSupportedLocales(supportedLocales);\n\n List<AbstractServiceMessageSource> serviceMessageSources = new ArrayList<>(factoryNames.size());\n\n for (String factoryName : factoryNames) {\n Class<?> factoryClass = resolveClassName(factoryName, classLoader);\n Constructor constructor = getConstructorIfAvailable(factoryClass, String.class);\n AbstractServiceMessageSource serviceMessageSource = (AbstractServiceMessageSource) instantiateClass(constructor, source);\n serviceMessageSources.add(serviceMessageSource);\n\n if (serviceMessageSource instanceof EnvironmentAware) {\n ((EnvironmentAware) serviceMessageSource).setEnvironment(environment);\n }\n serviceMessageSource.setDefaultLocale(defaultLocale);\n serviceMessageSource.setSupportedLocales(supportedLocales);\n serviceMessageSource.init();\n }\n\n AnnotationAwareOrderComparator.sort(serviceMessageSources);\n\n return serviceMessageSources;\n }\n\n private Locale initDefaultLocale(ConfigurableEnvironment environment) {\n String propertyName = I18nConstants.DEFAULT_LOCALE_PROPERTY_NAME;\n String localeValue = environment.getProperty(propertyName);\n final Locale locale;\n if (!hasText(localeValue)) {\n locale = super.getDefaultLocale();\n logger.debug(\"Default Locale configuration property [name : '{}'] not found, use default value: '{}'\", propertyName, locale);\n } else {\n locale = StringUtils.parseLocale(localeValue);\n logger.debug(\"Default Locale : '{}' parsed by configuration properties [name : '{}']\", propertyName, locale);\n }\n return locale;\n }\n\n private List<Locale> initSupportedLocales(ConfigurableEnvironment environment) {\n final List<Locale> supportedLocales;\n String propertyName = I18nConstants.SUPPORTED_LOCALES_PROPERTY_NAME;\n List<String> locales = environment.getProperty(propertyName, List.class, emptyList());\n if (locales.isEmpty()) {\n supportedLocales = super.getSupportedLocales();\n logger.debug(\"Support Locale list configuration property [name : '{}'] not found, use default value: {}\", propertyName, supportedLocales);\n } else {\n supportedLocales = locales.stream().map(StringUtils::parseLocale).collect(Collectors.toList());\n logger.debug(\"List of supported Locales parsed by configuration property [name : '{}']: {}\", propertyName, supportedLocales);\n }\n return unmodifiableList(supportedLocales);\n }\n\n @Override\n public void onApplicationEvent(ResourceServiceMessageSourceChangedEvent event) {\n Iterable<String> changedResources = event.getChangedResources();\n logger.debug(\"Receive event change resource: {}\", changedResources);\n for (AbstractServiceMessageSource serviceMessageSource : serviceMessageSources) {\n if (serviceMessageSource instanceof ReloadableResourceServiceMessageSource) {\n ReloadableResourceServiceMessageSource reloadableResourceServiceMessageSource = (ReloadableResourceServiceMessageSource) serviceMessageSource;\n if (reloadableResourceServiceMessageSource.canReload(changedResources)) {\n reloadableResourceServiceMessageSource.reload();\n logger.debug(\"change resource [{}] activate {} reloaded\", changedResources, reloadableResourceServiceMessageSource);\n }\n }\n }\n }\n\n @Override\n public String toString() {\n return \"ServiceMessageSourceFactoryBean{\" +\n \"serviceMessageSources=\" + serviceMessageSources +\n \", order=\" + order +\n '}';\n }\n}" }, { "identifier": "I18nUtils", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/util/I18nUtils.java", "snippet": "public class I18nUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(I18nUtils.class);\n\n private static volatile ServiceMessageSource serviceMessageSource;\n\n public static ServiceMessageSource serviceMessageSource() {\n if (serviceMessageSource == null) {\n logger.warn(\"serviceMessageSource is not initialized, EmptyServiceMessageSource will be used\");\n return EmptyServiceMessageSource.INSTANCE;\n }\n return serviceMessageSource;\n }\n\n public static void setServiceMessageSource(ServiceMessageSource serviceMessageSource) {\n I18nUtils.serviceMessageSource = serviceMessageSource;\n logger.debug(\"serviceMessageSource is initialized\");\n }\n\n public static void destroyServiceMessageSource() {\n serviceMessageSource = null;\n logger.debug(\"serviceMessageSource is destroyed\");\n }\n}" } ]
import io.microsphere.i18n.CompositeServiceMessageSource; import io.microsphere.i18n.ServiceMessageSource; import io.microsphere.i18n.constants.I18nConstants; import io.microsphere.i18n.spring.beans.factory.ServiceMessageSourceFactoryBean; import io.microsphere.i18n.util.I18nUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.Environment; import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver; import java.util.List; import java.util.Locale; import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_BEAN_NAME; import static io.microsphere.i18n.constants.I18nConstants.COMMON_SERVICE_MESSAGE_SOURCE_ORDER; import static io.microsphere.i18n.constants.I18nConstants.DEFAULT_ENABLED; import static io.microsphere.i18n.constants.I18nConstants.ENABLED_PROPERTY_NAME; import static io.microsphere.i18n.constants.I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME;
3,804
package io.microsphere.i18n.spring.context; /** * Internationalization Configuration class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public class I18nConfiguration implements DisposableBean { private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class); @Autowired
package io.microsphere.i18n.spring.context; /** * Internationalization Configuration class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public class I18nConfiguration implements DisposableBean { private static final Logger logger = LoggerFactory.getLogger(I18nConfiguration.class); @Autowired
@Qualifier(I18nConstants.SERVICE_MESSAGE_SOURCE_BEAN_NAME)
2
2023-11-17 11:35:59+00:00
8k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/ponder/FryerScenes.java
[ { "identifier": "MechanicalFryerEntity", "path": "src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryerEntity.java", "snippet": "public class MechanicalFryerEntity extends BasinOperatingBlockEntity {\n\n private static final Object DeepFryingRecipesKey = new Object();\n\n public int runningTicks;\n public int processingTicks;\n public boolean running;\n\n public MechanicalFryerEntity(BlockEntityType<?> type, BlockPos pos, BlockState state) {\n\n super(type, pos, state);\n }\n\n public float getRenderedHeadOffset(float partialTicks) {\n int localTick;\n float offset = 0;\n if (running) {\n if (runningTicks < 20) {\n localTick = runningTicks;\n float num = (localTick + partialTicks) / 20f;\n num = ((2 - Mth.cos((float) (num * Math.PI))) / 2);\n offset = num - .5f;\n } else if (runningTicks <= 20) {\n offset = 1;\n } else {\n localTick = 40 - runningTicks;\n float num = (localTick - partialTicks) / 20f;\n num = ((2 - Mth.cos((float) (num * Math.PI))) / 2);\n offset = num - .5f;\n }\n }\n return offset + 7 / 16f;\n }\n\n\n\n\n @Override\n protected AABB createRenderBoundingBox() {\n return new AABB(worldPosition).expandTowards(0, -1.5, 0);\n }\n\n @Override\n protected void read(CompoundTag compound, boolean clientPacket) {\n running = compound.getBoolean(\"Running\");\n runningTicks = compound.getInt(\"Ticks\");\n super.read(compound, clientPacket);\n\n if (clientPacket && hasLevel())\n getBasin().ifPresent(bte -> bte.setAreFluidsMoving(running && runningTicks <= 20));\n }\n\n @Override\n public void write(CompoundTag compound, boolean clientPacket) {\n compound.putBoolean(\"Running\", running);\n compound.putInt(\"Ticks\", runningTicks);\n super.write(compound, clientPacket);\n }\n\n @Override\n public void tick() {\n super.tick();\n\n if (runningTicks >= 40) {\n running = false;\n runningTicks = 0;\n basinChecker.scheduleUpdate();\n return;\n }\n\n float speed = Math.abs(getSpeed());\n if (running && level != null) {\n if (level.isClientSide && runningTicks == 20)\n renderParticles();\n\n if ((!level.isClientSide || isVirtual()) && runningTicks == 20) {\n if (processingTicks < 0) {\n float recipeSpeed = 1;\n if (currentRecipe instanceof ProcessingRecipe) {\n int t = ((ProcessingRecipe<?>) currentRecipe).getProcessingDuration();\n if (t != 0)\n recipeSpeed = t / 100f;\n }\n\n processingTicks = Mth.clamp((Mth.log2((int) (512 / speed))) * Mth.ceil(recipeSpeed * 15) + 1, 1, 512);\n\n Optional<BasinBlockEntity> basin = getBasin();\n if (basin.isPresent()) {\n Couple<SmartFluidTankBehaviour> tanks = basin.get()\n .getTanks();\n if (!tanks.getFirst()\n .isEmpty()\n || !tanks.getSecond()\n .isEmpty())\n level.playSound(null, worldPosition, SoundEvents.BUBBLE_COLUMN_BUBBLE_POP,\n SoundSource.BLOCKS, .75f, 1.6f);\n }\n\n } else {\n processingTicks--;\n if (processingTicks == 0) {\n runningTicks++;\n processingTicks = -1;\n applyBasinRecipe();\n sendData();\n }\n }\n }\n\n if (runningTicks != 20)\n runningTicks++;\n }\n }\n\n public void renderParticles() {\n Optional<BasinBlockEntity> basin = getBasin();\n if (!basin.isPresent() || level == null)\n return;\n\n for (SmartFluidTankBehaviour behaviour : basin.get()\n .getTanks()) {\n if (behaviour == null)\n continue;\n for (TankSegment tankSegment : behaviour.getTanks()) {\n if (tankSegment.isEmpty(0))\n continue;\n spillParticle(FluidFX.getFluidParticle(tankSegment.getRenderedFluid()));\n }\n }\n }\n\n protected void spillParticle(ParticleOptions data) {\n float angle = level.random.nextFloat() * 360;\n Vec3 offset = new Vec3(0, 0, 0.25f);\n offset = VecHelper.rotate(offset, angle, Axis.Y);\n Vec3 target = VecHelper.rotate(offset, getSpeed() > 0 ? 25 : -25, Axis.Y)\n .add(0, .25f, 0);\n Vec3 center = offset.add(VecHelper.getCenterOf(worldPosition));\n target = VecHelper.offsetRandomly(target.subtract(offset), level.random, 1 / 128f);\n level.addParticle(data, center.x, center.y - 1.75f, center.z, target.x, target.y, target.z);\n }\n\n @Override\n protected List<Recipe<?>> getMatchingRecipes() {\n List<Recipe<?>> matchingRecipes = super.getMatchingRecipes();\n\n\n Optional<BasinBlockEntity> basin = getBasin();\n if (!basin.isPresent())\n return matchingRecipes;\n\n BasinBlockEntity basinBlockEntity = basin.get();\n if (basin.isEmpty())\n return matchingRecipes;\n\n IItemHandler availableItems = basinBlockEntity\n .getCapability(ForgeCapabilities.ITEM_HANDLER)\n .orElse(null);\n if (availableItems == null)\n return matchingRecipes;\n\n return matchingRecipes;\n }\n\n @Override\n protected <C extends Container> boolean matchStaticFilters(Recipe<C> recipe) {\n return recipe.getType() == RecipeRegistry.DEEP_FRYING.getType();\n }\n\n @Override\n public void startProcessingBasin() {\n if (running && runningTicks <= 20)\n return;\n super.startProcessingBasin();\n running = true;\n runningTicks = 0;\n }\n\n @Override\n public boolean continueWithPreviousRecipe() {\n runningTicks = 20;\n return true;\n }\n\n @Override\n protected void onBasinRemoved() {\n if (!running)\n return;\n runningTicks = 40;\n running = false;\n }\n\n @Override\n protected Object getRecipeCacheKey() {\n return DeepFryingRecipesKey;\n }\n\n @Override\n protected boolean isRunning() {\n return running;\n }\n\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void tickAudio() {\n super.tickAudio();\n\n boolean slow = Math.abs(getSpeed()) < 65;\n if (slow && AnimationTickHolder.getTicks() % 2 == 0)\n return;\n if (runningTicks == 20)\n SoundsRegistry.FRYING.playAt(level, worldPosition, .75f, 1, true);\n }\n\n}" }, { "identifier": "CreateBicBitModItems", "path": "src/main/java/createbicyclesbitterballen/index/CreateBicBitModItems.java", "snippet": "public class CreateBicBitModItems {\n\tpublic static final ItemEntry<ChocolateGlazedStroopwafelItem> CHOCOLATE_GLAZED_STROOPWAFEL = REGISTRATE.item(\"chocolate_glazed_stroopwafel\", ChocolateGlazedStroopwafelItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(9).saturationMod(0.7f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<StroopwafelItem> STROOPWAFEL = REGISTRATE.item(\"stroopwafel\", StroopwafelItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(7).saturationMod(0.5f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<UnbakedStroopwafelItem> UNBAKED_STROOPWAFEL = REGISTRATE.item(\"unbaked_stroopwafel\", UnbakedStroopwafelItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(1).saturationMod(0.3f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<Item> SWEET_DOUGH = REGISTRATE.item(\"sweet_dough\", Item::new).register();\n\tpublic static final ItemEntry<RawFrikandelItem> RAW_FRIKANDEL = REGISTRATE.item(\"raw_frikandel\", RawFrikandelItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(4).saturationMod(0.2f).meat().effect(() -> new MobEffectInstance(MobEffects.HUNGER, 600, 0), 0.3F).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<FrikandelItem> FRIKANDEL = REGISTRATE.item(\"frikandel\", FrikandelItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(8).saturationMod(0.2f).meat().build()))\n\t\t\t.register();\n\t//public static final ItemEntry<FrikandelSandwichItem> FRIKANDEL_SANDWICH = REGISTRATE.item(\"frikandel_sandwich\", FrikandelSandwichItem::new)\n\t\t\t//.properties(p -> p.food((new FoodProperties.Builder()).nutrition(9).saturationMod(0.3f).meat().build()))\n\t\t\t//.register();\n\tpublic static final ItemEntry<Item> CRUSHED_SUNFLOWER_SEEDS = REGISTRATE.item(\"crushed_sunflower_seeds\", Item::new).register();\n\tpublic static final ItemEntry<SunflowerSeedsItem> SUNFLOWER_SEEDS = REGISTRATE.item(\"sunflower_seeds\", SunflowerSeedsItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(1).saturationMod(0.1f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<RoastedSunflowerSeedsItem> ROASTED_SUNFLOWER_SEEDS = REGISTRATE.item(\"roasted_sunflower_seeds\", RoastedSunflowerSeedsItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(2).saturationMod(0.2f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<FryingOilItem> FRYING_OIL_BUCKET = REGISTRATE.item(\"frying_oil_bucket\", FryingOilItem::new)\n\t\t\t.register();\n\n\tpublic static final ItemEntry<StamppotBowlItem> STAMPPOT_BOWL = REGISTRATE.item(\"stamppot_bowl\", StamppotBowlItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(10).saturationMod(0.5f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<SpeculaasItem> SPECULAAS = REGISTRATE.item(\"speculaas\", SpeculaasItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(5).saturationMod(0.3f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<RawBitterballenItem> RAW_BITTERBALLEN = REGISTRATE.item(\"raw_bitterballen\", RawBitterballenItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(3).saturationMod(0.2f).meat().effect(() -> new MobEffectInstance(MobEffects.HUNGER, 600, 0), 0.3F).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<BitterballenItem> BITTERBALLEN = REGISTRATE.item(\"bitterballen\", BitterballenItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(7).saturationMod(0.2f).meat().build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<KroketItem> KROKET = REGISTRATE.item(\"kroket\", KroketItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(8).saturationMod(0.2f).meat().build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<RawKroketItem> RAW_KROKET = REGISTRATE.item(\"raw_kroket\", RawKroketItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(4).saturationMod(0.2f).meat().effect(() -> new MobEffectInstance(MobEffects.HUNGER, 600, 0), 0.3F).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<OliebollenItem> OLIEBOLLEN = REGISTRATE.item(\"oliebollen\", OliebollenItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(5).saturationMod(0.2f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<RawFriesItem> RAW_FRIES = REGISTRATE.item(\"raw_fries\", RawFriesItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(1).saturationMod(0.3f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<FriesItem> FRIES = REGISTRATE.item(\"fries\", FriesItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(6).saturationMod(0.5f).build()))\n\t\t\t.register();\n\tpublic static final ItemEntry<WrappedFriesItem> WRAPPED_FRIES = REGISTRATE.item(\"wrapped_fries\", WrappedFriesItem::new)\n\t\t\t.properties(p -> p.food((new FoodProperties.Builder()).nutrition(6).saturationMod(0.5f).build()))\n\t\t\t.register();\n\n\tpublic static final ItemEntry<Item> DIRTY_PAPER = REGISTRATE.item(\"dirty_paper\", Item::new).register();\n\n\tpublic static final ItemEntry<Item> BASKET = REGISTRATE.item(\"andesite_basket\", Item::new).register();\n\n\n\tpublic static void register() {\n\t}\n}" } ]
import com.google.common.collect.ImmutableList; import com.simibubi.create.AllBlocks; import com.simibubi.create.content.processing.basin.BasinBlockEntity; import com.simibubi.create.content.processing.burner.BlazeBurnerBlock; import com.simibubi.create.foundation.ponder.SceneBuilder; import com.simibubi.create.foundation.ponder.SceneBuildingUtil; import com.simibubi.create.foundation.ponder.element.InputWindowElement; import com.simibubi.create.foundation.utility.IntAttached; import com.simibubi.create.foundation.utility.NBTHelper; import com.simibubi.create.foundation.utility.Pointing; import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryerEntity; import createbicyclesbitterballen.index.CreateBicBitModItems; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.world.item.ItemStack; import net.minecraft.world.phys.Vec3; import com.simibubi.create.content.processing.burner.BlazeBurnerBlock.HeatLevel;
4,041
package createbicyclesbitterballen.ponder; public class FryerScenes { public static void frying(SceneBuilder scene, SceneBuildingUtil util) { scene.title("mechanical_fryer", "Processing Items with the Mechanical Fryer"); scene.configureBasePlate(0, 0, 5); scene.world.setBlock(util.grid.at(1, 1, 2), AllBlocks.BLAZE_BURNER.getDefaultState().setValue(BlazeBurnerBlock.HEAT_LEVEL, HeatLevel.KINDLED), false); scene.world.showSection(util.select.layer(0), Direction.UP); scene.idle(5); scene.world.showSection(util.select.fromTo(1, 4, 3, 1, 1, 5), Direction.DOWN); scene.idle(5); scene.world.showSection(util.select.position(1, 1, 2), Direction.DOWN); scene.idle(5); scene.world.showSection(util.select.position(1, 2, 2), Direction.DOWN); scene.idle(5); scene.world.showSection(util.select.position(1, 4, 2), Direction.SOUTH); scene.idle(5); scene.world.showSection(util.select.fromTo(3, 1, 1, 1, 1, 1), Direction.SOUTH); scene.world.showSection(util.select.fromTo(3, 1, 5, 3, 1, 2), Direction.SOUTH); scene.idle(20); BlockPos basin = util.grid.at(1, 2, 2); BlockPos pressPos = util.grid.at(1, 4, 2); Vec3 basinSide = util.vector.blockSurface(basin, Direction.WEST);
package createbicyclesbitterballen.ponder; public class FryerScenes { public static void frying(SceneBuilder scene, SceneBuildingUtil util) { scene.title("mechanical_fryer", "Processing Items with the Mechanical Fryer"); scene.configureBasePlate(0, 0, 5); scene.world.setBlock(util.grid.at(1, 1, 2), AllBlocks.BLAZE_BURNER.getDefaultState().setValue(BlazeBurnerBlock.HEAT_LEVEL, HeatLevel.KINDLED), false); scene.world.showSection(util.select.layer(0), Direction.UP); scene.idle(5); scene.world.showSection(util.select.fromTo(1, 4, 3, 1, 1, 5), Direction.DOWN); scene.idle(5); scene.world.showSection(util.select.position(1, 1, 2), Direction.DOWN); scene.idle(5); scene.world.showSection(util.select.position(1, 2, 2), Direction.DOWN); scene.idle(5); scene.world.showSection(util.select.position(1, 4, 2), Direction.SOUTH); scene.idle(5); scene.world.showSection(util.select.fromTo(3, 1, 1, 1, 1, 1), Direction.SOUTH); scene.world.showSection(util.select.fromTo(3, 1, 5, 3, 1, 2), Direction.SOUTH); scene.idle(20); BlockPos basin = util.grid.at(1, 2, 2); BlockPos pressPos = util.grid.at(1, 4, 2); Vec3 basinSide = util.vector.blockSurface(basin, Direction.WEST);
ItemStack oil = new ItemStack(CreateBicBitModItems.FRYING_OIL_BUCKET);
1
2023-11-12 13:05:18+00:00
8k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFComponent.java
[ { "identifier": "Anchor", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Anchor.java", "snippet": "public class Anchor{\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({Start, Center, End})\n public @interface AnchorInt {}\n public static final int Start = 0;\n public static final int Center = 1;\n public static final int End = 2;\n\n @AnchorInt\n public int horizontal = Center;\n @AnchorInt\n public int vertical = Center;\n\n public Anchor(){}\n public Anchor(@AnchorInt int vertical, @AnchorInt int horizontal){\n this.vertical = vertical;\n this.horizontal = horizontal;\n }\n\n public static float getDeltaPixel(@AnchorInt int axis, float gap){\n switch (axis){\n case Start:\n return 0;\n case Center:\n return (gap * 0.5f);\n case End:\n return gap;\n }\n return 0;\n }\n\n private String getName(@AnchorInt int axis){\n switch (axis){\n case Start:\n return \"Start\";\n case Center:\n return \"Center\";\n case End:\n return \"End\";\n }\n return \"Null\";\n }\n\n @NonNull\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(16);\n sb.append(\"Anchor(\"); sb.append(getName(horizontal)); sb.append(\", \");\n sb.append(getName(vertical)); sb.append(\")\");\n return sb.toString();\n }\n}" }, { "identifier": "Border", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Border.java", "snippet": "public class Border {\n public RectF size;\n public ColorRect color;\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n */\n public Border(){\n size = new RectF(0,0,0,0);\n color = new ColorRect(Color.WHITE,Color.WHITE,Color.WHITE,Color.WHITE);\n }\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public Border(float size,@ColorInt int color){\n this.size = new RectF(\n size * Zoomable.getInstance().density,\n size * Zoomable.getInstance().density,\n size * Zoomable.getInstance().density,\n size * Zoomable.getInstance().density);\n this.color = new ColorRect(color, color, color, color);\n }\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public Border(RectF size, ColorRect color){\n size.left *= Zoomable.getInstance().density;\n size.top *= Zoomable.getInstance().density;\n size.right *= Zoomable.getInstance().density;\n size.bottom *= Zoomable.getInstance().density;\n this.size = size;\n this.color = color;\n }\n\n\n /**\n * 테두리 굵기 및 색상 지정 <br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public Border(RectF size,@ColorInt int color){\n size.left *= Zoomable.getInstance().density;\n size.top *= Zoomable.getInstance().density;\n size.right *= Zoomable.getInstance().density;\n size.bottom *= Zoomable.getInstance().density;\n this.size = size;\n this.color = new ColorRect(color, color, color, color);\n }\n\n public void copy(@Nullable Border b){\n if(b != null){\n size = b.size;\n color = b.color;\n }\n }\n\n public Border setLeft(float size,@ColorInt int color){\n this.size.left = size * Zoomable.getInstance().density;\n this.color.left = color;\n return this;\n }\n public Border setTop(float size,@ColorInt int color){\n this.size.top = size * Zoomable.getInstance().density;\n this.color.top = color;\n return this;\n }\n public Border setRight(float size,@ColorInt int color){\n this.size.right = size * Zoomable.getInstance().density;\n this.color.right = color;\n return this;\n }\n public Border setBottom(float size,@ColorInt int color){\n this.size.bottom = size * Zoomable.getInstance().density;\n this.color.bottom = color;\n return this;\n }\n\n public void draw(Canvas canvas, float measureX, float measureY, int measureWidth, int measureHeight){\n Paint paint = new Paint();\n paint.setFlags(TextPaint.FILTER_BITMAP_FLAG | TextPaint.LINEAR_TEXT_FLAG | TextPaint.ANTI_ALIAS_FLAG);\n float gap;\n if(size.left > 0) {\n gap = size.left*0.5f;\n paint.setStrokeWidth(size.left);\n paint.setColor(color.left);\n canvas.drawLine(measureX+gap, measureY,\n measureX+gap, measureY+measureHeight, paint);\n }\n if(size.top > 0) {\n gap = size.top*0.5f;\n paint.setStrokeWidth(size.top);\n paint.setColor(color.top);\n canvas.drawLine(measureX, measureY+gap,\n measureX+measureWidth, measureY+gap, paint);\n }\n if(size.right > 0) {\n gap = size.right*0.5f;\n paint.setStrokeWidth(size.right);\n paint.setColor(color.right);\n canvas.drawLine(measureX+measureWidth-gap, measureY,\n measureX+measureWidth-gap, measureY+measureHeight, paint);\n }\n if(size.bottom > 0) {\n gap = size.bottom*0.5f;\n paint.setStrokeWidth(size.bottom);\n paint.setColor(color.bottom);\n canvas.drawLine(measureX, measureY+measureHeight-gap,\n measureX+measureWidth, measureY+measureHeight-gap, paint);\n }\n }\n\n @Override\n public String toString() {\n return size.toString() + \", \" + color.toString();\n }\n\n /**\n * 왼쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the left border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderLeft(float size,@ColorInt int color){\n return new Border(new RectF(size * Zoomable.getInstance().density,0,0, 0), new ColorRect(color, Color.WHITE, Color.WHITE, Color.WHITE));\n }\n /**\n * 위쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the top border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderTop(float size,@ColorInt int color){\n return new Border(new RectF(0,size * Zoomable.getInstance().density,0, 0), new ColorRect(Color.WHITE, color, Color.WHITE, Color.WHITE));\n }\n /**\n * 오른쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the right border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderRight(float size,@ColorInt int color){\n return new Border(new RectF(0,0,size * Zoomable.getInstance().density, 0), new ColorRect(Color.WHITE, Color.WHITE, color, Color.WHITE));\n }\n /**\n * 아래쪽 테두리만 나타나도록 설정<br>\n * 테두리 굵기 및 색상 지정 <br>\n * Set so that only the bottom border appears<br>\n * Specify border thickness and color\n * @param size 테두리 굵기, thickness\n * @param color 테두리 색상, color\n */\n public static Border BorderBottom(float size,@ColorInt int color){\n return new Border(new RectF(0,0,0, size * Zoomable.getInstance().density), new ColorRect(Color.WHITE, Color.WHITE, Color.WHITE, color));\n }\n}" }, { "identifier": "Action", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/listener/Action.java", "snippet": "public interface Action<T, R> {\n R invoke(T t);\n}" }, { "identifier": "Zoomable", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/utils/Zoomable.java", "snippet": "public class Zoomable {\n private static Zoomable instance = null;\n\n public static Zoomable getInstance(){\n if(instance == null){\n instance = new Zoomable();\n }\n return instance;\n }\n\n /**\n * PDF 내에 들어가는 요소를 전부 이미지로 변환 후 집어 넣기 때문에<br>\n * density 를 통해 전체적으로 이미지 파일 크기 자체를 키워서<br>\n * 디바이스에 구애 받지 않고 dpi 를 늘리는 효과를 만든다. <br>\n * Since all elements in the PDF are converted into images and inserted,<br>\n * Through density, the image file size itself is increased as a whole,<br>\n * creating the effect of increasing dpi regardless of device.\n */\n public float density = 1.0f;\n\n private RectF contentRect = null;\n\n public void setContentRect(RectF contentRect){\n this.contentRect = contentRect;\n }\n\n public RectF getContentRect() {\n return contentRect;\n }\n public float getZoomWidth() {\n return contentRect.width() * density;\n }\n public float getZoomHeight() {\n return contentRect.height() * density;\n }\n}" } ]
import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.text.TextPaint; import androidx.annotation.ColorInt; import com.hangyeolee.androidpdfwriter.utils.Anchor; import com.hangyeolee.androidpdfwriter.utils.Border; import com.hangyeolee.androidpdfwriter.listener.Action; import com.hangyeolee.androidpdfwriter.utils.Zoomable;
5,427
Math.round(margin.top * Zoomable.getInstance().density), Math.round(margin.right * Zoomable.getInstance().density), Math.round(margin.bottom * Zoomable.getInstance().density)) ); return this; } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param all 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(int all){ return setMargin(all, all, all, all); } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param horizontal 가로 여백 * @param vertical 세로 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(int horizontal, int vertical){ return setMargin(horizontal, vertical, horizontal, vertical); } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param left 왼쪽 여백 * @param top 위쪽 여백 * @param right 오른쪽 여백 * @param bottom 아래쪽 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(int left, int top, int right, int bottom){ this.margin.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param padding 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(Rect padding){ this.padding.set(new Rect( Math.round(padding.left * Zoomable.getInstance().density), Math.round(padding.top * Zoomable.getInstance().density), Math.round(padding.right * Zoomable.getInstance().density), Math.round(padding.bottom * Zoomable.getInstance().density)) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param all 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(int all){ this.padding.set( Math.round(all * Zoomable.getInstance().density), Math.round(all * Zoomable.getInstance().density), Math.round(all * Zoomable.getInstance().density), Math.round(all * Zoomable.getInstance().density) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param horizontal 가로 패딩 * @param vertical 세로 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(int horizontal, int vertical){ this.padding.set( Math.round(horizontal * Zoomable.getInstance().density), Math.round(vertical * Zoomable.getInstance().density), Math.round(horizontal * Zoomable.getInstance().density), Math.round(vertical * Zoomable.getInstance().density) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param left 왼쪽 패딩 * @param top 위쪽 패딩 * @param right 오른쪽 패딩 * @param bottom 아래쪽 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(int left, int top, int right, int bottom){ this.padding.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } /** * 테두리 굵기 및 색상 지정<br> * Specify border thickness and color * @param action 테두리 변경 함수 */
package com.hangyeolee.androidpdfwriter.components; public abstract class PDFComponent{ PDFComponent parent = null; // margin을 뺀 나머지 길이 int width = 0; int height = 0; @ColorInt int backgroundColor = Color.TRANSPARENT; final Rect margin = new Rect(0,0,0,0); final Rect padding = new Rect(0,0,0,0); final Border border = new Border(); final Anchor anchor = new Anchor(); Bitmap buffer = null; Paint bufferPaint = null; float relativeX = 0; float relativeY = 0; // Absolute Position protected float measureX = 0; protected float measureY = 0; // margin을 뺀 나머지 길이 protected int measureWidth = -1; protected int measureHeight = -1; public PDFComponent(){} /** * 상위 컴포넌트에서의 레이아웃 계산 <br> * 상위 컴포넌트가 null 인 경우 전체 페이지를 기준 <br> * Compute layout on parent components <br> * Based on full page when parent component is null */ public void measure(){ measure(relativeX, relativeY); } /** * 상위 컴포넌트에서의 레이아웃 계산 <br> * 상위 컴포넌트가 null 인 경우 전체 페이지를 기준 <br> * Compute layout on parent components <br> * Based on full page when parent component is null * @param x 상대적인 X 위치, Relative X position * @param y 상대적인 Y 위치, Relative Y position */ public void measure(float x, float y){ if(width < 0) { width = 0; } if(height < 0) { height = 0; } relativeX = x; relativeY = y; float dx, dy; int gapX = 0; int gapY = 0; int left = margin.left; int top = margin.top; int right = margin.right; int bottom = margin.bottom; // Measure Width and Height if(parent == null){ measureWidth = (width - left - right); measureHeight = (height - top - bottom); } else{ // Get Max Width and Height from Parent int maxW = Math.round (parent.measureWidth - parent.border.size.left - parent.border.size.right - parent.padding.left - parent.padding.right - left - right); int maxH = Math.round (parent.measureHeight - parent.border.size.top - parent.border.size.bottom - parent.padding.top - parent.padding.bottom - top - bottom); if(maxW < 0) maxW = 0; if(maxH < 0) maxH = 0; // 설정한 Width 나 Height 가 최대값을 넘지 않으면, 설정한 값으로 if(0 < width && width + relativeX <= maxW) measureWidth = width; // 설정한 Width 나 Height 가 최대값을 넘으면, 최대 값으로 Width 나 Height를 설정 else measureWidth = Math.round (maxW - relativeX); if(0 < height && height + relativeY <= maxH) measureHeight = height; else measureHeight = Math.round (maxH - relativeY); gapX = maxW - measureWidth; gapY = maxH - measureHeight; } dx = Anchor.getDeltaPixel(anchor.horizontal, gapX); dy = Anchor.getDeltaPixel(anchor.vertical, gapY); if(parent != null){ dx += parent.measureX + parent.border.size.left + parent.padding.left; dy += parent.measureY + parent.border.size.top + parent.padding.top; } measureX = relativeX + left + dx; measureY = relativeY + top + dy; } /** * 부모 컴포넌트에서 부모 컴포넌트의 연산에 맞게<br> * 자식 컴포넌트를 강제로 수정해야할 떄 사용<br> * Used when a parent component needs to force a child component ~<br> * to be modified to match the parent component's operations * @param width * @param height */ protected void force(Integer width, Integer height, Rect forceMargin) { int max; int gap = 0; float d; if (width != null) { if(forceMargin == null) max = (width - margin.left - margin.right); else max = width; gap = max - measureWidth; // Measure X Anchor and Y Anchor d = Anchor.getDeltaPixel(anchor.horizontal, gap); if (parent != null) d += parent.measureX + parent.border.size.left + parent.padding.left; // Set Absolute Position From Parent measureWidth = max; measureX = relativeX + margin.left + d; } if(height != null) { if(forceMargin == null) max = (height - margin.top - margin.bottom); else max = height; gap = max - measureHeight; // Measure X Anchor and Y Anchor d = Anchor.getDeltaPixel(anchor.vertical, gap); if (parent != null) d += parent.measureY + parent.border.size.top + parent.padding.top; // Set Absolute Position From Parent measureHeight = max; measureY = relativeY + margin.top + d; } } public void draw(Canvas canvas){ //---------------배경 그리기-------------// Paint background = new Paint(); background.setColor(backgroundColor); background.setStyle(Paint.Style.FILL); background.setFlags(TextPaint.FILTER_BITMAP_FLAG | TextPaint.LINEAR_TEXT_FLAG | TextPaint.ANTI_ALIAS_FLAG); float left = relativeX + margin.left; float top = relativeY + margin.top; if (parent != null) { left += parent.measureX + parent.border.size.left + parent.padding.left; top += parent.measureY + parent.border.size.top + parent.padding.top; } if(measureWidth > 0 && measureHeight > 0) { canvas.drawRect(left, top, left + measureWidth, top + measureHeight, background); } //--------------테두리 그리기-------------// border.draw(canvas, left, top, measureWidth, measureHeight); } /** * 하위 컴포넌트로 상위 컴포넌트 업데이트 <br> * Update parent components to child components * @param heightGap */ protected void updateHeight(float heightGap){ int top = margin.top; int bottom = margin.bottom; if(parent == null){ height += heightGap; measureHeight = (height - top - bottom); } else{ parent.updateHeight(heightGap); int maxH = Math.round (parent.measureHeight - parent.border.size.top - parent.border.size.bottom - parent.padding.top - parent.padding.bottom - top - bottom); if(0 < height && height + relativeY <= maxH) measureHeight = height; else measureHeight = Math.round (maxH - relativeY); } } /** * 계산된 전체 너비를 구한다.<br> * Get the calculated total width. * @return 전체 너비 */ public int getTotalWidth(){ return measureWidth + margin.right + margin.left; } /** * 계산된 전체 높이를 구한다.<br> * Get the calculated total height. * @return 전체 높이 */ public int getTotalHeight(){ return measureHeight + margin.top + margin.bottom; } /** * 컴포넌트 내의 내용(content)의 크기 설정 <br> * Setting the size of content within a component * @param width 가로 크기 * @param height 세로 크기 * @return 컴포넌트 자기자신 */ public PDFComponent setSize(Float width, Float height){ if(width != null){ if(width < 0) width = 0f; this.width = Math.round(width * Zoomable.getInstance().density); } if(height != null){ if(height < 0) height = 0f; this.height = Math.round(height * Zoomable.getInstance().density); } return this; } /** * 컴포넌트 내의 배경의 색상 설정<br> * Set the color of the background within the component * @param color 색상 * @return 컴포넌트 자기자신 */ public PDFComponent setBackgroundColor(int color){ this.backgroundColor = color; return this; } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param margin 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(Rect margin){ this.margin.set(new Rect( Math.round(margin.left * Zoomable.getInstance().density), Math.round(margin.top * Zoomable.getInstance().density), Math.round(margin.right * Zoomable.getInstance().density), Math.round(margin.bottom * Zoomable.getInstance().density)) ); return this; } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param all 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(int all){ return setMargin(all, all, all, all); } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param horizontal 가로 여백 * @param vertical 세로 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(int horizontal, int vertical){ return setMargin(horizontal, vertical, horizontal, vertical); } /** * 컴포넌트 밖의 여백 설정<br> * Setting margins outside of components * @param left 왼쪽 여백 * @param top 위쪽 여백 * @param right 오른쪽 여백 * @param bottom 아래쪽 여백 * @return 컴포넌트 자기자신 */ public PDFComponent setMargin(int left, int top, int right, int bottom){ this.margin.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param padding 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(Rect padding){ this.padding.set(new Rect( Math.round(padding.left * Zoomable.getInstance().density), Math.round(padding.top * Zoomable.getInstance().density), Math.round(padding.right * Zoomable.getInstance().density), Math.round(padding.bottom * Zoomable.getInstance().density)) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param all 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(int all){ this.padding.set( Math.round(all * Zoomable.getInstance().density), Math.round(all * Zoomable.getInstance().density), Math.round(all * Zoomable.getInstance().density), Math.round(all * Zoomable.getInstance().density) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param horizontal 가로 패딩 * @param vertical 세로 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(int horizontal, int vertical){ this.padding.set( Math.round(horizontal * Zoomable.getInstance().density), Math.round(vertical * Zoomable.getInstance().density), Math.round(horizontal * Zoomable.getInstance().density), Math.round(vertical * Zoomable.getInstance().density) ); return this; } /** * 컴포넌트 내의 내용(content)과 테두리(border) 사이의 간격 설정<br> * Setting the interval between content and border within a component * @param left 왼쪽 패딩 * @param top 위쪽 패딩 * @param right 오른쪽 패딩 * @param bottom 아래쪽 패딩 * @return 컴포넌트 자기자신 */ public PDFComponent setPadding(int left, int top, int right, int bottom){ this.padding.set( Math.round(left * Zoomable.getInstance().density), Math.round(top * Zoomable.getInstance().density), Math.round(right * Zoomable.getInstance().density), Math.round(bottom * Zoomable.getInstance().density) ); return this; } /** * 테두리 굵기 및 색상 지정<br> * Specify border thickness and color * @param action 테두리 변경 함수 */
public PDFComponent setBorder(Action<Border, Border> action){
2
2023-11-15 08:05:28+00:00
8k
cometcake575/Origins-Reborn
src/main/java/com/starshootercity/abilities/impossible/ExtraReach.java
[ { "identifier": "OriginSwapper", "path": "src/main/java/com/starshootercity/OriginSwapper.java", "snippet": "public class OriginSwapper implements Listener {\n private final static NamespacedKey displayKey = new NamespacedKey(OriginsReborn.getInstance(), \"display-item\");\n private final static NamespacedKey confirmKey = new NamespacedKey(OriginsReborn.getInstance(), \"confirm-select\");\n private final static NamespacedKey originKey = new NamespacedKey(OriginsReborn.getInstance(), \"origin-name\");\n private final static NamespacedKey swapTypeKey = new NamespacedKey(OriginsReborn.getInstance(), \"swap-type\");\n private final static NamespacedKey pageSetKey = new NamespacedKey(OriginsReborn.getInstance(), \"page-set\");\n private final static NamespacedKey pageScrollKey = new NamespacedKey(OriginsReborn.getInstance(), \"page-scroll\");\n private final static Random random = new Random();\n\n public static String getInverse(String string) {\n StringBuilder result = new StringBuilder();\n for (char c : string.toCharArray()) {\n result.append(getInverse(c));\n }\n return result.toString();\n }\n\n public static void openOriginSwapper(Player player, PlayerSwapOriginEvent.SwapReason reason, int slot, int scrollAmount, boolean forceRandom) {\n if (OriginLoader.origins.size() == 0) return;\n boolean enableRandom = OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.random-option.enabled\");\n while (slot > OriginLoader.origins.size() || slot == OriginLoader.origins.size() && !enableRandom) {\n slot -= OriginLoader.origins.size() + (enableRandom ? 1 : 0);\n }\n while (slot < 0) {\n slot += OriginLoader.origins.size() + (enableRandom ? 1 : 0);\n }\n ItemStack icon;\n String name;\n char impact;\n LineData data;\n if (slot == OriginLoader.origins.size()) {\n List<String> excludedOrigins = OriginsReborn.getInstance().getConfig().getStringList(\"origin-selection.random-option.exclude\");\n icon = OrbOfOrigin.orb;\n name = \"Random\";\n impact = '\\uE002';\n StringBuilder names = new StringBuilder(\"You'll be assigned one of the following:\\n\\n\");\n for (Origin origin : OriginLoader.origins) {\n if (!excludedOrigins.contains(origin.getName())) {\n names.append(origin.getName()).append(\"\\n\");\n }\n }\n data = new LineData(LineData.makeLineFor(\n names.toString(),\n LineData.LineComponent.LineType.DESCRIPTION\n ));\n } else {\n Origin origin = OriginLoader.origins.get(slot);\n icon = origin.getIcon();\n name = origin.getName();\n impact = origin.getImpact();\n data = new LineData(origin);\n }\n StringBuilder compressedName = new StringBuilder(\"\\uF001\");\n for (char c : name.toCharArray()) {\n compressedName.append(c);\n compressedName.append('\\uF000');\n }\n Component component = Component.text(\"\\uF000\\uE000\\uF001\\uE001\\uF002\" + impact)\n .font(Key.key(\"minecraft:origin_selector\"))\n .color(NamedTextColor.WHITE)\n .append(Component.text(compressedName.toString())\n .font(Key.key(\"minecraft:origin_title_text\"))\n .color(NamedTextColor.WHITE)\n )\n .append(Component.text(getInverse(name) + \"\\uF000\")\n .font(Key.key(\"minecraft:reverse_text\"))\n .color(NamedTextColor.WHITE)\n );\n for (Component c : data.getLines(scrollAmount)) {\n component = component.append(c);\n }\n Inventory swapperInventory = Bukkit.createInventory(null, 54,\n component\n );\n ItemMeta meta = icon.getItemMeta();\n meta.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, name.toLowerCase());\n if (meta instanceof SkullMeta skullMeta) {\n skullMeta.setOwningPlayer(player);\n }\n meta.getPersistentDataContainer().set(displayKey, PersistentDataType.BOOLEAN, true);\n meta.getPersistentDataContainer().set(swapTypeKey, PersistentDataType.STRING, reason.getReason());\n icon.setItemMeta(meta);\n swapperInventory.setItem(1, icon);\n ItemStack confirm = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack invisibleConfirm = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemMeta confirmMeta = confirm.getItemMeta();\n ItemMeta invisibleConfirmMeta = invisibleConfirm.getItemMeta();\n\n confirmMeta.displayName(Component.text(\"Confirm\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n confirmMeta.setCustomModelData(5);\n confirmMeta.getPersistentDataContainer().set(confirmKey, PersistentDataType.BOOLEAN, true);\n\n invisibleConfirmMeta.displayName(Component.text(\"Confirm\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n invisibleConfirmMeta.setCustomModelData(6);\n invisibleConfirmMeta.getPersistentDataContainer().set(confirmKey, PersistentDataType.BOOLEAN, true);\n\n if (!forceRandom) {\n ItemStack left = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack right = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack up = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack down = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemMeta leftMeta = left.getItemMeta();\n ItemMeta rightMeta = right.getItemMeta();\n ItemMeta upMeta = up.getItemMeta();\n ItemMeta downMeta = down.getItemMeta();\n\n leftMeta.displayName(Component.text(\"Previous origin\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n leftMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot - 1);\n leftMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, 0);\n leftMeta.setCustomModelData(1);\n\n\n rightMeta.displayName(Component.text(\"Next origin\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n rightMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot + 1);\n rightMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, 0);\n rightMeta.setCustomModelData(2);\n\n int scrollSize = OriginsReborn.getInstance().getConfig().getInt(\"origin-selection.scroll-amount\", 1);\n\n upMeta.displayName(Component.text(\"Up\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n if (scrollAmount != 0) {\n upMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot);\n upMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, Math.max(scrollAmount - scrollSize, 0));\n }\n upMeta.setCustomModelData(3 + (scrollAmount == 0 ? 6 : 0));\n\n\n int size = data.lines.size() - scrollAmount - 6;\n boolean canGoDown = size > 0;\n\n downMeta.displayName(Component.text(\"Down\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n if (canGoDown) {\n downMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot);\n downMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, Math.min(scrollAmount + scrollSize, scrollAmount + size));\n }\n downMeta.setCustomModelData(4 + (!canGoDown ? 6 : 0));\n\n left.setItemMeta(leftMeta);\n right.setItemMeta(rightMeta);\n up.setItemMeta(upMeta);\n down.setItemMeta(downMeta);\n\n swapperInventory.setItem(47, left);\n swapperInventory.setItem(51, right);\n swapperInventory.setItem(52, up);\n swapperInventory.setItem(53, down);\n }\n\n confirm.setItemMeta(confirmMeta);\n invisibleConfirm.setItemMeta(invisibleConfirmMeta);\n swapperInventory.setItem(48, confirm);\n swapperInventory.setItem(49, invisibleConfirm);\n swapperInventory.setItem(50, invisibleConfirm);\n player.openInventory(swapperInventory);\n }\n\n @EventHandler\n public void onInventoryClick(InventoryClickEvent event) {\n ItemStack item = event.getWhoClicked().getOpenInventory().getItem(1);\n if (item != null) {\n if (item.getItemMeta() == null) return;\n if (item.getItemMeta().getPersistentDataContainer().has(displayKey)) {\n event.setCancelled(true);\n }\n if (event.getWhoClicked() instanceof Player player) {\n ItemStack currentItem = event.getCurrentItem();\n if (currentItem == null) return;\n Integer page = currentItem.getItemMeta().getPersistentDataContainer().get(pageSetKey, PersistentDataType.INTEGER);\n if (page != null) {\n Integer scroll = currentItem.getItemMeta().getPersistentDataContainer().get(pageScrollKey, PersistentDataType.INTEGER);\n if (scroll == null) return;\n player.playSound(player, Sound.UI_BUTTON_CLICK, SoundCategory.MASTER, 1, 1);\n openOriginSwapper(player, getReason(item), page, scroll, false);\n }\n if (currentItem.getItemMeta().getPersistentDataContainer().has(confirmKey)) {\n String originName = item.getItemMeta().getPersistentDataContainer().get(originKey, PersistentDataType.STRING);\n if (originName == null) return;\n Origin origin;\n if (originName.equalsIgnoreCase(\"random\")) {\n List<String> excludedOrigins = OriginsReborn.getInstance().getConfig().getStringList(\"origin-selection.random-option.exclude\");\n List<Origin> origins = new ArrayList<>(OriginLoader.origins);\n origins.removeIf(origin1 -> excludedOrigins.contains(origin1.getName()));\n if (origins.isEmpty()) {\n origin = OriginLoader.origins.get(0);\n } else {\n origin = origins.get(random.nextInt(origins.size()));\n }\n } else {\n origin = OriginLoader.originNameMap.get(originName);\n }\n PlayerSwapOriginEvent.SwapReason reason = getReason(item);\n player.playSound(player, Sound.UI_BUTTON_CLICK, SoundCategory.MASTER, 1, 1);\n player.closeInventory();\n\n ItemMeta meta = player.getInventory().getItemInMainHand().getItemMeta();\n\n if (reason == PlayerSwapOriginEvent.SwapReason.ORB_OF_ORIGIN) {\n EquipmentSlot hand = null;\n if (meta != null) {\n if (meta.getPersistentDataContainer().has(OrbOfOrigin.orbKey)) {\n hand = EquipmentSlot.HAND;\n }\n }\n if (hand == null) {\n ItemMeta offhandMeta = player.getInventory().getItemInOffHand().getItemMeta();\n if (offhandMeta != null) {\n if (offhandMeta.getPersistentDataContainer().has(OrbOfOrigin.orbKey)) {\n hand = EquipmentSlot.OFF_HAND;\n }\n }\n }\n if (hand == null) return;\n orbCooldown.put(player, System.currentTimeMillis());\n player.swingHand(hand);\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"orb-of-origin.consume\")) {\n player.getInventory().getItem(hand).setAmount(player.getInventory().getItem(hand).getAmount() - 1);\n }\n }\n boolean resetPlayer = shouldResetPlayer(reason);\n setOrigin(player, origin, reason, resetPlayer);\n }\n }\n }\n }\n\n public boolean shouldResetPlayer(PlayerSwapOriginEvent.SwapReason reason) {\n return switch (reason) {\n case COMMAND -> OriginsReborn.getInstance().getConfig().getBoolean(\"swap-command.reset-player\");\n case ORB_OF_ORIGIN -> OriginsReborn.getInstance().getConfig().getBoolean(\"orb-of-origin.reset-player\");\n default -> false;\n };\n }\n\n public static int getWidth(char c) {\n return switch (c) {\n case ':', '.', '\\'', 'i', ';', '|', '!', ',', '\\uF00A' -> 2;\n case 'l', '`' -> 3;\n case '(', '}', ')', '*', '[', ']', '{', '\"', 'I', 't', ' ' -> 4;\n case '<', 'k', '>', 'f' -> 5;\n case '^', '/', 'X', 'W', 'g', 'h', '=', 'x', 'J', '\\\\', 'n', 'y', 'w', 'L', 'j', 'Z', '1', '?', '-', 'G', 'H', 'K', 'N', '0', '7', '8', 'O', 'V', 'p', 'Y', 'z', '+', 'A', '2', 'd', 'T', 'B', 'b', 'R', 'q', 'F', 'Q', 'a', '6', 'e', 'C', 'U', '3', 'S', '#', 'P', 'M', '9', 'v', '_', 'o', 'm', '&', 'u', 'c', 'D', 'E', '4', '5', 'r', 's', '$', '%' -> 6;\n case '@', '~' -> 7;\n default -> throw new IllegalStateException(\"Unexpected value: \" + c);\n };\n }\n\n public static int getWidth(String s) {\n int result = 0;\n for (char c : s.toCharArray()) {\n result += getWidth(c);\n }\n return result;\n }\n\n public static char getInverse(char c) {\n return switch (getWidth(c)) {\n case 2 -> '\\uF001';\n case 3 -> '\\uF002';\n case 4 -> '\\uF003';\n case 5 -> '\\uF004';\n case 6 -> '\\uF005';\n case 7 -> '\\uF006';\n case 8 -> '\\uF007';\n case 9 -> '\\uF008';\n case 10 -> '\\uF009';\n default -> throw new IllegalStateException(\"Unexpected value: \" + c);\n };\n }\n\n public static Map<Player, Long> orbCooldown = new HashMap<>();\n\n public static void resetPlayer(Player player, boolean full) {\n AttributeInstance speedInstance = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);\n if (speedInstance != null) {\n speedInstance.removeModifier(player.getUniqueId());\n }\n ClientboundSetBorderWarningDistancePacket warningDistancePacket = new ClientboundSetBorderWarningDistancePacket(new WorldBorder() {{\n setWarningBlocks(player.getWorld().getWorldBorder().getWarningDistance());\n }});\n ((CraftPlayer) player).getHandle().connection.send(warningDistancePacket);\n player.setCooldown(Material.SHIELD, 0);\n player.setAllowFlight(false);\n player.setFlying(false);\n for (Player otherPlayer : Bukkit.getOnlinePlayers()) {\n AbilityRegister.updateEntity(player, otherPlayer);\n }\n AttributeInstance instance = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n double maxHealth = getMaxHealth(player);\n if (instance != null) {\n instance.setBaseValue(maxHealth);\n }\n for (PotionEffect effect : player.getActivePotionEffects()) {\n if (effect.getAmplifier() == -1 || effect.getDuration() == PotionEffect.INFINITE_DURATION) player.removePotionEffect(effect.getType());\n }\n if (!full) return;\n player.getInventory().clear();\n player.getEnderChest().clear();\n player.setSaturation(5);\n player.setFallDistance(0);\n player.setRemainingAir(player.getMaximumAir());\n player.setFoodLevel(20);\n player.setFireTicks(0);\n player.setHealth(maxHealth);\n ShulkerInventory.getInventoriesConfig().set(player.getUniqueId().toString(), null);\n for (PotionEffect effect : player.getActivePotionEffects()) {\n player.removePotionEffect(effect.getType());\n }\n World world = getRespawnWorld(getOrigin(player));\n player.teleport(world.getSpawnLocation());\n player.setBedSpawnLocation(null);\n }\n\n public static @NotNull World getRespawnWorld(@Nullable Origin origin) {\n if (origin != null) {\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof DefaultSpawnAbility defaultSpawnAbility) {\n World world = defaultSpawnAbility.getWorld();\n if (world != null) return world;\n }\n }\n }\n String overworld = OriginsReborn.getInstance().getConfig().getString(\"worlds.world\");\n if (overworld == null) {\n overworld = \"world\";\n OriginsReborn.getInstance().getConfig().set(\"worlds.world\", \"world\");\n OriginsReborn.getInstance().saveConfig();\n }\n World world = Bukkit.getWorld(overworld);\n if (world == null) return Bukkit.getWorlds().get(0);\n return world;\n }\n\n public static double getMaxHealth(Player player) {\n Origin origin = getOrigin(player);\n if (origin == null) return 20;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof HealthModifierAbility healthModifierAbility) {\n return healthModifierAbility.getHealth();\n }\n }\n return 20;\n }\n\n public static double getSpeedIncrease(Player player) {\n Origin origin = getOrigin(player);\n if (origin == null) return 0;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof SpeedModifierAbility speedModifierAbility) {\n return speedModifierAbility.getSpeedIncrease();\n }\n }\n return 0;\n }\n\n @EventHandler\n public void onServerTickEnd(ServerTickEndEvent event) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (getOrigin(player) == null) {\n if (player.isDead()) continue;\n if (player.getOpenInventory().getType() != InventoryType.CHEST) {\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.randomise\")) {\n selectRandomOrigin(player, PlayerSwapOriginEvent.SwapReason.INITIAL);\n } else openOriginSwapper(player, PlayerSwapOriginEvent.SwapReason.INITIAL, 0, 0, false);\n }\n } else {\n AttributeInstance healthInstance = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n if (healthInstance != null) healthInstance.setBaseValue(getMaxHealth(player));\n AttributeInstance speedInstance = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);\n if (speedInstance != null) {\n AttributeModifier modifier = speedInstance.getModifier(player.getUniqueId());\n if (modifier == null) {\n modifier = new AttributeModifier(player.getUniqueId(), \"speed-increase\", getSpeedIncrease(player), AttributeModifier.Operation.MULTIPLY_SCALAR_1);\n speedInstance.addModifier(modifier);\n }\n }\n player.setAllowFlight(AbilityRegister.canFly(player));\n player.setFlySpeed(AbilityRegister.getFlySpeed(player));\n player.setInvisible(AbilityRegister.isInvisible(player));\n }\n }\n }\n\n public void selectRandomOrigin(Player player, PlayerSwapOriginEvent.SwapReason reason) {\n Origin origin = OriginLoader.origins.get(random.nextInt(OriginLoader.origins.size()));\n setOrigin(player, origin, reason, shouldResetPlayer(reason));\n openOriginSwapper(player, reason, OriginLoader.origins.indexOf(origin), 0, true);\n }\n\n @EventHandler\n public void onPlayerRespawn(PlayerRespawnEvent event) {\n if (event.getPlayer().getBedSpawnLocation() == null) {\n World world = getRespawnWorld(getOrigin(event.getPlayer()));\n event.setRespawnLocation(world.getSpawnLocation());\n }\n if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) return;\n FileConfiguration config = OriginsReborn.getInstance().getConfig();\n if (config.getBoolean(\"origin-selection.death-origin-change\")) {\n setOrigin(event.getPlayer(), null, PlayerSwapOriginEvent.SwapReason.DIED, false);\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.randomise\")) {\n selectRandomOrigin(event.getPlayer(), PlayerSwapOriginEvent.SwapReason.INITIAL);\n } else openOriginSwapper(event.getPlayer(), PlayerSwapOriginEvent.SwapReason.INITIAL, 0, 0, false);\n }\n }\n\n public PlayerSwapOriginEvent.SwapReason getReason(ItemStack icon) {\n return PlayerSwapOriginEvent.SwapReason.get(icon.getItemMeta().getPersistentDataContainer().get(swapTypeKey, PersistentDataType.STRING));\n }\n\n public static Origin getOrigin(Player player) {\n if (player.getPersistentDataContainer().has(originKey)) {\n return OriginLoader.originNameMap.get(player.getPersistentDataContainer().get(originKey, PersistentDataType.STRING));\n } else {\n String name = originFileConfiguration.getString(player.getUniqueId().toString());\n if (name == null) return null;\n player.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, name);\n return OriginLoader.originNameMap.get(name);\n }\n }\n public static void setOrigin(Player player, @Nullable Origin origin, PlayerSwapOriginEvent.SwapReason reason, boolean resetPlayer) {\n PlayerSwapOriginEvent swapOriginEvent = new PlayerSwapOriginEvent(player, reason, resetPlayer, getOrigin(player), origin);\n if (!swapOriginEvent.callEvent()) return;\n if (swapOriginEvent.getNewOrigin() == null) {\n originFileConfiguration.set(player.getUniqueId().toString(), null);\n player.getPersistentDataContainer().remove(originKey);\n saveOrigins();\n resetPlayer(player, swapOriginEvent.isResetPlayer());\n return;\n }\n originFileConfiguration.set(player.getUniqueId().toString(), swapOriginEvent.getNewOrigin().getName().toLowerCase());\n player.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, swapOriginEvent.getNewOrigin().getName().toLowerCase());\n saveOrigins();\n resetPlayer(player, swapOriginEvent.isResetPlayer());\n }\n\n\n private static File originFile;\n private static FileConfiguration originFileConfiguration;\n public OriginSwapper() {\n originFile = new File(OriginsReborn.getInstance().getDataFolder(), \"selected-origins.yml\");\n if (!originFile.exists()) {\n boolean ignored = originFile.getParentFile().mkdirs();\n OriginsReborn.getInstance().saveResource(\"selected-origins.yml\", false);\n }\n originFileConfiguration = new YamlConfiguration();\n try {\n originFileConfiguration.load(originFile);\n } catch (IOException | InvalidConfigurationException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void saveOrigins() {\n try {\n originFileConfiguration.save(originFile);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static class LineData {\n public static List<LineComponent> makeLineFor(String text, LineComponent.LineType type) {\n StringBuilder result = new StringBuilder();\n List<LineComponent> list = new ArrayList<>();\n List<String> splitLines = new ArrayList<>(Arrays.stream(text.split(\"\\n\", 2)).toList());\n StringBuilder otherPart = new StringBuilder();\n String firstLine = splitLines.remove(0);\n if (firstLine.contains(\" \") && getWidth(firstLine) > 140) {\n List<String> split = new ArrayList<>(Arrays.stream(firstLine.split(\" \")).toList());\n StringBuilder firstPart = new StringBuilder(split.get(0));\n split.remove(0);\n boolean canAdd = true;\n for (String s : split) {\n if (canAdd && getWidth(firstPart + \" \" + s) <= 140) {\n firstPart.append(\" \");\n firstPart.append(s);\n } else {\n canAdd = false;\n if (otherPart.length() > 0) otherPart.append(\" \");\n otherPart.append(s);\n }\n }\n firstLine = firstPart.toString();\n }\n for (String s : splitLines) {\n if (otherPart.length() > 0) otherPart.append(\"\\n\");\n otherPart.append(s);\n }\n if (type == LineComponent.LineType.DESCRIPTION) firstLine = '\\uF00A' + firstLine;\n for (char c : firstLine.toCharArray()) {\n result.append(c);\n result.append('\\uF000');\n }\n String finalText = firstLine;\n list.add(new LineComponent(\n Component.text(result.toString())\n .color(type == LineComponent.LineType.TITLE ? NamedTextColor.WHITE : TextColor.fromHexString(\"#CACACA\"))\n .append(Component.text(getInverse(finalText))),\n type\n ));\n if (otherPart.length() != 0) {\n list.addAll(makeLineFor(otherPart.toString(), type));\n }\n return list;\n }\n public static class LineComponent {\n public enum LineType {\n TITLE,\n DESCRIPTION\n }\n private final Component component;\n private final LineType type;\n\n public LineComponent(Component component, LineType type) {\n this.component = component;\n this.type = type;\n }\n\n public LineComponent() {\n this.type = LineType.DESCRIPTION;\n this.component = Component.empty();\n }\n\n public Component getComponent(int lineNumber) {\n @Subst(\"minecraft:text_line_0\") String formatted = \"minecraft:%stext_line_%s\".formatted(type == LineType.DESCRIPTION ? \"\" : \"title_\", lineNumber);\n return component.font(\n Key.key(formatted)\n );\n }\n }\n private final List<LineComponent> lines;\n public LineData(Origin origin) {\n lines = new ArrayList<>();\n lines.addAll(origin.getLineData());\n List<VisibleAbility> visibleAbilities = origin.getVisibleAbilities();\n int size = visibleAbilities.size();\n int count = 0;\n if (size > 0) lines.add(new LineComponent());\n for (VisibleAbility visibleAbility : visibleAbilities) {\n count++;\n lines.addAll(visibleAbility.getTitle());\n lines.addAll(visibleAbility.getDescription());\n if (count < size) lines.add(new LineComponent());\n }\n }\n public LineData(List<LineComponent> lines) {\n this.lines = lines;\n }\n\n public List<Component> getLines(int startingPoint) {\n List<Component> resultLines = new ArrayList<>();\n for (int i = startingPoint; i < startingPoint + 6 && i < lines.size(); i++) {\n resultLines.add(lines.get(i).getComponent(i - startingPoint));\n }\n return resultLines;\n }\n }\n}" }, { "identifier": "VisibleAbility", "path": "src/main/java/com/starshootercity/abilities/VisibleAbility.java", "snippet": "public interface VisibleAbility extends Ability {\n @NotNull List<OriginSwapper.LineData.LineComponent> getDescription();\n @NotNull List<OriginSwapper.LineData.LineComponent> getTitle();\n}" } ]
import com.starshootercity.OriginSwapper; import com.starshootercity.abilities.VisibleAbility; import net.kyori.adventure.key.Key; import org.jetbrains.annotations.NotNull; import java.util.List;
6,355
package com.starshootercity.abilities.impossible; public class ExtraReach implements VisibleAbility { @Override public @NotNull Key getKey() { return Key.key("origins:extra_reach"); } @Override
package com.starshootercity.abilities.impossible; public class ExtraReach implements VisibleAbility { @Override public @NotNull Key getKey() { return Key.key("origins:extra_reach"); } @Override
public @NotNull List<OriginSwapper.LineData.LineComponent> getDescription() {
0
2023-11-10 21:39:16+00:00
8k
SoBadFish/Report
src/main/java/org/sobadfish/report/command/ReportCommand.java
[ { "identifier": "ReportMainClass", "path": "src/main/java/org/sobadfish/report/ReportMainClass.java", "snippet": "public class ReportMainClass extends PluginBase {\n\n private static IDataManager dataManager;\n\n private static ReportMainClass mainClass;\n\n private ReportConfig reportConfig;\n\n private Config messageConfig;\n\n private Config adminPlayerConfig;\n\n private PlayerInfoManager playerInfoManager;\n\n private List<String> adminPlayers = new ArrayList<>();\n\n\n @Override\n public void onEnable() {\n mainClass = this;\n saveDefaultConfig();\n reloadConfig();\n sendMessageToConsole(\"&e举报系统正在加载\");\n if(!initSql()){\n sendMessageToConsole(\"&c无法接入数据库!\");\n dataManager = new ReportYamlManager(this);\n }\n this.getServer().getPluginManager().registerEvents(new ReportListener(),this);\n reportConfig = new ReportConfig(getConfig());\n saveResource(\"message.yml\",false);\n saveResource(\"players.yml\",false);\n messageConfig = new Config(this.getDataFolder()+\"/message.yml\",Config.YAML);\n adminPlayerConfig = new Config(this.getDataFolder()+\"/players.yml\",Config.YAML);\n adminPlayers = adminPlayerConfig.getStringList(\"admin-players\");\n playerInfoManager = new PlayerInfoManager();\n this.getServer().getCommandMap().register(\"report\",new ReportCommand(\"rp\"));\n this.getServer().getScheduler().scheduleRepeatingTask(this,playerInfoManager,20);\n sendMessageToConsole(\"举报系统加载完成\");\n }\n\n public List<String> getAdminPlayers() {\n return adminPlayers;\n }\n\n public Config getAdminPlayerConfig() {\n return adminPlayerConfig;\n }\n\n public void saveAdminPlayers(){\n adminPlayerConfig.set(\"admin-players\",adminPlayers);\n adminPlayerConfig.save();\n }\n\n public PlayerInfoManager getPlayerInfoManager() {\n return playerInfoManager;\n }\n\n public ReportConfig getReportConfig() {\n return reportConfig;\n }\n\n public Config getMessageConfig() {\n return messageConfig;\n }\n\n public static ReportMainClass getMainClass() {\n return mainClass;\n }\n\n private boolean initSql(){\n sendMessageToConsole(\"初始化数据库\");\n try {\n\n Class.forName(\"com.smallaswater.easysql.EasySql\");\n String user = getConfig().getString(\"mysql.username\");\n int port = getConfig().getInt(\"mysql.port\");\n String url = getConfig().getString(\"mysql.host\");\n String passWorld = getConfig().getString(\"mysql.password\");\n String table = getConfig().getString(\"mysql.database\");\n UserData data = new UserData(user, passWorld, url, port, table);\n SqlManager sql = new SqlManager(this, data);\n dataManager = new ReportSqlManager(sql);\n if (!((ReportSqlManager) dataManager).createTable()) {\n sendMessageToConsole(\"&c创建表单 \" + ReportSqlManager.SQL_TABLE + \" 失败!\");\n }\n sendMessageToConsole(\"&a数据库初始化完成\");\n return true;\n\n }catch (Exception e) {\n sendMessageToConsole(\"&c数据库初始化失败\");\n return false;\n }\n\n }\n\n public static IDataManager getDataManager() {\n return dataManager;\n }\n\n private static void sendMessageToConsole(String msg){\n sendMessageToObject(msg,null);\n }\n\n public static void sendMessageToAdmin(String msg){\n for(Player player: Server.getInstance().getOnlinePlayers().values()){\n if(player.isOp() || getMainClass().adminPlayers.contains(player.getName())){\n sendMessageToObject(msg,player);\n }\n }\n }\n\n public static void sendMessageToObject(String msg, CommandSender target){\n if(target == null){\n mainClass.getLogger().info(formatString(msg));\n }else{\n target.sendMessage(formatString(msg));\n }\n }\n\n public static void sendMessageToAll(String msg){\n Server.getInstance().broadcastMessage(formatString(msg));\n }\n\n\n private static String formatString(String str){\n return TextFormat.colorize('&',\"&7[&e举报系统&7] &r>&r \"+str);\n }\n}" }, { "identifier": "DisplayCustomForm", "path": "src/main/java/org/sobadfish/report/form/DisplayCustomForm.java", "snippet": "public class DisplayCustomForm {\n\n private final int id;\n\n public static int getRid(){\n return Utils.rand(11900,21000);\n }\n\n public DisplayCustomForm(int id){\n this.id = id;\n }\n\n\n\n public int getId() {\n return id;\n }\n\n public static LinkedHashMap<Player, DisplayCustomForm> DISPLAY_FROM = new LinkedHashMap<>();\n\n public void disPlay(Player player, String target){\n\n FormWindowCustom formWindowCustom = new FormWindowCustom(TextFormat.colorize('&',\"&b举报系统\"));\n Config msg = ReportMainClass.getMainClass().getMessageConfig();\n formWindowCustom.addElement(new ElementLabel(TextFormat.colorize('&'\n ,msg.getString(\"report-form-msg\"))));\n List<String> onLinePlayers = new ArrayList<>();\n for(Player online: Server.getInstance().getOnlinePlayers().values()){\n if(online.equals(player)){\n continue;\n }\n onLinePlayers.add(online.getName());\n }\n if(target != null){\n onLinePlayers.add(target);\n }\n\n if(onLinePlayers.size() == 0){\n ReportMainClass.sendMessageToObject(\"&c没有可以举报的玩家\",player);\n return;\n }\n\n formWindowCustom.addElement(new ElementDropdown(\"请选择举报的玩家\",onLinePlayers,onLinePlayers.size()-1));\n List<String> showMsg = new ArrayList<>();\n for(String s:msg.getStringList(\"report-list\") ){\n showMsg.add(TextFormat.colorize('&',s));\n }\n formWindowCustom.addElement(new ElementDropdown(\"请选择举报原因\",showMsg));\n formWindowCustom.addElement(new ElementInput(\"请输入举报理由\"));\n\n player.showFormWindow(formWindowCustom,getId());\n DISPLAY_FROM.put(player,this);\n\n }\n\n public void onListener(Player player,FormResponseCustom responseCustom){\n PlayerInfo info = ReportMainClass.getMainClass().getPlayerInfoManager().getInfo(player.getName());\n String playerName = responseCustom.getDropdownResponse(1).getElementContent();\n String msg = responseCustom.getDropdownResponse(2).getElementContent()+\"&\"+TextFormat.colorize('&',responseCustom.getInputResponse(3));\n if(info != null){\n switch (info.addReport(playerName)){\n case SUCCESS:\n ReportMainClass.getDataManager().pullReport(playerName,msg,player.getName());\n ReportMainClass.sendMessageToObject(\"&b举报成功! 感谢你对服务器建设的支持 &7(等待管理员处理)\",player);\n break;\n case COLD:\n ReportMainClass.sendMessageToObject(\"&c举报太频繁了,请在 &r \"+info.getCold()+\" &c秒后重试\",player);\n break;\n case DAY_MAX:\n ReportMainClass.sendMessageToObject(\"&c今日举报次数达到上限,请明天再进行举报吧\",player);\n break;\n case HAS_TARGET:\n ReportMainClass.sendMessageToObject(\"&c你今日已经举报过他了\",player);\n break;\n case MY:\n ReportMainClass.sendMessageToObject(\"&c你不能举报自己\",player);\n break;\n default:break;\n }\n }\n\n }\n\n\n\n}" }, { "identifier": "DisplayForm", "path": "src/main/java/org/sobadfish/report/form/DisplayForm.java", "snippet": "public class DisplayForm {\n\n private static final int ITEM_SIZE = 6;\n\n public static LinkedHashMap<Player, DisplayForm> DISPLAY_FROM = new LinkedHashMap<>();\n\n private ArrayList<BaseClickButton> clickButtons = new ArrayList<>();\n\n private List<String> players = new ArrayList<>();\n\n private int page = 1;\n\n private int id;\n\n public DisplayForm(int id){\n this.id = id;\n }\n\n public void setClickButtons(ArrayList<BaseClickButton> clickButtons) {\n this.clickButtons = clickButtons;\n }\n\n public ArrayList<BaseClickButton> getClickButtons() {\n return clickButtons;\n }\n\n public int getId() {\n return id;\n }\n\n public static int getRid(){\n return Utils.rand(1890,118025);\n }\n\n public void disPlay(Player player){\n FormWindowSimple simple = new FormWindowSimple(TextFormat.colorize('&',\"&b举报系统\"),\"\");\n ArrayList<BaseClickButton> buttons = new ArrayList<>();\n if(players.size() == 0) {\n players = ReportMainClass.getDataManager().getPlayers();\n }\n if(players.size() > 0){\n for(String s: getArrayListByPage(page,players)){\n List<Report> reports = ReportMainClass.getDataManager().getReports(s);\n if(reports.size() == 0){\n continue;\n }\n Report nRepot = reports.get(0);\n String str = s.trim();\n str += \"\\n&4[New] &c\"+nRepot.getTime()+\" &r \"+reports.size()+\" &2条相关记录\";\n buttons.add(new BaseClickButton(new ElementButton(TextFormat.colorize('&',str),new ElementButtonImageData(\"path\"\n ,\"textures/ui/Friend2\")),s) {\n @Override\n public void onClick(Player player) {\n DisplayManageForm fromButton = new DisplayManageForm(DisplayManageForm.getRid());\n fromButton.disPlay(player,getTarget());\n\n }\n });\n }\n }else{\n ReportMainClass.sendMessageToObject(\"&c无举报记录\",player);\n return;\n }\n if(mathPage((ArrayList<?>) players) > 1) {\n if (page == 1) {\n addNext(buttons);\n }else if(page != mathPage((ArrayList<?>) players)){\n addLast(buttons);\n addNext(buttons);\n\n }else{\n addLast(buttons);\n\n }\n }\n for(BaseClickButton button: buttons){\n simple.addButton(button.getButton());\n }\n player.showFormWindow(simple,getId());\n setClickButtons(buttons);\n DISPLAY_FROM.put(player,this);\n\n }\n\n private void addLast(ArrayList<BaseClickButton> buttons){\n buttons.add(new BaseClickButton(new ElementButton(\"上一页\", new ElementButtonImageData(\"path\", \"textures/ui/arrow_dark_left_stretch\")), null) {\n @Override\n public void onClick(Player player) {\n DisplayForm from = DISPLAY_FROM.get(player);\n from.setId(getRid());\n from.page--;\n from.disPlay(player);\n\n\n }\n });\n }\n\n private void addNext(ArrayList<BaseClickButton> buttons){\n buttons.add(new BaseClickButton(new ElementButton(\"下一页\", new ElementButtonImageData(\"path\", \"textures/ui/arrow_dark_right_stretch\")), null) {\n @Override\n public void onClick(Player player) {\n DisplayForm from = DISPLAY_FROM.get(player);\n from.setId(getRid());\n from.page++;\n from.disPlay(player);\n }\n });\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public <T> ArrayList<T> getArrayListByPage(int page, List<T> list){\n ArrayList<T> button = new ArrayList<>();\n for(int i = (page - 1) * ITEM_SIZE; i < ITEM_SIZE + ((page - 1) * ITEM_SIZE);i++){\n if(list.size() > i){\n button.add(list.get(i));\n }\n }\n return button;\n }\n\n public int mathPage(ArrayList<?> button){\n if(button.size() == 0){\n return 1;\n }\n return (int) Math.ceil(button.size() / (double)ITEM_SIZE);\n }\n\n\n\n}" }, { "identifier": "DisplayHistoryForm", "path": "src/main/java/org/sobadfish/report/form/DisplayHistoryForm.java", "snippet": "public class DisplayHistoryForm {\n\n private ArrayList<BaseClickButton> clickButtons = new ArrayList<>();\n\n public static LinkedHashMap<Player, DisplayHistoryForm> DISPLAY_FROM = new LinkedHashMap<>();\n\n private final int id;\n\n public static int getRid(){\n return Utils.rand(31000,41000);\n }\n\n public ArrayList<BaseClickButton> getClickButtons() {\n return clickButtons;\n }\n\n public String target;\n\n public DisplayHistoryForm(int id){\n this.id = id;\n }\n\n\n public int getId() {\n return id;\n }\n\n public void disPlay(Player player,String target) {\n FormWindowSimple simple = new FormWindowSimple(TextFormat.colorize('&', \"&b举报系统 &7—— &e记录\"), \"\");\n\n int reportsSize = ReportMainClass.getDataManager().getHistoryPlayers(player.getName(),target).size();\n\n List<String> reportsList = ReportMainClass.getDataManager().getHistoryPlayers(null,target);\n\n if(reportsList.size() == 0){\n ReportMainClass.sendMessageToObject(\"&c暂无处理记录\",player);\n return;\n }\n ArrayList<BaseClickButton> buttons = new ArrayList<>();\n String str = \"服务器累计处理 \"+reportsList.size()+\" 条举报! 您已处理 \"+reportsSize+\" 条\";\n simple.setContent(str);\n for(String s:reportsList){\n List<Report> reps = ReportMainClass.getDataManager().getHistoryReports(s);\n Report rp = reps.get(0);\n String s2 = s+\"\\n&c[New]\"+rp.getManagerTime()+\" &r\"+reps.size()+\" &2条举报记录\";\n buttons.add(new BaseClickButton(new ElementButton(TextFormat.colorize('&',s2),new ElementButtonImageData(\"path\"\n ,\"textures/ui/Friend2\")),s) {\n @Override\n public void onClick(Player player) {\n FormWindowSimple simple1 = new FormWindowSimple(TextFormat.colorize('&',\"&b举报系统 &7—— &e记录 &7—— &2\"+getTarget())\n ,\"\");\n String target = getTarget();\n StringBuilder stringBuilder = new StringBuilder();\n List<Report> reports = ReportMainClass.getDataManager().getHistoryReports(target);\n stringBuilder.append(\"&l&r被举报玩家: &r&a\").append(target).append(\"&r\\n\\n\");\n stringBuilder.append(\"&r&l举报原因:&r \\n\");\n for(Report report: reports){\n String[] rel = Utils.splitMsg(report.getReportMessage());\n\n stringBuilder.append(\" &7[\").append(report.getTime()).append(\"]&r &e\")\n .append(report.getTarget()).append(\" &7:>>&r\\n\").append(\"&7(&l\")\n .append(rel[0]).append(\"&r&7)&r: \").append(rel[1]).append(\"&r\\n\");\n }\n stringBuilder.append(\"\\n&r&l处理记录: \").append(\"\\n\");\n StringBuilder mg = new StringBuilder();\n for(Report report: reports){\n if(!\"\".equalsIgnoreCase(report.getManager())){\n mg.append(\" &l&7[&e\").append(report.getManagerTime()).append(\"&7] &2\")\n .append(report.getManager()).append(\"&r: \").append(report.getManagerMsg()).append(\"&r\\n\");\n }\n\n }\n stringBuilder.append(mg);\n simple1.setContent(TextFormat.colorize('&',stringBuilder.toString()));\n player.showFormWindow(simple1,getRid());\n }\n });\n\n }\n for(BaseClickButton button: buttons){\n simple.addButton(button.getButton());\n }\n\n setClickButtons(buttons);\n player.showFormWindow(simple,getId());\n DISPLAY_FROM.put(player,this);\n\n\n }\n\n public void setClickButtons(ArrayList<BaseClickButton> clickButtons) {\n this.clickButtons = clickButtons;\n }\n\n}" } ]
import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.command.Command; import cn.nukkit.command.CommandSender; import org.sobadfish.report.ReportMainClass; import org.sobadfish.report.form.DisplayCustomForm; import org.sobadfish.report.form.DisplayForm; import org.sobadfish.report.form.DisplayHistoryForm; import java.util.List;
4,139
package org.sobadfish.report.command; /** * @author SoBadFish * 2022/1/21 */ public class ReportCommand extends Command { public ReportCommand(String name) { super(name); } @Override public boolean execute(CommandSender commandSender, String s, String[] strings) { if(strings.length == 0) { if (commandSender instanceof Player) { DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,null); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } return true; } String cmd = strings[0]; if("r".equalsIgnoreCase(cmd)){ if(strings.length > 1){ DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,strings[1]); return true; } } if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){ switch (cmd){ case "a": if(commandSender instanceof Player){
package org.sobadfish.report.command; /** * @author SoBadFish * 2022/1/21 */ public class ReportCommand extends Command { public ReportCommand(String name) { super(name); } @Override public boolean execute(CommandSender commandSender, String s, String[] strings) { if(strings.length == 0) { if (commandSender instanceof Player) { DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,null); }else{ ReportMainClass.sendMessageToObject("&c请不要在控制台执行", commandSender); } return true; } String cmd = strings[0]; if("r".equalsIgnoreCase(cmd)){ if(strings.length > 1){ DisplayCustomForm displayCustomForm = new DisplayCustomForm(DisplayCustomForm.getRid()); displayCustomForm.disPlay((Player) commandSender,strings[1]); return true; } } if(commandSender.isOp() || ReportMainClass.getMainClass().getAdminPlayers().contains(commandSender.getName())){ switch (cmd){ case "a": if(commandSender instanceof Player){
DisplayForm displayFrom = new DisplayForm(DisplayForm.getRid());
2
2023-11-15 03:08:23+00:00
8k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/InventoryAPIImpl.java
[ { "identifier": "InventoryAPI", "path": "api/src/main/java/kor/toxicity/inventory/api/InventoryAPI.java", "snippet": "@SuppressWarnings(\"unused\")\npublic abstract class InventoryAPI extends JavaPlugin {\n private static InventoryAPI api;\n\n private ImageManager imageManager;\n private FontManager fontManager;\n private ResourcePackManager resourcePackManager;\n\n @Override\n public final void onLoad() {\n if (api != null) throw new SecurityException();\n api = this;\n }\n\n public static @NotNull InventoryAPI getInstance() {\n return Objects.requireNonNull(api);\n }\n\n public final void setFontManager(@NotNull FontManager fontManager) {\n this.fontManager = Objects.requireNonNull(fontManager);\n }\n\n public final @NotNull FontManager getFontManager() {\n return Objects.requireNonNull(fontManager);\n }\n\n public final @NotNull ImageManager getImageManager() {\n return Objects.requireNonNull(imageManager);\n }\n\n public final void setImageManager(@NotNull ImageManager imageManager) {\n this.imageManager = Objects.requireNonNull(imageManager);\n }\n\n public final void setResourcePackManager(@NotNull ResourcePackManager resourcePackManager) {\n this.resourcePackManager = Objects.requireNonNull(resourcePackManager);\n }\n\n public @NotNull ResourcePackManager getResourcePackManager() {\n return Objects.requireNonNull(resourcePackManager);\n }\n public final void reload() {\n reload(true);\n }\n\n public abstract void reload(boolean callEvent);\n public void reload(@NotNull Consumer<Long> longConsumer) {\n var pluginManager = Bukkit.getPluginManager();\n pluginManager.callEvent(new PluginReloadStartEvent());\n Bukkit.getScheduler().runTaskAsynchronously(this, () -> {\n var time = System.currentTimeMillis();\n reload(false);\n var time2 = System.currentTimeMillis() - time;\n Bukkit.getScheduler().runTask(this, () -> {\n pluginManager.callEvent(new PluginReloadEndEvent());\n longConsumer.accept(time2);\n });\n });\n }\n\n public @NotNull ItemStack getEmptyItem(@NotNull Consumer<ItemMeta> metaConsumer) {\n var stack = new ItemStack(getResourcePackManager().getEmptyMaterial());\n var meta = stack.getItemMeta();\n assert meta != null;\n metaConsumer.accept(meta);\n meta.setCustomModelData(1);\n stack.setItemMeta(meta);\n return stack;\n }\n public abstract @NotNull MiniMessage miniMessage();\n public abstract @NotNull GuiFont defaultFont();\n public abstract void openGui(@NotNull Player player, @NotNull Gui gui, @NotNull GuiType type, long delay, @NotNull GuiExecutor executor);\n}" }, { "identifier": "PluginReloadEndEvent", "path": "api/src/main/java/kor/toxicity/inventory/api/event/PluginReloadEndEvent.java", "snippet": "public final class PluginReloadEndEvent extends Event implements InventoryAPIEvent {\n public PluginReloadEndEvent() {\n super(true);\n }\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return HANDLER_LIST;\n }\n public static HandlerList getHandlerList() {\n return HANDLER_LIST;\n }\n}" }, { "identifier": "PluginReloadStartEvent", "path": "api/src/main/java/kor/toxicity/inventory/api/event/PluginReloadStartEvent.java", "snippet": "public final class PluginReloadStartEvent extends Event implements InventoryAPIEvent {\n public PluginReloadStartEvent() {\n super(true);\n }\n @NotNull\n @Override\n public HandlerList getHandlers() {\n return HANDLER_LIST;\n }\n public static HandlerList getHandlerList() {\n return HANDLER_LIST;\n }\n}" }, { "identifier": "InventoryManager", "path": "api/src/main/java/kor/toxicity/inventory/api/manager/InventoryManager.java", "snippet": "public interface InventoryManager {\n void reload();\n}" }, { "identifier": "FontManagerImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/manager/FontManagerImpl.java", "snippet": "public class FontManagerImpl implements FontManager {\n private final FontRegistryImpl fontRegistry = new FontRegistryImpl();\n @Override\n public void reload() {\n fontRegistry.clear();\n PluginUtil.loadFolder(\"fonts\", f -> {\n var name = PluginUtil.getFileName(f);\n switch (name.extension().toLowerCase()) {\n case \"ttf\", \"oft\" -> {\n try (var stream = new BufferedInputStream(new FileInputStream(f))) {\n fontRegistry.register(name.name(), Font.createFont(Font.TRUETYPE_FONT, stream));\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to read this font: \" + f.getName());\n PluginUtil.warn(\"Reason: \" + e.getMessage());\n }\n }\n }\n });\n }\n\n @Override\n public @NotNull Registry<Font> getRegistry() {\n return fontRegistry;\n }\n}" }, { "identifier": "ImageManagerImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/manager/ImageManagerImpl.java", "snippet": "public class ImageManagerImpl implements ImageManager {\n private final ImageRegistryImpl imageRegistry = new ImageRegistryImpl();\n @Override\n public void reload() {\n imageRegistry.clear();\n PluginUtil.loadFolder(\"images\", f -> {\n var name = PluginUtil.getFileName(f);\n if (name.extension().equalsIgnoreCase(\"png\")) {\n try {\n imageRegistry.register(name.name(), ImageIO.read(f));\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to read this image: \" + f.getName());\n PluginUtil.warn(\"Reason: \" + e.getMessage());\n }\n }\n });\n }\n\n @Override\n public @NotNull Registry<BufferedImage> getRegistry() {\n return imageRegistry;\n }\n}" }, { "identifier": "ResourcePackManagerImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/manager/ResourcePackManagerImpl.java", "snippet": "public class ResourcePackManagerImpl implements ResourcePackManager {\n private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();\n private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>();\n private final List<ImageObjectGeneratorImpl> images = new ArrayList<>();\n @Getter\n private Material emptyMaterial = Material.DIAMOND_HORSE_ARMOR;\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n @Override\n public void reload() {\n var topFolder = getFile(getFile(InventoryAPI.getInstance().getDataFolder(), \".generated\"), \"assets\");\n var assets = getFile(topFolder, \"inventory\");\n var font = getFile(assets, \"font\");\n var fontFont = getFile(font, \"font\");\n var textures = getFile(assets, \"textures\");\n var texturesFont = getFile(textures, \"font\");\n var texturesFontGui = getFile(texturesFont, \"gui\");\n var texturesFontFont = getFile(texturesFont, \"font\");\n var models = getFile(getFile(getFile(topFolder, \"minecraft\"), \"models\"),\"item\");\n\n var config = new File(InventoryAPI.getInstance().getDataFolder(), \"config.yml\");\n if (!config.exists()) InventoryAPI.getInstance().saveResource(\"config.yml\", false);\n try {\n var yaml = YamlConfiguration.loadConfiguration(config).getString(\"default-empty-material\");\n if (yaml != null) emptyMaterial = Material.valueOf(yaml.toUpperCase());\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to load config.yml\");\n PluginUtil.warn(\"Reason: \" + e.getMessage());\n }\n var emptyMaterialLowerCase = emptyMaterial.name().toLowerCase();\n var modelsFile = new File(models, emptyMaterialLowerCase + \".json\");\n var modelsJson = new JsonObjectBuilder()\n .add(\"parent\", \"item/generated\")\n .add(\"textures\", new JsonObjectBuilder()\n .add(\"layer0\", \"minecraft:item/\" + emptyMaterialLowerCase)\n .build()\n )\n .add(\"overrides\", new JsonArrayBuilder()\n .add(new JsonObjectBuilder()\n .add(\"predicate\", new JsonObjectBuilder()\n .add(\"custom_model_data\", 1)\n .build())\n .add(\"model\", \"inventory:item/empty\")\n .build()\n )\n .build()\n )\n .build();\n try (var writer = new JsonWriter(new BufferedWriter(new FileWriter(modelsFile)))) {\n gson.toJson(modelsJson, writer);\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to make a empty material file.\");\n }\n\n fonts.forEach(f -> {\n var targetFolder = new File(texturesFontFont, f.getFont().getName());\n var jsonFolder = new File(fontFont, f.getFontTitle() + \".json\");\n var guiFont = f.getFont();\n var available = guiFont.getAvailableChar();\n if (!targetFolder.exists()) {\n targetFolder.mkdir();\n var i = 0;\n var n = 1;\n var yAxis = (float) GuiFont.VERTICAL_SIZE * guiFont.getMetrics().getHeight();\n while (i < available.size()) {\n var image = new BufferedImage(16 * guiFont.getSize(), (int) (yAxis * 16), BufferedImage.TYPE_INT_ARGB);\n var graphics = image.createGraphics();\n graphics.setFont(guiFont.getFont());\n graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));\n graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);\n graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);\n find: for (int i1 = 0; i1 < 16; i1++) {\n for (int i2 = 0; i2 < 16; i2++) {\n var getIndex = i + i1 * 16 + i2;\n if (getIndex >= available.size()) break find;\n graphics.drawString(Character.toString(available.get(getIndex)), (float) (i2 * guiFont.getSize()), (i1 + 0.75F) * yAxis);\n }\n }\n graphics.dispose();\n var pngName = f.getFont().getName() + \"_\" + (n++) + \".png\";\n try {\n ImageIO.write(image, \"png\", new File(targetFolder, pngName));\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save this file: \" + pngName);\n }\n i += 256;\n }\n }\n if (!jsonFolder.exists()) {\n var i = 0;\n var n = 1;\n var json = new JsonArrayBuilder()\n .add(new JsonObjectBuilder()\n .add(\"type\", \"space\")\n .add(\"advances\", new JsonObjectBuilder()\n .add(\" \", 4)\n .build())\n .build())\n .build();\n while (i < available.size()) {\n var charArray = new JsonArray();\n find: for (int i1 = 0; i1 < 16; i1++) {\n var sb = new StringBuilder();\n for (int i2 = 0; i2 < 16; i2++) {\n var getIndex = i + i1 * 16 + i2;\n if (getIndex >= available.size()) break find;\n sb.append(available.get(getIndex));\n }\n charArray.add(sb.toString());\n }\n var pngName = f.getFont().getName() + \"_\" + (n++) + \".png\";\n json.add(new JsonObjectBuilder()\n .add(\"type\", \"bitmap\")\n .add(\"file\", \"inventory:font/font/\" + f.getFont().getName() + \"/\" + pngName)\n .add(\"ascent\", f.getAscent())\n .add(\"height\", f.getHeight())\n .add(\"chars\", charArray)\n .build());\n i += 256;\n }\n try (var writer = new JsonWriter(new BufferedWriter(new FileWriter(jsonFolder)))) {\n gson.toJson(new JsonObjectBuilder()\n .add(\"providers\", json)\n .build(), writer);\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save gui.json.\");\n }\n }\n });\n\n var array = new JsonArray();\n images.stream().sorted().forEach(i -> {\n var name = i.getImage().name() + \".png\";\n try {\n ImageIO.write(i.getImage().image(), \"png\", new File(texturesFontGui, name));\n array.add(new JsonObjectBuilder()\n .add(\"type\", \"bitmap\")\n .add(\"file\", \"inventory:font/gui/\" + name)\n .add(\"ascent\", i.getAscent())\n .add(\"height\", i.getHeight())\n .add(\"chars\", new JsonArrayBuilder()\n .add(i.getSerialChar())\n .build())\n .build());\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save this image: \" + name);\n }\n });\n try (var writer = new JsonWriter(new BufferedWriter(new FileWriter(new File(font, \"gui.json\"))))) {\n gson.toJson(new JsonObjectBuilder()\n .add(\"providers\", array)\n .build(), writer);\n } catch (Exception e) {\n PluginUtil.warn(\"Unable to save gui.json.\");\n }\n\n ImageObjectGeneratorImpl.initialize();\n fonts.clear();\n images.clear();\n }\n\n @Override\n public @NotNull GuiObjectGenerator registerTask(@NotNull GuiResource resource, int height, int ascent) {\n if (resource instanceof GuiFont guiFont) {\n var generator = new FontObjectGeneratorImpl(guiFont, height, ascent);\n fonts.add(generator);\n return generator;\n } else if (resource instanceof GuiImage image) {\n var generator = new ImageObjectGeneratorImpl(image, height, ascent);\n images.add(generator);\n return generator;\n } else throw new UnsupportedOperationException(\"unsupported type found.\");\n }\n\n @SuppressWarnings(\"ResultOfMethodCallIgnored\")\n private static File getFile(File mother, String dir) {\n var file = new File(mother, dir);\n if (!file.exists()) file.mkdir();\n return file;\n }\n}" }, { "identifier": "AdventureUtil", "path": "plugin/src/main/java/kor/toxicity/inventory/util/AdventureUtil.java", "snippet": "public class AdventureUtil {\n private static final Key SPACE_KEY = Key.key(\"inventory:space\");\n private AdventureUtil() {\n throw new SecurityException();\n }\n public static String parseChar(int i) {\n if (i <= 0xFFFF) return Character.toString((char) i);\n else {\n var t = i - 0x10000;\n return Character.toString((t >>> 10) + 0xD800) + Character.toString((t & ((1 << 10) - 1)) + 0xDC00);\n }\n }\n\n public static Component getSpaceFont(int i) {\n return Component.text(parseChar(i + 0xD0000)).font(SPACE_KEY);\n }\n}" }, { "identifier": "PluginUtil", "path": "plugin/src/main/java/kor/toxicity/inventory/util/PluginUtil.java", "snippet": "@SuppressWarnings(\"ResultOfMethodCallIgnored\")\npublic class PluginUtil {\n private PluginUtil() {\n throw new SecurityException();\n }\n\n public static void loadFolder(String dir, Consumer<File> fileConsumer) {\n var dataFolder = InventoryAPI.getInstance().getDataFolder();\n if (!dataFolder.exists()) dataFolder.mkdir();\n var folder = new File(dataFolder, dir);\n if (!folder.exists()) folder.mkdir();\n var listFiles = folder.listFiles();\n if (listFiles != null) for (File listFile : listFiles) {\n fileConsumer.accept(listFile);\n }\n }\n\n public static FileName getFileName(File file) {\n var name = file.getName().split(\"\\\\.\");\n return new FileName(name[0], name.length > 1 ? name[1] : \"\");\n }\n\n public static void warn(String message) {\n InventoryAPI.getInstance().getLogger().warning(message);\n }\n\n public record FileName(String name, String extension) {\n }\n}" } ]
import kor.toxicity.inventory.api.InventoryAPI; import kor.toxicity.inventory.api.event.PluginReloadEndEvent; import kor.toxicity.inventory.api.event.PluginReloadStartEvent; import kor.toxicity.inventory.api.gui.*; import kor.toxicity.inventory.api.manager.InventoryManager; import kor.toxicity.inventory.manager.FontManagerImpl; import kor.toxicity.inventory.manager.ImageManagerImpl; import kor.toxicity.inventory.manager.ResourcePackManagerImpl; import kor.toxicity.inventory.util.AdventureUtil; import kor.toxicity.inventory.util.PluginUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.minimessage.Context; import net.kyori.adventure.text.minimessage.MiniMessage; import net.kyori.adventure.text.minimessage.tag.Tag; import net.kyori.adventure.text.minimessage.tag.resolver.ArgumentQueue; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.*; import java.util.List; import java.util.jar.JarFile;
4,386
package kor.toxicity.inventory; @SuppressWarnings("unused") public final class InventoryAPIImpl extends InventoryAPI { private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text("")); private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!")); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder() .tags(TagResolver.builder() .resolvers( TagResolver.standard(), TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> { if (argumentQueue.hasNext()) { var next = argumentQueue.pop().value(); try { return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next))); } catch (Exception e) { return ERROR_TAG; } } else return NONE_TAG; }) ) .build() ) .postProcessor(c -> { var style = c.style(); if (style.color() == null) style = style.color(NamedTextColor.WHITE); var deco = style.decorations(); var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class); for (TextDecoration value : TextDecoration.values()) { var get = deco.get(value); if (get == null || get == TextDecoration.State.NOT_SET) { newDeco.put(value, TextDecoration.State.FALSE); } else newDeco.put(value, get); } style = style.decorations(newDeco); return c.style(style); }) .build(); private GuiFont font; private final List<InventoryManager> managers = new ArrayList<>(); private static final ItemStack AIR = new ItemStack(Material.AIR); @Override public void onEnable() { var pluginManager = Bukkit.getPluginManager(); var fontManager = new FontManagerImpl(); setFontManager(fontManager); var imageManager = new ImageManagerImpl(); setImageManager(imageManager);
package kor.toxicity.inventory; @SuppressWarnings("unused") public final class InventoryAPIImpl extends InventoryAPI { private static final Tag NONE_TAG = Tag.selfClosingInserting(Component.text("")); private static final Tag ERROR_TAG = Tag.selfClosingInserting(Component.text("error!")); private static final MiniMessage MINI_MESSAGE = MiniMessage.builder() .tags(TagResolver.builder() .resolvers( TagResolver.standard(), TagResolver.resolver("space", (ArgumentQueue argumentQueue, Context context) -> { if (argumentQueue.hasNext()) { var next = argumentQueue.pop().value(); try { return Tag.selfClosingInserting(AdventureUtil.getSpaceFont(Integer.parseInt(next))); } catch (Exception e) { return ERROR_TAG; } } else return NONE_TAG; }) ) .build() ) .postProcessor(c -> { var style = c.style(); if (style.color() == null) style = style.color(NamedTextColor.WHITE); var deco = style.decorations(); var newDeco = new EnumMap<TextDecoration, TextDecoration.State>(TextDecoration.class); for (TextDecoration value : TextDecoration.values()) { var get = deco.get(value); if (get == null || get == TextDecoration.State.NOT_SET) { newDeco.put(value, TextDecoration.State.FALSE); } else newDeco.put(value, get); } style = style.decorations(newDeco); return c.style(style); }) .build(); private GuiFont font; private final List<InventoryManager> managers = new ArrayList<>(); private static final ItemStack AIR = new ItemStack(Material.AIR); @Override public void onEnable() { var pluginManager = Bukkit.getPluginManager(); var fontManager = new FontManagerImpl(); setFontManager(fontManager); var imageManager = new ImageManagerImpl(); setImageManager(imageManager);
var resourcePackManager = new ResourcePackManagerImpl();
6
2023-11-13 00:19:46+00:00
8k
GoogleCloudPlatform/dataflow-ordered-processing
beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedEventProcessor.java
[ { "identifier": "Builder", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java", "snippet": "@AutoValue.Builder\npublic abstract static class Builder {\n\n public abstract Builder setSequenceNumber(long value);\n\n public abstract Builder setReceivedOrder(long value);\n\n public abstract Builder setProcessingTime(Instant value);\n\n public abstract Builder setEventBufferedTime(Instant value);\n\n public abstract Builder setQueriedBufferedEvents(QueriedBufferedEvents value);\n\n public abstract Builder setClearedBufferedEvents(ClearedBufferedEvents value);\n\n public abstract OrderedProcessingDiagnosticEvent build();\n}" }, { "identifier": "ClearedBufferedEvents", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java", "snippet": "@DefaultSchema(AutoValueSchema.class)\n@AutoValue\npublic abstract static class ClearedBufferedEvents {\n\n public static ClearedBufferedEvents create(Instant rangeStart, Instant rangeEnd) {\n return builder().setRangeStart(rangeStart).setRangeEnd(rangeEnd).build();\n }\n\n public abstract Instant getRangeStart();\n\n public abstract Instant getRangeEnd();\n\n public static Builder builder() {\n return new AutoValue_OrderedProcessingDiagnosticEvent_ClearedBufferedEvents.Builder();\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder setRangeStart(Instant value);\n\n public abstract Builder setRangeEnd(Instant value);\n\n public abstract ClearedBufferedEvents build();\n }\n}" }, { "identifier": "QueriedBufferedEvents", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/OrderedProcessingDiagnosticEvent.java", "snippet": "@DefaultSchema(AutoValueSchema.class)\n@AutoValue\npublic abstract static class QueriedBufferedEvents {\n\n public static QueriedBufferedEvents create(Instant queryStart, Instant queryEnd,\n Instant firstReturnedEvent) {\n return builder().setQueryStart(queryStart).setQueryEnd(queryEnd)\n .setFirstReturnedEvent(firstReturnedEvent).build();\n }\n\n public abstract Instant getQueryStart();\n\n public abstract Instant getQueryEnd();\n\n @Nullable\n public abstract Instant getFirstReturnedEvent();\n\n public static Builder builder() {\n return new org.apache.beam.sdk.extensions.ordered.AutoValue_OrderedProcessingDiagnosticEvent_QueriedBufferedEvents.Builder();\n }\n\n @AutoValue.Builder\n public abstract static class Builder {\n\n public abstract Builder setQueryStart(Instant value);\n\n public abstract Builder setQueryEnd(Instant value);\n\n public abstract Builder setFirstReturnedEvent(Instant value);\n\n public abstract QueriedBufferedEvents build();\n }\n}" }, { "identifier": "ProcessingStateCoder", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/ProcessingState.java", "snippet": "static class ProcessingStateCoder<KeyT> extends Coder<ProcessingState<KeyT>> {\n\n private static final NullableCoder<Long> NULLABLE_LONG_CODER = NullableCoder.of(\n VarLongCoder.of());\n private static final Coder<Long> LONG_CODER = VarLongCoder.of();\n private static final VarIntCoder INTEGER_CODER = VarIntCoder.of();\n private static final BooleanCoder BOOLEAN_CODER = BooleanCoder.of();\n\n private Coder<KeyT> keyCoder;\n\n public static <KeyT> ProcessingStateCoder<KeyT> of(Coder<KeyT> keyCoder) {\n ProcessingStateCoder<KeyT> result = new ProcessingStateCoder<>();\n result.keyCoder = keyCoder;\n return result;\n }\n\n @Override\n public void encode(ProcessingState<KeyT> value, OutputStream outStream) throws IOException {\n NULLABLE_LONG_CODER.encode(value.getLastOutputSequence(), outStream);\n NULLABLE_LONG_CODER.encode(value.getEarliestBufferedSequence(), outStream);\n NULLABLE_LONG_CODER.encode(value.getLatestBufferedSequence(), outStream);\n LONG_CODER.encode(value.getBufferedRecordCount(), outStream);\n LONG_CODER.encode(value.getRecordsReceived(), outStream);\n LONG_CODER.encode(value.getDuplicates(), outStream);\n LONG_CODER.encode(value.getResultCount(), outStream);\n BOOLEAN_CODER.encode(value.isLastEventReceived(), outStream);\n keyCoder.encode(value.getKey(), outStream);\n }\n\n @Override\n public ProcessingState<KeyT> decode(InputStream inStream) throws IOException {\n Long lastOutputSequence = NULLABLE_LONG_CODER.decode(inStream);\n Long earliestBufferedSequence = NULLABLE_LONG_CODER.decode(inStream);\n Long latestBufferedSequence = NULLABLE_LONG_CODER.decode(inStream);\n int bufferedRecordCount = INTEGER_CODER.decode(inStream);\n long recordsReceivedCount = LONG_CODER.decode(inStream);\n long duplicates = LONG_CODER.decode(inStream);\n long resultCount = LONG_CODER.decode(inStream);\n boolean isLastEventReceived = BOOLEAN_CODER.decode(inStream);\n KeyT key = keyCoder.decode(inStream);\n\n return new ProcessingState<>(key, lastOutputSequence, earliestBufferedSequence,\n latestBufferedSequence, bufferedRecordCount, recordsReceivedCount, duplicates,\n resultCount, isLastEventReceived);\n }\n\n @Override\n public List<? extends Coder<?>> getCoderArguments() {\n return List.of();\n }\n\n @Override\n public void verifyDeterministic() {\n }\n}" }, { "identifier": "Reason", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/UnprocessedEvent.java", "snippet": "public enum Reason {duplicate, buffered}" }, { "identifier": "UnprocessedEventCoder", "path": "beam-ordered-processing/src/main/java/org/apache/beam/sdk/extensions/ordered/UnprocessedEvent.java", "snippet": " static class UnprocessedEventCoder<EventT> extends Coder<UnprocessedEvent<EventT>> {\n\n private final Coder<EventT> eventCoder;\n\n UnprocessedEventCoder(Coder<EventT> eventCoder) {\n this.eventCoder = eventCoder;\n }\n\n @Override\n public void encode(UnprocessedEvent<EventT> value, OutputStream outStream) throws IOException {\n ByteCoder.of().encode((byte) value.getReason().ordinal(), outStream);\n eventCoder.encode(value.getEvent(), outStream);\n }\n\n @Override\n public UnprocessedEvent<EventT> decode(InputStream inputStream) throws IOException {\n Reason reason = Reason.values()[ByteCoder.of().decode(inputStream)];\n EventT event = eventCoder.decode(inputStream);\n return UnprocessedEvent.create(event, reason);\n }\n\n @Override\n public List<? extends Coder<?>> getCoderArguments() {\n// TODO: implement\n return null;\n }\n\n @Override\n public void verifyDeterministic() throws NonDeterministicException {\n// TODO: implement\n }\n }" } ]
import com.google.auto.value.AutoValue; import java.util.Arrays; import java.util.Iterator; import javax.annotation.Nullable; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.coders.BooleanCoder; import org.apache.beam.sdk.coders.Coder; import org.apache.beam.sdk.coders.KvCoder; import org.apache.beam.sdk.coders.VarLongCoder; import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.Builder; import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.ClearedBufferedEvents; import org.apache.beam.sdk.extensions.ordered.OrderedProcessingDiagnosticEvent.QueriedBufferedEvents; import org.apache.beam.sdk.extensions.ordered.ProcessingState.ProcessingStateCoder; import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.Reason; import org.apache.beam.sdk.extensions.ordered.UnprocessedEvent.UnprocessedEventCoder; import org.apache.beam.sdk.schemas.NoSuchSchemaException; import org.apache.beam.sdk.schemas.SchemaCoder; import org.apache.beam.sdk.schemas.SchemaRegistry; import org.apache.beam.sdk.state.OrderedListState; import org.apache.beam.sdk.state.StateSpec; import org.apache.beam.sdk.state.StateSpecs; import org.apache.beam.sdk.state.TimeDomain; import org.apache.beam.sdk.state.Timer; import org.apache.beam.sdk.state.TimerSpec; import org.apache.beam.sdk.state.TimerSpecs; import org.apache.beam.sdk.state.ValueState; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.transforms.ParDo; import org.apache.beam.sdk.transforms.windowing.BoundedWindow; import org.apache.beam.sdk.values.KV; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollection.IsBounded; import org.apache.beam.sdk.values.PCollectionTuple; import org.apache.beam.sdk.values.TimestampedValue; import org.apache.beam.sdk.values.TupleTag; import org.apache.beam.sdk.values.TupleTagList; import org.apache.beam.sdk.values.TypeDescriptor; import org.joda.time.Duration; import org.joda.time.Instant; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
4,898
* Main DoFn for processing ordered events * * @param <Event> * @param <EventKey> * @param <State> */ static class OrderedProcessorDoFn<Event, EventKey, Result, State extends MutableState<Event, Result>> extends DoFn<KV<EventKey, KV<Long, Event>>, KV<EventKey, Result>> { private static final Logger LOG = LoggerFactory.getLogger(OrderedProcessorDoFn.class); private static final String PROCESSING_STATE = "processingState"; private static final String MUTABLE_STATE = "mutableState"; private static final String BUFFERED_EVENTS = "bufferedEvents"; private static final String STATUS_EMISSION_TIMER = "statusTimer"; private static final String LARGE_BATCH_EMISSION_TIMER = "largeBatchTimer"; private static final String WINDOW_CLOSED = "windowClosed"; private final EventExaminer<Event, State> eventExaminer; @StateId(BUFFERED_EVENTS) @SuppressWarnings("unused") private final StateSpec<OrderedListState<Event>> bufferedEventsSpec; @StateId(PROCESSING_STATE) @SuppressWarnings("unused") private final StateSpec<ValueState<ProcessingState<EventKey>>> processingStateSpec; @SuppressWarnings("unused") @StateId(MUTABLE_STATE) private final StateSpec<ValueState<State>> mutableStateSpec; @StateId(WINDOW_CLOSED) @SuppressWarnings("unused") private final StateSpec<ValueState<Boolean>> windowClosedSpec; @TimerId(STATUS_EMISSION_TIMER) @SuppressWarnings("unused") private final TimerSpec statusEmissionTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME); @TimerId(LARGE_BATCH_EMISSION_TIMER) @SuppressWarnings("unused") private final TimerSpec largeBatchEmissionTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME); private final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag; private final Duration statusUpdateFrequency; private final TupleTag<KV<EventKey, Result>> mainOutputTupleTag; private final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag; private final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventsTupleTag; private final boolean produceDiagnosticEvents; private final boolean produceStatusUpdateOnEveryEvent; private final long maxNumberOfResultsToProduce; private Long numberOfResultsBeforeBundleStart; /** * Stateful DoFn to do the bulk of processing * * @param eventExaminer * @param eventCoder * @param stateCoder * @param keyCoder * @param mainOutputTupleTag * @param statusTupleTag * @param statusUpdateFrequency * @param diagnosticEventsTupleTag * @param unprocessedEventTupleTag * @param produceDiagnosticEvents * @param produceStatusUpdateOnEveryEvent * @param maxNumberOfResultsToProduce */ OrderedProcessorDoFn( EventExaminer<Event, State> eventExaminer, Coder<Event> eventCoder, Coder<State> stateCoder, Coder<EventKey> keyCoder, TupleTag<KV<EventKey, Result>> mainOutputTupleTag, TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag, Duration statusUpdateFrequency, TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag, TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventTupleTag, boolean produceDiagnosticEvents, boolean produceStatusUpdateOnEveryEvent, long maxNumberOfResultsToProduce) { this.eventExaminer = eventExaminer; this.bufferedEventsSpec = StateSpecs.orderedList(eventCoder); this.mutableStateSpec = StateSpecs.value(stateCoder); this.processingStateSpec = StateSpecs.value(ProcessingStateCoder.of(keyCoder)); this.windowClosedSpec = StateSpecs.value(BooleanCoder.of()); this.mainOutputTupleTag = mainOutputTupleTag; this.statusTupleTag = statusTupleTag; this.unprocessedEventsTupleTag = unprocessedEventTupleTag; this.statusUpdateFrequency = statusUpdateFrequency; this.diagnosticEventsTupleTag = diagnosticEventsTupleTag; this.produceDiagnosticEvents = produceDiagnosticEvents; this.produceStatusUpdateOnEveryEvent = produceStatusUpdateOnEveryEvent; this.maxNumberOfResultsToProduce = maxNumberOfResultsToProduce; } @StartBundle public void onBundleStart() { numberOfResultsBeforeBundleStart = null; } @FinishBundle public void onBundleFinish() { // This might be necessary because this field is also used in a Timer numberOfResultsBeforeBundleStart = null; } @ProcessElement public void processElement( @StateId(BUFFERED_EVENTS) OrderedListState<Event> bufferedEventsState, @AlwaysFetched @StateId(PROCESSING_STATE) ValueState<ProcessingState<EventKey>> processingStateState, @StateId(MUTABLE_STATE) ValueState<State> mutableStateState, @TimerId(STATUS_EMISSION_TIMER) Timer statusEmissionTimer, @TimerId(LARGE_BATCH_EMISSION_TIMER) Timer largeBatchEmissionTimer, @Element KV<EventKey, KV<Long, Event>> eventAndSequence, MultiOutputReceiver outputReceiver, BoundedWindow window) { // TODO: should we make diagnostics generation optional?
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.sdk.extensions.ordered; /** * Transform for processing ordered events. Events are grouped by the key and within each key they * are applied according to the provided sequence. Events which arrive out of sequence are buffered * and reprocessed when new events for a given key arrived. * * @param <Event> * @param <EventKey> * @param <State> */ @AutoValue @SuppressWarnings({"nullness", "TypeNameShadowing"}) public abstract class OrderedEventProcessor<Event, EventKey, Result, State extends MutableState<Event, Result>> extends PTransform<PCollection<KV<EventKey, KV<Long, Event>>>, OrderedEventProcessorResult<EventKey, Result, Event>> { public static final int DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS = 5; public static final boolean DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS = false; private static final boolean DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT = false; public static final int DEFAULT_MAX_ELEMENTS_TO_OUTPUT = 10_000; public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create( EventExaminer<EventType, StateType> eventExaminer, Coder<KeyType> keyCoder, Coder<StateType> stateCoder, Coder<ResultType> resultTypeCoder) { return new AutoValue_OrderedEventProcessor<>(eventExaminer, null /* no event coder */, stateCoder, keyCoder, resultTypeCoder, DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT, DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT); } /** * Default constructor method * * @param <EventType> * @param <KeyType> * @param <StateType> * @param eventCoder coder for the Event class * @param keyCoder coder for the Key class * @param stateCoder coder for the State class * @param resultCoder * @return */ public static <EventType, KeyType, ResultType, StateType extends MutableState<EventType, ResultType>> OrderedEventProcessor<EventType, KeyType, ResultType, StateType> create( EventExaminer<EventType, StateType> eventExaminer, Coder<EventType> eventCoder, Coder<KeyType> keyCoder, Coder<StateType> stateCoder, Coder<ResultType> resultCoder) { // TODO: none of the values are marked as @Nullable and the transform will fail if nulls are provided. But need a better error messaging. return new AutoValue_OrderedEventProcessor<>(eventExaminer, eventCoder, stateCoder, keyCoder, resultCoder, DEFAULT_STATUS_UPDATE_FREQUENCY_SECONDS, DEFAULT_PRODUCE_STATUS_UPDATE_ON_EVERY_EVENT, DEFAULT_PRODUCE_DIAGNOSTIC_EVENTS, DEFAULT_MAX_ELEMENTS_TO_OUTPUT); } /** * Provide a custom status update frequency * * @param seconds * @return */ public OrderedEventProcessor<Event, EventKey, Result, State> withStatusUpdateFrequencySeconds( int seconds) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), seconds, this.isProduceStatusUpdateOnEveryEvent(), this.isProduceDiagnosticEvents(), this.getMaxNumberOfResultsPerOutput()); } public OrderedEventProcessor<Event, EventKey, Result, State> produceDiagnosticEvents( boolean produceDiagnosticEvents) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(), produceDiagnosticEvents, this.getMaxNumberOfResultsPerOutput()); } /** * Notice that unless the status frequency update is set to 0 or negative number the status will * be produced on every event and with the specified frequency. */ public OrderedEventProcessor<Event, EventKey, Result, State> produceStatusUpdatesOnEveryEvent( boolean value) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), this.getStatusUpdateFrequencySeconds(), value, this.isProduceDiagnosticEvents(), this.getMaxNumberOfResultsPerOutput()); } public OrderedEventProcessor<Event, EventKey, Result, State> withMaxResultsPerOutput( long maxResultsPerOutput) { return new AutoValue_OrderedEventProcessor<>( this.getEventExaminer(), this.getEventCoder(), this.getStateCoder(), this.getKeyCoder(), this.getResultCoder(), this.getStatusUpdateFrequencySeconds(), this.isProduceStatusUpdateOnEveryEvent(), this.isProduceDiagnosticEvents(), maxResultsPerOutput); } abstract EventExaminer<Event, State> getEventExaminer(); @Nullable abstract Coder<Event> getEventCoder(); abstract Coder<State> getStateCoder(); @Nullable abstract Coder<EventKey> getKeyCoder(); abstract Coder<Result> getResultCoder(); abstract int getStatusUpdateFrequencySeconds(); abstract boolean isProduceStatusUpdateOnEveryEvent(); abstract boolean isProduceDiagnosticEvents(); abstract long getMaxNumberOfResultsPerOutput(); @Override public OrderedEventProcessorResult<EventKey, Result, Event> expand( PCollection<KV<EventKey, KV<Long, Event>>> input) { final TupleTag<KV<EventKey, Result>> mainOutput = new TupleTag<>("mainOutput") { }; final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusOutput = new TupleTag<>("status") { }; final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticOutput = new TupleTag<>( "diagnostics") { }; final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventOutput = new TupleTag<>( "unprocessed-events") { }; Coder<EventKey> keyCoder = getKeyCoder(); if (keyCoder == null) { // Assume that the default key coder is used and use the key coder from it. keyCoder = ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getKeyCoder(); } Coder<Event> eventCoder = getEventCoder(); if (eventCoder == null) { // Assume that the default key coder is used and use the event coder from it. eventCoder = ((KvCoder<Long, Event>) ((KvCoder<EventKey, KV<Long, Event>>) input.getCoder()).getValueCoder()).getValueCoder(); } PCollectionTuple processingResult = input.apply(ParDo.of( new OrderedProcessorDoFn<>(getEventExaminer(), eventCoder, getStateCoder(), keyCoder, mainOutput, statusOutput, getStatusUpdateFrequencySeconds() <= 0 ? null : Duration.standardSeconds(getStatusUpdateFrequencySeconds()), diagnosticOutput, unprocessedEventOutput, isProduceDiagnosticEvents(), isProduceStatusUpdateOnEveryEvent(), input.isBounded() == IsBounded.BOUNDED ? Integer.MAX_VALUE : getMaxNumberOfResultsPerOutput())).withOutputTags(mainOutput, TupleTagList.of(Arrays.asList(statusOutput, diagnosticOutput, unprocessedEventOutput)))); KvCoder<EventKey, Result> mainOutputCoder = KvCoder.of(keyCoder, getResultCoder()); KvCoder<EventKey, OrderedProcessingStatus> processingStatusCoder = KvCoder.of(keyCoder, getOrderedProcessingStatusCoder(input.getPipeline())); KvCoder<EventKey, OrderedProcessingDiagnosticEvent> diagnosticOutputCoder = KvCoder.of(keyCoder, getOrderedProcessingDiagnosticsCoder(input.getPipeline())); KvCoder<EventKey, KV<Long, UnprocessedEvent<Event>>> unprocessedEventsCoder = KvCoder.of( keyCoder, KvCoder.of(VarLongCoder.of(), new UnprocessedEventCoder<>(eventCoder))); return new OrderedEventProcessorResult<>( input.getPipeline(), processingResult.get(mainOutput).setCoder(mainOutputCoder), mainOutput, processingResult.get(statusOutput).setCoder(processingStatusCoder), statusOutput, processingResult.get(diagnosticOutput).setCoder(diagnosticOutputCoder), diagnosticOutput, processingResult.get(unprocessedEventOutput).setCoder(unprocessedEventsCoder), unprocessedEventOutput); } private static Coder<OrderedProcessingStatus> getOrderedProcessingStatusCoder(Pipeline pipeline) { SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry(); Coder<OrderedProcessingStatus> result; try { result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingStatus.class), TypeDescriptor.of(OrderedProcessingStatus.class), schemaRegistry.getToRowFunction(OrderedProcessingStatus.class), schemaRegistry.getFromRowFunction(OrderedProcessingStatus.class)); } catch (NoSuchSchemaException e) { throw new RuntimeException(e); } return result; } private static Coder<OrderedProcessingDiagnosticEvent> getOrderedProcessingDiagnosticsCoder( Pipeline pipeline) { SchemaRegistry schemaRegistry = pipeline.getSchemaRegistry(); Coder<OrderedProcessingDiagnosticEvent> result; try { result = SchemaCoder.of(schemaRegistry.getSchema(OrderedProcessingDiagnosticEvent.class), TypeDescriptor.of(OrderedProcessingDiagnosticEvent.class), schemaRegistry.getToRowFunction(OrderedProcessingDiagnosticEvent.class), schemaRegistry.getFromRowFunction(OrderedProcessingDiagnosticEvent.class)); } catch (NoSuchSchemaException e) { throw new RuntimeException(e); } return result; } /** * Main DoFn for processing ordered events * * @param <Event> * @param <EventKey> * @param <State> */ static class OrderedProcessorDoFn<Event, EventKey, Result, State extends MutableState<Event, Result>> extends DoFn<KV<EventKey, KV<Long, Event>>, KV<EventKey, Result>> { private static final Logger LOG = LoggerFactory.getLogger(OrderedProcessorDoFn.class); private static final String PROCESSING_STATE = "processingState"; private static final String MUTABLE_STATE = "mutableState"; private static final String BUFFERED_EVENTS = "bufferedEvents"; private static final String STATUS_EMISSION_TIMER = "statusTimer"; private static final String LARGE_BATCH_EMISSION_TIMER = "largeBatchTimer"; private static final String WINDOW_CLOSED = "windowClosed"; private final EventExaminer<Event, State> eventExaminer; @StateId(BUFFERED_EVENTS) @SuppressWarnings("unused") private final StateSpec<OrderedListState<Event>> bufferedEventsSpec; @StateId(PROCESSING_STATE) @SuppressWarnings("unused") private final StateSpec<ValueState<ProcessingState<EventKey>>> processingStateSpec; @SuppressWarnings("unused") @StateId(MUTABLE_STATE) private final StateSpec<ValueState<State>> mutableStateSpec; @StateId(WINDOW_CLOSED) @SuppressWarnings("unused") private final StateSpec<ValueState<Boolean>> windowClosedSpec; @TimerId(STATUS_EMISSION_TIMER) @SuppressWarnings("unused") private final TimerSpec statusEmissionTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME); @TimerId(LARGE_BATCH_EMISSION_TIMER) @SuppressWarnings("unused") private final TimerSpec largeBatchEmissionTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME); private final TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag; private final Duration statusUpdateFrequency; private final TupleTag<KV<EventKey, Result>> mainOutputTupleTag; private final TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag; private final TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventsTupleTag; private final boolean produceDiagnosticEvents; private final boolean produceStatusUpdateOnEveryEvent; private final long maxNumberOfResultsToProduce; private Long numberOfResultsBeforeBundleStart; /** * Stateful DoFn to do the bulk of processing * * @param eventExaminer * @param eventCoder * @param stateCoder * @param keyCoder * @param mainOutputTupleTag * @param statusTupleTag * @param statusUpdateFrequency * @param diagnosticEventsTupleTag * @param unprocessedEventTupleTag * @param produceDiagnosticEvents * @param produceStatusUpdateOnEveryEvent * @param maxNumberOfResultsToProduce */ OrderedProcessorDoFn( EventExaminer<Event, State> eventExaminer, Coder<Event> eventCoder, Coder<State> stateCoder, Coder<EventKey> keyCoder, TupleTag<KV<EventKey, Result>> mainOutputTupleTag, TupleTag<KV<EventKey, OrderedProcessingStatus>> statusTupleTag, Duration statusUpdateFrequency, TupleTag<KV<EventKey, OrderedProcessingDiagnosticEvent>> diagnosticEventsTupleTag, TupleTag<KV<EventKey, KV<Long, UnprocessedEvent<Event>>>> unprocessedEventTupleTag, boolean produceDiagnosticEvents, boolean produceStatusUpdateOnEveryEvent, long maxNumberOfResultsToProduce) { this.eventExaminer = eventExaminer; this.bufferedEventsSpec = StateSpecs.orderedList(eventCoder); this.mutableStateSpec = StateSpecs.value(stateCoder); this.processingStateSpec = StateSpecs.value(ProcessingStateCoder.of(keyCoder)); this.windowClosedSpec = StateSpecs.value(BooleanCoder.of()); this.mainOutputTupleTag = mainOutputTupleTag; this.statusTupleTag = statusTupleTag; this.unprocessedEventsTupleTag = unprocessedEventTupleTag; this.statusUpdateFrequency = statusUpdateFrequency; this.diagnosticEventsTupleTag = diagnosticEventsTupleTag; this.produceDiagnosticEvents = produceDiagnosticEvents; this.produceStatusUpdateOnEveryEvent = produceStatusUpdateOnEveryEvent; this.maxNumberOfResultsToProduce = maxNumberOfResultsToProduce; } @StartBundle public void onBundleStart() { numberOfResultsBeforeBundleStart = null; } @FinishBundle public void onBundleFinish() { // This might be necessary because this field is also used in a Timer numberOfResultsBeforeBundleStart = null; } @ProcessElement public void processElement( @StateId(BUFFERED_EVENTS) OrderedListState<Event> bufferedEventsState, @AlwaysFetched @StateId(PROCESSING_STATE) ValueState<ProcessingState<EventKey>> processingStateState, @StateId(MUTABLE_STATE) ValueState<State> mutableStateState, @TimerId(STATUS_EMISSION_TIMER) Timer statusEmissionTimer, @TimerId(LARGE_BATCH_EMISSION_TIMER) Timer largeBatchEmissionTimer, @Element KV<EventKey, KV<Long, Event>> eventAndSequence, MultiOutputReceiver outputReceiver, BoundedWindow window) { // TODO: should we make diagnostics generation optional?
OrderedProcessingDiagnosticEvent.Builder diagnostics = OrderedProcessingDiagnosticEvent.builder();
0
2023-11-15 21:26:06+00:00
8k
Hikaito/Fox-Engine
src/system/gui/project/ProjectEditor.java
[ { "identifier": "ProjectManager", "path": "src/system/project/ProjectManager.java", "snippet": "public class ProjectManager {\n\n // UUID methods\n public String getUUID(){return root.getUUID();}\n public boolean matchesUUID(String other){\n return root.getUUID().equals(other);\n }\n\n public String getTitle(){return root.getTitle();}\n\n // reject if program number is lower than project\n public static boolean evaluateProjectNumber(VersionNumber program, VersionNumber project){\n if(program.compareTo(project) < 0) return false;\n return true;\n }\n\n // project root\n protected ProjectRoot root;\n public ProjectRoot getRoot(){return root;}\n\n // tree generation\n public DefaultMutableTreeNode getTree(){\n return root.getTree();\n }\n\n // updates menu offshoot entities\n public void updateDependencies(){\n buildDictionary();\n root.generateMenu();\n }\n\n //region dictionary----------------------------\n // dictionary\n protected HashMap<Long, ProjectFile> dictionary;\n\n //build dictionary\n public void buildDictionary(){\n dictionary = new HashMap<>(); // generate new dictionary\n addDict(root); // build from root\n }\n\n // build dictionary recursive\n protected void addDict(ProjectUnitCore root){\n // case file: add to dictionary\n if (root instanceof ProjectFile){\n ProjectFile unit = (ProjectFile) root; //cast object\n dictionary.put(unit.getID(), unit);\n }\n //recurse to all children for file types\n else if (root instanceof ProjectFolderInterface){\n ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object\n for (ProjectUnitCore child: unit.getChildren()){\n addDict(child);\n }\n }\n }\n\n //query dictionary; returns null if none found\n public ProjectFile getFile(long code){\n // return null if nocode\n if(code == Program.getDefaultFileCode()) return null;\n\n return dictionary.get(code);\n }\n // endregion\n\n // save file------------------------------------\n // GSON builder\n private static final Gson gson = new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag\n .setPrettyPrinting() // creates a pretty version of the output\n .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter\n .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer\n .registerTypeAdapter(ProjectUnitCore.class, new ProjectTypeAdapter()) // registers abstract classes\n .create();\n\n // function for saving file\n public boolean saveFile(){\n // derive json\n String json = gson.toJson(root);\n\n //generate absolute path to location\n String path = Paths.get(root.getPath(), Program.getProjectFile()).toString();\n\n // write json to file\n try {\n FileWriter out = new FileWriter(path, false);\n out.write(json);\n out.close();\n // log action\n Program.log(\"File '\" + Program.getProjectFile() + \"' saved as project file at \" + path);\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n\n return true;\n }\n\n // initialization function----------------------------\n public void initializeEmpty(){\n root = new ProjectRoot(\"Null Project\"); //create project root\n\n Program.log(\"Project initialized from filesystem.\");\n }\n\n public void initializeProject(String fullpath){\n // attempt opening\n ProjectRoot tempRoot = readTree(fullpath); // read file\n\n // test version number\n if(!evaluateProjectNumber(Program.getProgramVersion(), tempRoot.getProgramVersion())){\n WarningWindow.warningWindow(\"Project version invalid. Program version: \" + Program.getProgramVersion() + \"; Project version: \" + tempRoot.getProgramVersion());\n initializeEmpty();\n return;\n }\n\n // open directory\n root = tempRoot; // if project version acceptible, save project\n root = readTree(fullpath);\n\n Program.log(\"Project at \"+ fullpath + \" imported.\");\n\n // open file editing dialogue\n // dictionary generated on window close\n try {\n ProjectEditor window = new ProjectEditor(this);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n protected ProjectRoot readTree(String fullpath){\n // open directory\n File file = new File(fullpath); // create file object to represent path\n String title = file.getName(); //set project name to folder title\n ProjectRoot tempRoot = new ProjectRoot(title); //create project root\n tempRoot.setPath(fullpath); //set directory path\n\n // recurse for each item in folder on created folder as parent\n File[] files = file.listFiles();\n assert files != null;\n for(File child: files){\n initializeTree(tempRoot.getChildren(), child, tempRoot);\n }\n // generate parents when complete\n tempRoot.generateParents();\n\n Program.log(\"Project at \"+ fullpath + \" read from filesystem.\");\n\n return tempRoot;\n }\n\n protected void initializeTree(LinkedList<ProjectUnitCore> folder, File file, ProjectRoot temproot){\n //recursive case: folder; repeat call for each file inside\n if (file.isDirectory()){\n // exclude internal folders\n if(file.getAbsolutePath().endsWith(Program.getSaveFolder())\n || file.getAbsolutePath().endsWith(Program.getRenderFolder())\n || file.getAbsolutePath().endsWith(Program.getTemplateFolder())){\n return;\n }\n\n // create a folder node and add to tree\n ProjectFolder folderObj = new ProjectFolder(file.getName(), temproot.getNextID());\n folder.addLast(folderObj);\n\n // recurse for each item in folder on created folder as parent\n File[] files = file.listFiles();\n assert files != null;\n for(File child: files){\n initializeTree(folderObj.getChildren(), child, temproot);\n }\n }\n // base case: file. add file if a valid file is found\n else{\n // if the file has a valid extension\n if (FileOperations.validExtension(file.getName(), Program.getFileExtensionLoadImage())) {\n //create a file node and add to tree\n ProjectFile newFile = new ProjectFile(FileOperations.trimDirectory(temproot.getPath(),file.getAbsolutePath()).toString(),\n FileOperations.stripExtension(file.getName(), Program.getFileExtensionLoadImage()),\n temproot.getNextID());\n newFile.setValid(true);\n folder.addLast(newFile);\n }\n }\n }\n\n // loading function: folder selection\n public void loadProject(){\n\n String text = FileOperations.selectFolder(System.getProperty(\"user.dir\")); // get project, starting at local directory\n // if a directory was selected\n if(text != null){\n // autosave file\n Program.generateManagerFile(Program.getAutosavePath(\"PROJECT_CHANGE\")); // autosave layer tree\n loadProject(text); // load project\n Program.newFileNoWarning(); // remove null file NOTE it is importannt that this occur after the project change\n Program.redrawAllRegions();\n Program.redrawMenuBar();\n Program.setProjectPath(text); // set new project path\n }\n }\n\n // loading function\n public void loadProject(String path){\n String fullpath = Paths.get(path, Program.getProjectFile()).toString(); //generate absolute path to project\n\n //load root\n try {\n String json = new String(Files.readAllBytes(Paths.get(fullpath))); // read json from file\n ProjectRoot tempRootLoad = gson.fromJson(json, ProjectRoot.class); // convert json to object of interest\n Program.log(\"Project loaded from \" + fullpath);\n\n // set root path\n tempRootLoad.setPath(path);\n\n // evaluate project number\n if(!evaluateProjectNumber(Program.getProgramVersion(), tempRootLoad.getProgramVersion())){\n WarningWindow.warningWindow(\"Project version invalid. Program version: \" + Program.getProgramVersion() + \"; Project version: \" + tempRootLoad.getProgramVersion());\n initializeEmpty();\n return;\n }\n\n root = tempRootLoad; // keep load\n\n // load project tree\n ProjectRoot tempRoot = readTree(path);\n\n // place\n SortedSet<ProjectFile> discoveredFiles = new TreeSet<>();\n SortedSet<ProjectFile> existingFiles = new TreeSet<>();\n\n //traverse trees\n fillFileList(tempRoot, discoveredFiles);\n fillFileList(root, existingFiles);\n\n //eliminate common files\n //common files list exists to prevent concurrent removal and traversal errors\n SortedSet<ProjectFile> commonFiles = new TreeSet<>();\n // find files that are common\n for(ProjectFile file:existingFiles){\n // if a file was found, remove it from both lists\n if (discoveredFiles.contains(file)){\n commonFiles.add(file); //add to common list\n }\n }\n // remove common files\n for(ProjectFile file:commonFiles){\n // if a file was found, remove it from both lists\n discoveredFiles.remove(file);\n existingFiles.remove(file);\n file.setValid(true);\n }\n\n // open reconciliation dialogue\n // if files remain in either list, open window\n if (discoveredFiles.size() != 0 || existingFiles.size() != 0){\n // dictionary generated on window close\n ProjectReconciliation window = new ProjectReconciliation(this, existingFiles, discoveredFiles);\n }\n else{\n root.generateParents(); //generate parents to menu\n updateDependencies(); // generate dictionary if all is well\n }\n\n // save new location\n Program.setProjectPath(path);\n\n }\n // return null if no object could be loaded; initialize instead\n catch (IOException e) {\n Program.log(\"Project file could not be read. Source: \" + fullpath);\n initializeProject(path);\n }\n }\n\n // tree traversal function for collecting files into a sorted list\n protected void fillFileList(ProjectUnitCore root, SortedSet<ProjectFile> files){\n // if file, add to files and return\n if(root instanceof ProjectFile){\n files.add((ProjectFile) root);\n return;\n }\n // if folder, generate children list\n LinkedList<ProjectUnitCore> children;\n if (root instanceof ProjectRoot) children = ((ProjectRoot) root).getChildren();\n else if (root instanceof ProjectFolder) children = ((ProjectFolder) root).getChildren();\n else return;\n\n // recurse on children\n for (ProjectUnitCore child:children){\n fillFileList(child, files);\n }\n }\n\n public String getAbsolutePath(ProjectFile file){\n return Paths.get(root.getPath(), file.getPath()).toString();\n }\n\n public static void mergeFile(ProjectFile keep, ProjectFile flake){\n keep.setValid(flake.isValid()); // copy validity\n keep.setPath(flake.getPath()); // copy path\n }\n\n public void addFile(ProjectFile file){\n file.setValid(true); //set valid as true\n file.setID(root.getNextID()); // assign a proper ID value\n root.getChildren().addLast(file); // add element to root list\n file.setParent(root); // register root as parent\n }\n\n public void openEditor(){\n try {\n //generates dictionary on close\n ProjectEditor window = new ProjectEditor(this);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // selector for layer\n public void openSelector(Layer layer){\n try {\n ProjectFileSelection window = new ProjectFileSelection(this, layer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // selector for folder\n public void openSelector(Folder folder){\n try {\n ProjectFileSelection window = new ProjectFileSelection(this, folder);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public JMenu getMenu(){\n return root.generateMenu();\n }\n\n}" }, { "identifier": "CoreGlobal", "path": "src/system/setting/CoreGlobal.java", "snippet": "public class CoreGlobal {\n public static final int LEFT_BASE_PAD = 40;\n public static final int LEFT_INCREMENTAL_PAD = 50;\n public static final int LEFT_PAD = LEFT_BASE_PAD + LEFT_INCREMENTAL_PAD;\n public static final int TREE_LEVEL_PAD = 30;\n public static final int MAX_HEIGHT_TREE_BAR = 50;\n public static final int MAX_WIDTH = 9000;\n\n public static final int EDITOR_WINDOW_HEIGHT = 600;\n public static final int EDITOR_WINDOW_WIDTH = 1000;\n public static final int EDITOR_WINDOW_IMAGE = 500;\n public static final int RECONCILIATION_WINDOW_HEIGHT = 600;\n public static final int RECONCILIATION_WINDOW_WIDTH = 1200;\n //public static final int RECONCILIATION_WINDOW_IMAGE = 500;\n public static final int WARNING_WINDOW_HEIGHT = 200;\n public static final int WARNING_WINDOW_WIDTH = 500;\n}" }, { "identifier": "EventE", "path": "src/system/backbone/EventE.java", "snippet": "public interface EventE {\n public abstract void enact();\n}" }, { "identifier": "ProjectRoot", "path": "src/system/project/treeElements/ProjectRoot.java", "snippet": "public class ProjectRoot extends ProjectUnitCore implements ProjectFolderInterface {\n\n // constructor\n public ProjectRoot(){\n super(\"root\"); //set type to root\n this.title = \"Project\";\n this.programVersion = Program.getProgramVersion(); // save program version\n uuid = java.util.UUID.randomUUID().toString(); // generate UUID value\n }\n\n // longer constructor\n public ProjectRoot(String title){\n super(\"root\"); //set type to root\n this.title = title; //set title\n this.programVersion = Program.getProgramVersion(); // save program version\n uuid = java.util.UUID.randomUUID().toString(); // generate UUID value\n }\n\n // unique project identifier\n @Expose\n @SerializedName(value = \"UUID\")\n protected final String uuid;\n public String getUUID(){return uuid;}\n\n // count for layer ID [saves space as it is smaller]\n @Expose\n @SerializedName(value = \"current_layer_id\")\n protected long layerIDIterate = 0;\n public long getNextID(){\n return layerIDIterate++;\n }\n public long checkID(){return layerIDIterate;}\n\n //directory of project (set at load)\n //path for file\n protected String path = \"\";\n public String getPath(){return path;}\n public void setPath(String path){this.path = path;}\n\n // program path\n @Expose\n @SerializedName(value=\"program_version\")\n protected VersionNumber programVersion;\n public VersionNumber getProgramVersion(){return programVersion;}\n\n //region children-------------------------------------\n //Contain Children\n @Expose\n @SerializedName(value = \"subitems\")\n public LinkedList<ProjectUnitCore> subitems = new LinkedList<>();\n @Override\n public LinkedList<ProjectUnitCore> getChildren(){return subitems;}\n\n // parent generation\n public void generateParents(){\n for(ProjectUnitCore unit: subitems){\n unit.parent = this;\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateParents();\n }\n }\n //endregion\n\n //region tree-------------------------\n // generate GUI tree\n public DefaultMutableTreeNode getTree(){\n // create tree root\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n\n //recurse to children\n for(ProjectUnitCore child: subitems){\n if (child instanceof ProjectCore) ((ProjectCore)child).getTree(cat);\n }\n\n return cat;\n }\n //endregion\n\n JMenu menu = null;\n\n //build menu for menubar\n public JMenu generateMenu(){\n //create menu element for self; initalize when necessary\n if(menu == null){\n menu = new JMenu(getTitle());\n }\n else{\n menu.removeAll();\n menu.setText(getTitle());\n }\n\n //recursively register children\n for (ProjectUnitCore unit : subitems){\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateMenu(menu);\n else if (unit instanceof ProjectFile) ((ProjectFile)unit).generateMenu(menu);\n }\n\n menu.revalidate();\n return menu;\n }\n}" }, { "identifier": "ProjectUnitCore", "path": "src/system/project/treeElements/ProjectUnitCore.java", "snippet": "public abstract class ProjectUnitCore {\n\n //constructor\n public ProjectUnitCore(String type){\n this.type = type;\n }\n\n //type differentiation [used for saving and loading]\n @Expose\n @SerializedName(value = \"type\")\n private final String type;\n public String getType(){return type;}\n\n //alias (user-generated name)\n @Expose\n @SerializedName(value = \"alias\")\n protected String title;\n public void setTitle(String title){this.title = title;}\n public String getTitle(){return title;}\n\n // necessary for tree\n @Override\n public String toString(){return title;}\n\n // tree operations\n protected ProjectUnitCore parent = null;\n public ProjectUnitCore getParent(){return parent;}\n public void setParent(ProjectUnitCore obj){parent = obj;}\n}" }, { "identifier": "ProjectFile", "path": "src/system/project/treeElements/ProjectFile.java", "snippet": "public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> {\n\n // constructor\n public ProjectFile(String title, long id){\n super(\"file\", id); //super\n this.title = title;\n }\n\n // longer constructor\n public ProjectFile(String path, String title, long id){\n super(\"file\", id); //super\n this.path = path;\n this.title = title;\n }\n\n //path for file\n @Expose\n @SerializedName(value = \"filepath\")\n protected String path = \"\";\n public String getPath(){return path;}\n public void setPath(String path){this.path = path;}\n public void setNewPath(String directory, String path){\n // reject if directory doesn't match\n if(!(directory.equals(path.substring(0, directory.length())))){\n WarningWindow.warningWindow(\"File rejected; must be in root folder.\");\n return;\n }\n\n this.path = FileOperations.trimDirectory(directory, path).toString(); // get relative path\n fileValid = true;\n }\n\n //file validation function\n protected boolean fileValid = false;\n public boolean isValid(){return fileValid;}\n public void setValid(boolean state){fileValid = state;}\n\n //boolean for use color\n @Expose\n @SerializedName(value = \"use_color\")\n protected boolean use_color = true;\n public void setUseColor(boolean set){use_color = set;}\n public boolean getUseColor(){return use_color;}\n\n //Color to use\n @Expose\n @SerializedName(value = \"color\")\n public Color color = Color.lightGray;\n public void setColor(Color color){this.color = color;}\n public Color getColor(){return color;}\n\n // generate GUI tree\n public void getTree(DefaultMutableTreeNode top){\n // add self to tree\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n top.add(cat);\n }\n\n // used for sorting during save and load\n @Override\n public int compareTo(ProjectFile o) {\n return path.compareTo(o.getPath());\n }\n\n //build menu for menubar\n public void generateMenu(JMenu root){\n // only add to tree if valid file\n if(fileValid){\n // add self to menu\n JMenuItem menu = new JMenuItem(this.getTitle());\n root.add(menu);\n\n // when clicked, generate new layer with file\n menu.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n BufferedImage image = Program.getImage(getID());\n //if image loaded properly, initalize a node\n if (image != null){\n Program.addLayer(id, use_color, color);\n }\n else{\n Program.log(\"File missing for element \" + title + \" at \" + path);\n }\n }\n });\n }\n }\n}" }, { "identifier": "ProjectFolder", "path": "src/system/project/treeElements/ProjectFolder.java", "snippet": "public class ProjectFolder extends ProjectCore implements ProjectFolderInterface {\n\n //constructor\n public ProjectFolder(String title, long id){\n super(\"folder\", id);\n this.title = title;\n }\n\n //region children-------------------------------------\n //Contain Children\n @Expose\n @SerializedName(value = \"subitems\")\n public LinkedList<ProjectUnitCore> subitems = new LinkedList<>();\n @Override\n public LinkedList<ProjectUnitCore> getChildren(){return subitems;}\n\n // parent generation\n public void generateParents(){\n for(ProjectUnitCore unit: subitems){\n unit.parent = this;\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateParents();\n }\n }\n //endregion\n\n //region tree-------------------------\n // generate GUI tree\n public void getTree(DefaultMutableTreeNode top){\n // add self to tree\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n top.add(cat);\n\n //recurse to children\n for(ProjectUnitCore child: subitems){\n if (child instanceof ProjectCore) ((ProjectCore)child).getTree(cat);\n }\n }\n //endregion\n\n //build menu for menubar\n public void generateMenu(JMenu root){\n // add self to menu\n JMenu menu = new JMenu(this.getTitle());\n root.add(menu);\n\n //recursively register children\n for (ProjectUnitCore unit : subitems){\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateMenu(menu);\n else if (unit instanceof ProjectFile) ((ProjectFile)unit).generateMenu(menu);\n }\n }\n\n}" } ]
import system.project.ProjectManager; import system.setting.CoreGlobal; import system.backbone.EventE; import system.project.treeElements.ProjectRoot; import system.project.treeElements.ProjectUnitCore; import system.project.treeElements.ProjectFile; import system.project.treeElements.ProjectFolder; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.io.IOException;
6,286
package system.gui.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectEditor { protected ProjectManager source; JPanel editorPane = null; // used for resetting display JPanel imageDisplay = null; // used for resetting display JSplitPane splitPane = null; DefaultMutableTreeNode treeRoot = null; JTree tree; // used for drawing background decision private boolean[] color; //constructor public ProjectEditor(ProjectManager source) throws IOException { // initialize color decision color= new boolean[1]; color[0] = true; //initialize frame this.source = source; //overall window JFrame jFrame = new JFrame("Project Editor"); //initialize window title jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size jFrame.setLocationRelativeTo(null); //center window // on close, generate dictionary jFrame.addWindowListener(new java.awt.event.WindowAdapter(){ @Override public void windowClosed(java.awt.event.WindowEvent windowEvent){ source.updateDependencies(); //rebuild dictionary } }); //label region imageDisplay = new JPanel(); imageDisplay.setLayout(new GridBagLayout()); //center items //editor region editorPane = new JPanel(); //editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS)); editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it //prepare regions regenerateEditorPane(null); // initialize to null selection // tree region treeRoot = source.getTree(); tree = generateTree(); JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane); //new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER )); secondaryPane.setResizeWeight(.7); //Main split pane; generate tree [needs to initialize under editor for null selection reasons] splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane); splitPane.setResizeWeight(.3); jFrame.add(splitPane); jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization) } // variable used for selection memory ProjectUnitCore activeSelection = new ProjectFolder("NULL", -1); // empty file that is overwritten protected JTree generateTree(){ // tree panel generation JTree tree = new JTree(treeRoot); // make tree object tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // set tree as selectable, one at a time //selection listener tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { // on selection, call selection update DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //get last selected item regenerateEditorPane(node); } }); return tree; } // class for regenerating editor pane public static class RegenerateEvent implements EventE { private final ProjectEditor editor; public RegenerateEvent(ProjectEditor editor){ this.editor = editor; } @Override public void enact() { editor.regenerateEditorPane(); } } protected void regenerateEditorPane(){ regenerateEditorPane((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); } protected void regenerateEditorPane(DefaultMutableTreeNode selection){ //if no selection, render for no selection if(selection == null){ generateNullDetails(); // if no selection, render for no selection activeSelection = null; //update selection return; } // render selection ProjectUnitCore select = (ProjectUnitCore) selection.getUserObject(); // if selection has not changed, do nothing //if (select == activeSelection) return; //removed so this can be used to intentionally refresh data //otherwise generate appropriate details if (select == null) generateNullDetails(); else if (select instanceof ProjectFile) generateFileDetails(selection); else if (select instanceof ProjectFolder) generateFolderDetails(selection);
package system.gui.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectEditor { protected ProjectManager source; JPanel editorPane = null; // used for resetting display JPanel imageDisplay = null; // used for resetting display JSplitPane splitPane = null; DefaultMutableTreeNode treeRoot = null; JTree tree; // used for drawing background decision private boolean[] color; //constructor public ProjectEditor(ProjectManager source) throws IOException { // initialize color decision color= new boolean[1]; color[0] = true; //initialize frame this.source = source; //overall window JFrame jFrame = new JFrame("Project Editor"); //initialize window title jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size jFrame.setLocationRelativeTo(null); //center window // on close, generate dictionary jFrame.addWindowListener(new java.awt.event.WindowAdapter(){ @Override public void windowClosed(java.awt.event.WindowEvent windowEvent){ source.updateDependencies(); //rebuild dictionary } }); //label region imageDisplay = new JPanel(); imageDisplay.setLayout(new GridBagLayout()); //center items //editor region editorPane = new JPanel(); //editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS)); editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it //prepare regions regenerateEditorPane(null); // initialize to null selection // tree region treeRoot = source.getTree(); tree = generateTree(); JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane); //new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER )); secondaryPane.setResizeWeight(.7); //Main split pane; generate tree [needs to initialize under editor for null selection reasons] splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane); splitPane.setResizeWeight(.3); jFrame.add(splitPane); jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization) } // variable used for selection memory ProjectUnitCore activeSelection = new ProjectFolder("NULL", -1); // empty file that is overwritten protected JTree generateTree(){ // tree panel generation JTree tree = new JTree(treeRoot); // make tree object tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // set tree as selectable, one at a time //selection listener tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { // on selection, call selection update DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //get last selected item regenerateEditorPane(node); } }); return tree; } // class for regenerating editor pane public static class RegenerateEvent implements EventE { private final ProjectEditor editor; public RegenerateEvent(ProjectEditor editor){ this.editor = editor; } @Override public void enact() { editor.regenerateEditorPane(); } } protected void regenerateEditorPane(){ regenerateEditorPane((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); } protected void regenerateEditorPane(DefaultMutableTreeNode selection){ //if no selection, render for no selection if(selection == null){ generateNullDetails(); // if no selection, render for no selection activeSelection = null; //update selection return; } // render selection ProjectUnitCore select = (ProjectUnitCore) selection.getUserObject(); // if selection has not changed, do nothing //if (select == activeSelection) return; //removed so this can be used to intentionally refresh data //otherwise generate appropriate details if (select == null) generateNullDetails(); else if (select instanceof ProjectFile) generateFileDetails(selection); else if (select instanceof ProjectFolder) generateFolderDetails(selection);
else if (select instanceof ProjectRoot) generateRootDetails(selection);
3
2023-11-12 21:12:21+00:00
8k
KomnisEvangelos/GeoApp
app/src/main/java/gr/ihu/geoapp/ui/signin/SignInViewModel.java
[ { "identifier": "Repository", "path": "app/src/main/java/gr/ihu/geoapp/managers/Repository.java", "snippet": "public class Repository {\n private static final String BASE_URL = \"http://192.168.1.6/geoapp/\";\n private static Repository instance;\n\n private Repository() {\n }\n\n public static Repository getInstance() {\n if (instance == null) {\n synchronized (Repository.class) {\n if (instance == null) {\n instance = new Repository();\n }\n }\n }\n return instance;\n }\n\n /**\n * Performs a login operation.\n * Sends a POST request to the server with the user's email and password.\n * The server's response is passed to the provided callback.\n *\n * @param email the user's email address\n * @param password the user's password\n * @param callback the callback to handle the server's response\n */\n public void login(String email, String password, final RepositoryCallback callback) {\n JSONObject requestData = new JSONObject();\n try {\n requestData.put(\"email\", email);\n requestData.put(\"password\", password);\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n performAPIRequest(\"login.php\", requestData, callback);\n }\n\n /**\n * Performs a registration operation.\n * Sends a POST request to the server with the user's details.\n * The server's response is passed to the provided callback.\n *\n * @param full_name the user's full name\n * @param email the user's email address\n * @param password the user's password\n * @param birthdate the user's birthdate\n * @param job the user's job\n * @param diploma the user's diploma\n * @param callback the callback to handle the server's response\n */\n public void register(String full_name, String email, String password, String birthdate, String job,\n String diploma, final RepositoryCallback callback) {\n JSONObject requestData = new JSONObject();\n try {\n requestData.put(\"full_name\", full_name);\n requestData.put(\"email\", email);\n requestData.put(\"password\", password);\n requestData.put(\"birthdate\", birthdate);\n requestData.put(\"job\", job);\n requestData.put(\"diploma\", diploma);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n performAPIRequest(\"register.php\", requestData, callback);\n\n }\n\n /**\n * Performs a logout operation.\n * Sends a POST request to the server with the user's email and API key.\n * The server's response is passed to the provided callback.\n *\n * @param email the user's email address\n * @param apiKey the user's API key\n * @param callback the callback to handle the server's response\n */\n public void logout(String email, String apiKey, final RepositoryCallback callback) {\n JSONObject requestData = new JSONObject();\n try {\n requestData.put(\"email\", email);\n requestData.put(\"apiKey\", apiKey);\n\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n performAPIRequest(\"api.php\", requestData, callback);\n\n }\n\n /**\n * Performs an API request to the server.\n * Sends a POST request to the specified endpoint with the provided data.\n * The server's response is passed to the provided callback.\n *\n * @param endpoint the endpoint to send the request to\n * @param requestData the data to send in the request\n * @param callback the callback to handle the server's response\n *\n */\n\n @SuppressLint(\"StaticFieldLeak\")\n public void performAPIRequest(final String endpoint, final JSONObject requestData, final RepositoryCallback callback) {\n new AsyncTask<Void, Void, String>() {\n /**\n * Background task to execute the API request.\n *\n * @param voids not used\n * @return a JSON string representing the server's response\n */\n @Override\n protected String doInBackground(Void... voids) {\n HttpURLConnection connection = null;\n StringBuilder response = new StringBuilder();\n\n try {\n URL url = new URL(BASE_URL + endpoint);\n connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"POST\");\n connection.setDoOutput(true);\n\n connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n\n String postData = encodeDataAsFormUrlEncoded(requestData);\n\n OutputStream outputStream = connection.getOutputStream();\n outputStream.write(postData.getBytes(\"UTF-8\"));\n outputStream.close();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n response.append(line);\n }\n reader.close();\n\n } catch (IOException | JSONException e) {\n e.printStackTrace();\n } finally {\n if (connection != null) {\n connection.disconnect();\n }\n }\n\n return response.toString();\n }\n /**\n * Callback method called on the main thread after the completion of the API request.\n *\n * @param response the server's response\n */\n @Override\n protected void onPostExecute(String response) {\n super.onPostExecute(response);\n Log.d(\"response\",response);\n\n try {\n JSONObject jsonResponse = new JSONObject(response);\n\n if (jsonResponse.has(\"status\")) {\n String status = jsonResponse.getString(\"status\");\n if (status.equals(\"success\")) {\n callback.onSuccess(jsonResponse);\n } else {\n callback.onError(jsonResponse.getString(\"status\") + jsonResponse.getString(\"message\"));\n }\n } else {\n callback.onError(\"Invalid response from server\");\n }\n } catch (JSONException e) {\n e.printStackTrace();\n callback.onError(\"Error parsing JSON response\");\n }\n }\n /**\n * Helper method to encode data as form-urlencoded format.\n *\n * @param data the data to be encoded\n * @return a string representing the encoded data\n * @throws UnsupportedEncodingException if the encoding is not supported\n * @throws JSONException if there is an issue with JSON processing\n */\n private String encodeDataAsFormUrlEncoded(JSONObject data) throws UnsupportedEncodingException, JSONException {\n StringBuilder result = new StringBuilder();\n boolean first = true;\n Iterator<String> keys = data.keys();\n\n while (keys.hasNext()) {\n String key = keys.next();\n String value = data.getString(key);\n\n if (first) {\n first = false;\n } else {\n result.append(\"&\");\n }\n\n result.append(URLEncoder.encode(key, \"UTF-8\"));\n result.append(\"=\");\n result.append(URLEncoder.encode(value, \"UTF-8\"));\n }\n return result.toString();\n }\n\n\n }.execute();\n }\n /**\n * An interface for handling the callbacks from the API requests.\n */\n public interface RepositoryCallback {\n /**\n * Called when the API request is successful.\n *\n * @param response the server's response\n */\n void onSuccess(JSONObject response);\n /**\n * Called when the API request encounters an error.\n *\n * @param error the error message\n */\n void onError(String error);\n }\n}" }, { "identifier": "Image", "path": "app/src/main/java/gr/ihu/geoapp/models/Image.java", "snippet": "public class Image {\n private String id;\n private String path;\n private String title;\n private String description;\n private String tags_csv;\n //private String location;\n\n /**\n * Constructs an Image object with the specified id, path, title, description, and tags.\n *\n * @param id the id of the image\n * @param path the path of the image\n * @param title the title of the image\n * @param description the description of the image\n * @param tags_csv the tags of the image in CSV format\n */\n public Image(String id, String path, String title, String description, String tags_csv) {\n this.id = id;\n this.path = path;\n this.title = title;\n this.description = description;\n this.tags_csv = tags_csv;\n }\n\n /**\n * Constructs an Image object with the specified title, description, and tags.\n * The id and path of the image are left unspecified.\n *\n * @param title the title of the image\n * @param description the description of the image\n * @param tags_csv the tags of the image in CSV format\n */\n public Image(String title, String description, String tags_csv) {\n this.id = id;\n this.path = path;\n this.title = title;\n this.description = description;\n this.tags_csv = tags_csv;\n }\n\n /**\n * Gets the id of the image.\n *\n * @return the id of the image\n */\n public String getId() {\n return id;\n }\n\n /**\n * Sets the id of the image.\n *\n * @param id the id of the image\n */\n public void setId(String id) {\n this.id = id;\n }\n /**\n * Gets the path of the image.\n *\n * @return the path of the image\n */\n public String getPath() {\n return path;\n }\n /**\n * Sets the path of the image.\n *\n * @param path the path of the image\n */\n public void setPath(String path) {\n this.path = path;\n }\n /**\n * Gets the title of the image.\n *\n * @return the title of the image\n */\n public String getTitle() {\n return title;\n }\n /**\n * Sets the title of the image.\n *\n * @param title the title of the image\n */\n public void setTitle(String title) {\n this.title = title;\n }\n /**\n * Gets the description of the image.\n *\n * @return the description of the image\n */\n public String getDescription() {\n return description;\n }\n /**\n * Sets the description of the image.\n *\n * @param description the description of the image\n */\n public void setDescription(String description) {\n this.description = description;\n }\n /**\n * Gets the tags of the image in CSV format.\n *\n * @return the tags of the image in CSV format\n */\n public String getTags_csv() {\n return tags_csv;\n }\n /**\n * Sets the tags of the image in CSV format.\n *\n * @param tags_csv the tags of the image in CSV format\n */\n public void setTags_csv(String tags_csv) {\n this.tags_csv = tags_csv;\n }\n}" }, { "identifier": "RegularUser", "path": "app/src/main/java/gr/ihu/geoapp/models/users/RegularUser.java", "snippet": "public class RegularUser{\n private String user_id;\n private String full_name;\n private String password;\n private String email;\n private String birthdate;\n private String job;\n private String diploma;\n private String api_key;\n private List<Image> imageList;\n\n private static RegularUser instance;\n\n private RegularUser() {\n this.user_id = \"N/A\";\n this.full_name = \"N/A\";\n this.email = \"N/A\";\n this.birthdate = \"N/A\";\n this.job = \"N/A\";\n this.diploma = \"N/A\";\n this.imageList = new ArrayList<>();\n }\n\n public static RegularUser getInstance() {\n if (instance == null) {\n instance = new RegularUser();\n }\n return instance;\n }\n\n /**\n * Gets the unique ID of the user.\n *\n * @return the user's ID\n */\n public String getUserId() {\n return user_id;\n }\n\n /**\n * Sets the unique ID of the user.\n *\n * @param userId the user's ID\n */\n public void setUserId(String userId) {\n this.user_id = userId;\n }\n\n /**\n * Gets the full name of the user.\n *\n * @return the user's full name\n */\n public String getFullName() {\n return full_name;\n }\n\n /**\n * Sets the full name of the user.\n *\n * @param fullName the user's full name\n */\n public void setFullName(String fullName) {\n this.full_name = fullName;\n }\n\n /**\n * Gets the email of the user.\n *\n * @return the user's email\n */\n public String getEmail() {\n return email;\n }\n\n /**\n * Sets the email of the user.\n *\n * @param email the user's email\n */\n public void setEmail(String email) {\n this.email = email;\n }\n\n /**\n * Gets the birth date of the user.\n *\n * @return the user's birth date\n */\n public String getBirthdate() {\n return birthdate;\n }\n\n /**\n * Sets the birth date of the user.\n *\n * @param birthdate the user's birth date\n */\n public void setBirthdate(String birthdate) {\n this.birthdate = birthdate;\n }\n\n /**\n * Gets the job of the user.\n *\n * @return the user's job\n */\n public String getJob() {\n return job;\n }\n\n /**\n * Sets the job of the user.\n *\n * @param job the user's job\n */\n public void setJob(String job) {\n this.job = job;\n }\n\n /**\n * Gets the diploma of the user.\n *\n * @return the user's diploma\n */\n public String getDiploma() {\n return diploma;\n }\n\n /**\n * Sets the diploma of the user.\n *\n * @param diploma the user's diploma\n */\n public void setDiploma(String diploma) {\n this.diploma = diploma;\n }\n\n /**\n * Sets the singleton instance of the RegularUser class.\n *\n * @param instance the instance to set\n */\n public static void setInstance(RegularUser instance) {\n RegularUser.instance = instance;\n }\n\n /**\n * Gets the password of the user.\n *\n * @return the user's password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Sets the password of the user.\n *\n * @param password the user's password\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n /**\n * Gets the API key of the user.\n *\n * @return the user's API key\n */\n public String getApi_key() {\n return api_key;\n }\n\n /**\n * Sets the API key of the user.\n *\n * @param api_key the user's API key\n */\n public void setApi_key(String api_key) {\n this.api_key = api_key;\n }\n\n /**\n * Gets the unique ID of the user.\n *\n * @return the user's ID\n */\n public String getUser_id() {\n return user_id;\n }\n\n /**\n * Sets the unique ID of the user.\n *\n * @param user_id the user's ID\n */\n public void setUser_id(String user_id) {\n this.user_id = user_id;\n }\n\n /**\n * Gets the full name of the user.\n *\n * @return the user's full name\n */\n public String getFull_name() {\n return full_name;\n }\n /**\n * Sets the full name of the user.\n *\n * @param full_name the user's full name\n */\n public void setFull_name(String full_name) {\n this.full_name = full_name;\n }\n\n /**\n * Gets the list of images associated with the user.\n *\n * @return the list of images\n */\n public List<Image> getImageList() {\n return imageList;\n }\n\n /**\n * Sets the list of images associated with the user.\n *\n * @param imageList the list of images\n */\n public void setImageList(List<Image> imageList) {\n this.imageList = imageList;\n }\n}" }, { "identifier": "User", "path": "app/src/main/java/gr/ihu/geoapp/models/users/User.java", "snippet": "public interface User {\n\n /**\n * Performs a login operation.\n *\n * @return a task representing the authentication result\n */\n public com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> login();\n /**\n * Performs a registration operation.\n *\n * @return a task representing the authentication result\n */\n public com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> register();\n /**\n * Performs a logout operation.\n */\n public void logout();\n /**\n * Fetches user data.\n */\n public void fetchData();\n\n}" } ]
import android.util.Log; import android.widget.EditText; import android.widget.Toast; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.jar.JarException; import gr.ihu.geoapp.managers.Repository; import gr.ihu.geoapp.models.Image; import gr.ihu.geoapp.models.users.RegularUser; import gr.ihu.geoapp.models.users.User;
4,905
package gr.ihu.geoapp.ui.signin; /** * ViewModel class for the SignInFragment. * This class handles user sign-in operations, communicates with the repository, and manages the UI-related data for the SignInFragment. */ public class SignInViewModel extends ViewModel { /** * MutableLiveData to notify observers about the success or failure of the sign-in operation. */ private MutableLiveData<Boolean> signinSuccess = new MutableLiveData<>(); /** * Instance of the repository for handling user-related operations. */ private Repository repository; /** * The RegularUser instance representing the signed-in user. */ private RegularUser user = RegularUser.getInstance(); /** * Constructor for the SignInViewModel. * Initializes the repository instance. */ public SignInViewModel(){ repository = Repository.getInstance(); } /** * Retrieves the LiveData object containing the sign-in result. * * */ public LiveData<Boolean> getSigninResult(){ return signinSuccess; } /** * Initiates the sign-in process with the provided email and password. * * @param signinEmail the user's email for sign-in * @param signinPassword the user's password for sign-in */ public void signIn(String signinEmail, String signinPassword) { repository.login(signinEmail, signinPassword, new Repository.RepositoryCallback() { @Override public void onSuccess(JSONObject response) { //Log.d("response",response.toString()); if (response != null) { try { JSONObject jsonResponse = new JSONObject(String.valueOf(response)); if (jsonResponse.has("status")) { String status = jsonResponse.getString("status"); if (status.equals("success")) { JSONObject userData = (JSONObject) jsonResponse.get("user_data"); Integer idInt = (Integer) userData.get("id"); String idString = String.valueOf(idInt); String fullName = (String) userData.get("full_name"); String email = (String) userData.get("email"); // String password = (String) userData.get("password"); String birthdate = (String) userData.get("birthdate"); String job = (String) userData.get("job"); String diploma = (String) userData.get("diploma"); String apiKey = (String) userData.get("api_key"); user.setUserId(idString); user.setFullName(fullName); user.setEmail(email); user.setBirthdate(birthdate); user.setJob(job); user.setDiploma(diploma); user.setApi_key(apiKey); //try{ // String website = jsonResponse.getString("website"); // user.setWebsite(website); // }catch (Exception e){ // user.setWebsite(null); // } // String photo = jsonResponse.isNull("photo") ? null : jsonResponse.getString("photo"); // user.setPhoto(photo); // JSONArray iamgesArray = userData.getJSONArray("photos");
package gr.ihu.geoapp.ui.signin; /** * ViewModel class for the SignInFragment. * This class handles user sign-in operations, communicates with the repository, and manages the UI-related data for the SignInFragment. */ public class SignInViewModel extends ViewModel { /** * MutableLiveData to notify observers about the success or failure of the sign-in operation. */ private MutableLiveData<Boolean> signinSuccess = new MutableLiveData<>(); /** * Instance of the repository for handling user-related operations. */ private Repository repository; /** * The RegularUser instance representing the signed-in user. */ private RegularUser user = RegularUser.getInstance(); /** * Constructor for the SignInViewModel. * Initializes the repository instance. */ public SignInViewModel(){ repository = Repository.getInstance(); } /** * Retrieves the LiveData object containing the sign-in result. * * */ public LiveData<Boolean> getSigninResult(){ return signinSuccess; } /** * Initiates the sign-in process with the provided email and password. * * @param signinEmail the user's email for sign-in * @param signinPassword the user's password for sign-in */ public void signIn(String signinEmail, String signinPassword) { repository.login(signinEmail, signinPassword, new Repository.RepositoryCallback() { @Override public void onSuccess(JSONObject response) { //Log.d("response",response.toString()); if (response != null) { try { JSONObject jsonResponse = new JSONObject(String.valueOf(response)); if (jsonResponse.has("status")) { String status = jsonResponse.getString("status"); if (status.equals("success")) { JSONObject userData = (JSONObject) jsonResponse.get("user_data"); Integer idInt = (Integer) userData.get("id"); String idString = String.valueOf(idInt); String fullName = (String) userData.get("full_name"); String email = (String) userData.get("email"); // String password = (String) userData.get("password"); String birthdate = (String) userData.get("birthdate"); String job = (String) userData.get("job"); String diploma = (String) userData.get("diploma"); String apiKey = (String) userData.get("api_key"); user.setUserId(idString); user.setFullName(fullName); user.setEmail(email); user.setBirthdate(birthdate); user.setJob(job); user.setDiploma(diploma); user.setApi_key(apiKey); //try{ // String website = jsonResponse.getString("website"); // user.setWebsite(website); // }catch (Exception e){ // user.setWebsite(null); // } // String photo = jsonResponse.isNull("photo") ? null : jsonResponse.getString("photo"); // user.setPhoto(photo); // JSONArray iamgesArray = userData.getJSONArray("photos");
List<Image> imageList = new ArrayList<>();
1
2023-11-10 17:43:18+00:00
8k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/manager/init/start/PacketManager.java
[ { "identifier": "PacketWorldReaderEight", "path": "src/main/java/ac/grim/grimac/events/packets/worldreader/PacketWorldReaderEight.java", "snippet": "public class PacketWorldReaderEight extends BasePacketWorldReader {\n // Synchronous\n private void readChunk(ShortBuffer buf, BaseChunk[] chunks, BitSet set) {\n // We only need block data!\n for (int ind = 0; ind < 16; ind++) {\n if (set.get(ind)) {\n TwelveChunk compressed = new TwelveChunk(buf);\n chunks[ind] = compressed;\n }\n }\n }\n\n @Override\n public void handleMapChunkBulk(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacket packet = new WrappedPacket(event.getNMSPacket());\n int[] chunkXArray = packet.readIntArray(0);\n int[] chunkZArray = packet.readIntArray(1);\n Object[] chunkData = (Object[]) packet.readAnyObject(2);\n\n for (int i = 0; i < chunkXArray.length; i++) {\n BaseChunk[] chunks = new BaseChunk[16];\n int chunkX = chunkXArray[i];\n int chunkZ = chunkZArray[i];\n\n WrappedPacket nmsChunkMapWrapper = new WrappedPacket(new NMSPacket(chunkData[i]));\n ShortBuffer buf = ByteBuffer.wrap(nmsChunkMapWrapper.readByteArray(0)).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();\n\n readChunk(buf, chunks, BitSet.valueOf(new long[]{nmsChunkMapWrapper.readInt(0)}));\n\n Column column = new Column(chunkX, chunkZ, chunks, player.lastTransactionSent.get() + 1);\n player.compensatedWorld.addToCache(column, chunkX, chunkZ);\n }\n }\n\n @Override\n public void handleMapChunk(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacketOutMapChunk packet = new WrappedPacketOutMapChunk(event.getNMSPacket());\n\n try {\n int chunkX = packet.getChunkX();\n int chunkZ = packet.getChunkZ();\n\n // Map chunk packet with 0 sections and continuous chunk is the unload packet in 1.7 and 1.8\n // Optional is only empty on 1.17 and above\n Object chunkMap = packet.readAnyObject(2);\n if (chunkMap.getClass().getDeclaredField(\"b\").getInt(chunkMap) == 0 && packet.isGroundUpContinuous().get()) {\n unloadChunk(player, chunkX, chunkZ);\n return;\n }\n\n ShortBuffer buf = ByteBuffer.wrap(packet.getCompressedData()).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();\n BaseChunk[] chunks = new BaseChunk[16];\n BitSet set = packet.getBitSet().get();\n\n readChunk(buf, chunks, set);\n\n addChunkToCache(player, chunks, packet.isGroundUpContinuous().get(), chunkX, chunkZ);\n } catch (NoSuchFieldException | IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void handleMultiBlockChange(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacket packet = new WrappedPacket(event.getNMSPacket());\n\n try {\n // Section Position or Chunk Section - depending on version\n Object position = packet.readAnyObject(0);\n\n Object[] blockInformation;\n blockInformation = (Object[]) packet.readAnyObject(1);\n\n // This shouldn't be possible\n if (blockInformation.length == 0) return;\n\n Field getX = position.getClass().getDeclaredField(\"x\");\n Field getZ = position.getClass().getDeclaredField(\"z\");\n\n int chunkX = getX.getInt(position) << 4;\n int chunkZ = getZ.getInt(position) << 4;\n\n Field shortField = Reflection.getField(blockInformation[0].getClass(), 0);\n Field blockDataField = Reflection.getField(blockInformation[0].getClass(), 1);\n\n int range = (player.getTransactionPing() / 100) + 32;\n if (Math.abs(chunkX - player.x) < range && Math.abs(chunkZ - player.z) < range)\n event.setPostTask(player::sendTransaction);\n\n\n for (Object o : blockInformation) {\n short pos = shortField.getShort(o);\n int blockID = getByCombinedID(blockDataField.get(o));\n\n int blockX = pos >> 12 & 15;\n int blockY = pos & 255;\n int blockZ = pos >> 8 & 15;\n\n player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.compensatedWorld.updateBlock(chunkX + blockX, blockY, chunkZ + blockZ, blockID));\n }\n\n } catch (IllegalAccessException | NoSuchFieldException exception) {\n exception.printStackTrace();\n }\n }\n}" }, { "identifier": "PacketWorldReaderNine", "path": "src/main/java/ac/grim/grimac/events/packets/worldreader/PacketWorldReaderNine.java", "snippet": "public class PacketWorldReaderNine extends BasePacketWorldReader {\n boolean isThirteenOrOlder, isFlattened;\n\n public PacketWorldReaderNine() {\n isThirteenOrOlder = ServerVersion.getVersion().isOlderThan(ServerVersion.v_1_14);\n isFlattened = ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_13);\n }\n\n @Override\n public void handleMapChunk(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacketOutMapChunk packet = new WrappedPacketOutMapChunk(event.getNMSPacket());\n\n try {\n int chunkX = packet.getChunkX();\n int chunkZ = packet.getChunkZ();\n\n byte[] chunkData = packet.getCompressedData();\n BitSet bitSet = packet.getBitSet().get();\n NetInput dataIn = new StreamNetInput(new ByteArrayInputStream(chunkData));\n\n BaseChunk[] chunks = new BaseChunk[16];\n for (int index = 0; index < chunks.length; ++index) {\n if (bitSet.get(index)) {\n chunks[index] = isFlattened ? FifteenChunk.read(dataIn) : new TwelveChunk(dataIn);\n\n // Advance the data past the blocklight and skylight bytes\n if (isThirteenOrOlder) dataIn.readBytes(4096);\n }\n }\n\n addChunkToCache(player, chunks, packet.isGroundUpContinuous().get(), chunkX, chunkZ);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}" }, { "identifier": "PacketWorldReaderSeven", "path": "src/main/java/ac/grim/grimac/events/packets/worldreader/PacketWorldReaderSeven.java", "snippet": "public class PacketWorldReaderSeven extends BasePacketWorldReader {\n public static Method ancientGetById;\n\n public PacketWorldReaderSeven() {\n ancientGetById = Reflection.getMethod(NMSUtils.blockClass, \"getId\", int.class);\n }\n\n @Override\n public void handleMapChunk(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacketOutMapChunk packet = new WrappedPacketOutMapChunk(event.getNMSPacket());\n\n int chunkX = packet.getChunkX();\n int chunkZ = packet.getChunkZ();\n\n // Map chunk packet with 0 sections and continuous chunk is the unload packet in 1.7 and 1.8\n // Optional is only empty on 1.17 and above\n if (packet.readInt(5) == 0 && packet.isGroundUpContinuous().get()) {\n player.compensatedWorld.removeChunkLater(chunkX, chunkZ);\n return;\n }\n\n byte[] data = packet.getCompressedData();\n SevenChunk[] chunks = new SevenChunk[16];\n\n ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);\n readChunk(buf, chunks, packet.getBitSet().get());\n\n addChunkToCache(player, chunks, packet.isGroundUpContinuous().get(), chunkX, chunkZ);\n }\n\n @Override\n public void handleMapChunkBulk(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacket packet = new WrappedPacket(event.getNMSPacket());\n int[] chunkXArray = packet.readIntArray(0);\n int[] chunkZArray = packet.readIntArray(1);\n int[] bitset = packet.readIntArray(2);\n\n byte[][] byteArrayArray = packet.readObject(0, byte[][].class);\n\n for (int i = 0; i < chunkXArray.length; i++) {\n SevenChunk[] chunks = new SevenChunk[16];\n int chunkX = chunkXArray[i];\n int chunkZ = chunkZArray[i];\n\n ByteBuffer buf = ByteBuffer.wrap(byteArrayArray[i]).order(ByteOrder.LITTLE_ENDIAN);\n readChunk(buf, chunks, BitSet.valueOf(new long[]{bitset[i]}));\n\n Column column = new Column(chunkX, chunkZ, chunks, player.lastTransactionSent.get() + 1);\n player.compensatedWorld.addToCache(column, chunkX, chunkZ);\n }\n }\n\n public void readChunk(ByteBuffer buf, SevenChunk[] chunks, BitSet primarySet) {\n // 0 = Calculate expected length and determine if the packet has skylight.\n // 1 = Create chunks from mask and get blocks.\n // 2 = Get metadata.\n // 3 = Get block light.\n // 4 = Get sky light.\n // 5 = Get extended block data - This doesn't exist!\n //\n // Fun fact, a mojang dev (forgot who) wanted to do the flattening in 1.8\n // So the extended block data was likely how mojang wanted to get around the 255 block id limit\n // Before they decided to quite using magic values and instead went with the new 1.13 solution\n //\n // That's probably why extended block data exists, although yeah it was never used.\n //\n // (We only need blocks and metadata)\n for (int pass = 1; pass < 3; pass++) {\n for (int ind = 0; ind < 16; ind++) {\n if (primarySet.get(ind)) {\n if (pass == 1) {\n chunks[ind] = new SevenChunk();\n ByteArray3d blocks = chunks[ind].getBlocks();\n buf.get(blocks.getData(), 0, blocks.getData().length);\n }\n\n if (pass == 2) {\n NibbleArray3d metadata = chunks[ind].getMetadata();\n buf.get(metadata.getData(), 0, metadata.getData().length);\n }\n }\n }\n }\n }\n\n @Override\n public void handleBlockChange(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacketOutBlockChange wrappedBlockChange = new WrappedPacketOutBlockChange(event.getNMSPacket());\n\n try {\n // 1.7 includes the block data right in the packet\n Field id = Reflection.getField(event.getNMSPacket().getRawNMSPacket().getClass(), \"data\");\n int blockData = id.getInt(event.getNMSPacket().getRawNMSPacket());\n\n Field block = Reflection.getField(event.getNMSPacket().getRawNMSPacket().getClass(), \"block\");\n Object blockNMS = block.get(event.getNMSPacket().getRawNMSPacket());\n\n int materialID = (int) ancientGetById.invoke(null, blockNMS);\n int combinedID = materialID + (blockData << 12);\n\n handleUpdateBlockChange(player, event, wrappedBlockChange, combinedID);\n\n } catch (IllegalAccessException | InvocationTargetException exception) {\n exception.printStackTrace();\n }\n }\n\n @Override\n public void handleMultiBlockChange(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacket packet = new WrappedPacket(event.getNMSPacket());\n\n try {\n // 1.7 multi block change format:\n // https://wiki.vg/index.php?title=Protocol&oldid=6003#Chunk_Data\n // Object 1 - ChunkCoordIntPair\n // Object 5 - Blocks array using integers\n // 00 00 00 0F - block metadata\n // 00 00 FF F0 - block ID\n // 00 FF 00 00 - Y coordinate\n // 0F 00 00 00 - Z coordinate relative to chunk\n // F0 00 00 00 - X coordinate relative to chunk\n Object coordinates = packet.readAnyObject(1);\n int chunkX = coordinates.getClass().getDeclaredField(\"x\").getInt(coordinates) << 4;\n int chunkZ = coordinates.getClass().getDeclaredField(\"z\").getInt(coordinates) << 4;\n\n byte[] blockData = (byte[]) packet.readAnyObject(2);\n\n ByteBuffer buffer = ByteBuffer.wrap(blockData);\n\n int range = (player.getTransactionPing() / 100) + 32;\n if (Math.abs(chunkX - player.x) < range && Math.abs(chunkZ - player.z) < range)\n event.setPostTask(player::sendTransaction);\n\n while (buffer.hasRemaining()) {\n short positionData = buffer.getShort();\n short block = buffer.getShort();\n\n int relativeX = positionData >> 12 & 15;\n int relativeZ = positionData >> 8 & 15;\n int relativeY = positionData & 255;\n\n int blockID = block >> 4 & 255;\n int blockMagicValue = block & 15;\n\n player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.compensatedWorld.updateBlock(chunkX + relativeX, relativeY, chunkZ + relativeZ, blockID | blockMagicValue << 12));\n }\n } catch (IllegalAccessException | NoSuchFieldException exception) {\n exception.printStackTrace();\n }\n }\n}" }, { "identifier": "PacketWorldReaderSixteen", "path": "src/main/java/ac/grim/grimac/events/packets/worldreader/PacketWorldReaderSixteen.java", "snippet": "public class PacketWorldReaderSixteen extends PacketWorldReaderNine {\n\n @Override\n public void handleMapChunk(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacketOutMapChunk packet = new WrappedPacketOutMapChunk(event.getNMSPacket());\n\n try {\n int chunkX = packet.getChunkX();\n int chunkZ = packet.getChunkZ();\n\n BaseChunk[] chunks;\n\n byte[] chunkData = packet.getCompressedData();\n NetInput dataIn = new StreamNetInput(new ByteArrayInputStream(chunkData));\n\n if (XMaterial.getVersion() < 18) {\n BitSet bitSet = packet.getBitSet().get();\n\n chunks = new SixteenChunk[bitSet.size()];\n\n for (int index = 0; index < chunks.length; ++index) {\n if (bitSet.get(index)) {\n chunks[index] = SixteenChunk.read(dataIn);\n }\n }\n } else {\n // TODO: Get the world height correctly\n BaseChunk[] temp = new SixteenChunk[1000];\n int total = 0;\n\n while (dataIn.available() > 0) {\n temp[total++] = SixteenChunk.read(dataIn);\n }\n\n Bukkit.broadcastMessage(total + \"\");\n chunks = temp;\n }\n\n boolean isGroundUp = packet.isGroundUpContinuous().orElse(true);\n addChunkToCache(player, chunks, isGroundUp, chunkX, chunkZ);\n\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n @Override\n public void handleMultiBlockChange(GrimPlayer player, PacketPlaySendEvent event) {\n WrappedPacket packet = new WrappedPacket(event.getNMSPacket());\n\n try {\n // Section Position or Chunk Section - depending on version\n int positionPos = ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_17) ? 1 : 0;\n Object position = packet.readAnyObject(positionPos);\n\n // In 1.16, chunk sections are used. The have X, Y, and Z values\n int chunkX = (int) NMSUtils.getBlockPosX.invoke(position) << 4;\n int chunkY = (int) NMSUtils.getBlockPosY.invoke(position) << 4;\n int chunkZ = (int) NMSUtils.getBlockPosZ.invoke(position) << 4;\n\n short[] blockPositions = packet.readShortArray(0);\n\n int blockDataPos = ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_17) ? 3 : 2;\n Object[] blockDataArray = (Object[]) packet.readAnyObject(blockDataPos);\n\n int range = (player.getTransactionPing() / 100) + 32;\n if (Math.abs(chunkX - player.x) < range && Math.abs(chunkY - player.y) < range && Math.abs(chunkZ - player.z) < range)\n event.setPostTask(player::sendTransaction);\n\n for (int i = 0; i < blockPositions.length; i++) {\n short blockPosition = blockPositions[i];\n\n int blockX = sixteenSectionRelativeX(blockPosition);\n int blockY = sixteenSectionRelativeY(blockPosition);\n int blockZ = sixteenSectionRelativeZ(blockPosition);\n\n int blockID = getByCombinedID(blockDataArray[i]);\n\n player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.compensatedWorld.updateBlock(chunkX + blockX, chunkY + blockY, chunkZ + blockZ, blockID));\n }\n\n } catch (IllegalAccessException | InvocationTargetException exception) {\n exception.printStackTrace();\n }\n }\n\n public static int sixteenSectionRelativeX(short data) {\n return data >>> 8 & 15;\n }\n\n public static int sixteenSectionRelativeY(short data) {\n return data & 15;\n }\n\n public static int sixteenSectionRelativeZ(short data) {\n return data >>> 4 & 15;\n }\n}" }, { "identifier": "Initable", "path": "src/main/java/ac/grim/grimac/manager/init/Initable.java", "snippet": "public interface Initable {\n void start();\n}" }, { "identifier": "LogUtil", "path": "src/main/java/ac/grim/grimac/utils/anticheat/LogUtil.java", "snippet": "@UtilityClass\npublic class LogUtil {\n public void info(final String info) {\n GrimAPI.INSTANCE.getPlugin().getLogger().info(info);\n }\n\n public void warn(final String warn) {\n GrimAPI.INSTANCE.getPlugin().getLogger().info(warn);\n }\n\n public void error(final String error) {\n GrimAPI.INSTANCE.getPlugin().getLogger().info(error);\n }\n}" } ]
import ac.grim.grimac.events.packets.*; import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderEight; import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderNine; import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderSeven; import ac.grim.grimac.events.packets.worldreader.PacketWorldReaderSixteen; import ac.grim.grimac.manager.init.Initable; import ac.grim.grimac.utils.anticheat.LogUtil; import io.github.retrooper.packetevents.PacketEvents; import io.github.retrooper.packetevents.utils.server.ServerVersion;
4,740
package ac.grim.grimac.manager.init.start; public class PacketManager implements Initable { @Override public void start() { LogUtil.info("Registering packets..."); PacketEvents.get().registerListener(new PacketPlayerAbilities()); PacketEvents.get().registerListener(new PacketPingListener()); PacketEvents.get().registerListener(new PacketPlayerDigging()); PacketEvents.get().registerListener(new PacketPlayerAttack()); PacketEvents.get().registerListener(new PacketEntityAction()); PacketEvents.get().registerListener(new PacketBlockAction()); PacketEvents.get().registerListener(new PacketFireworkListener()); PacketEvents.get().registerListener(new PacketSelfMetadataListener()); PacketEvents.get().registerListener(new PacketServerTeleport()); PacketEvents.get().registerListener(new PacketPlayerCooldown()); PacketEvents.get().registerListener(new PacketPlayerRespawn()); PacketEvents.get().registerListener(new CheckManagerListener()); PacketEvents.get().registerListener(new PacketPlayerSteer()); if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_16)) {
package ac.grim.grimac.manager.init.start; public class PacketManager implements Initable { @Override public void start() { LogUtil.info("Registering packets..."); PacketEvents.get().registerListener(new PacketPlayerAbilities()); PacketEvents.get().registerListener(new PacketPingListener()); PacketEvents.get().registerListener(new PacketPlayerDigging()); PacketEvents.get().registerListener(new PacketPlayerAttack()); PacketEvents.get().registerListener(new PacketEntityAction()); PacketEvents.get().registerListener(new PacketBlockAction()); PacketEvents.get().registerListener(new PacketFireworkListener()); PacketEvents.get().registerListener(new PacketSelfMetadataListener()); PacketEvents.get().registerListener(new PacketServerTeleport()); PacketEvents.get().registerListener(new PacketPlayerCooldown()); PacketEvents.get().registerListener(new PacketPlayerRespawn()); PacketEvents.get().registerListener(new CheckManagerListener()); PacketEvents.get().registerListener(new PacketPlayerSteer()); if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_16)) {
PacketEvents.get().registerListener(new PacketWorldReaderSixteen());
3
2023-11-11 05:14:12+00:00
8k
kawainime/IOT-Smart_Farming
IOT_Farm_V.2/src/UI/task.java
[ { "identifier": "Bugs_Log", "path": "IOT_Farm_V.2/src/Core/Background/Bugs_Log.java", "snippet": "public class Bugs_Log \n{\n public static void exceptions(String message)\n {\n String file_name = get_localDate.LocalDate()+\"Bugs.dat\";\n \n try\n {\n FileOutputStream details = new FileOutputStream(file_name,true);\n\n PrintWriter file = new PrintWriter(details);\n\n BufferedWriter store = new BufferedWriter(file);\n \n store.write(get_localDate.LocalDate()+\"[ \"+message+\" ]\\n\");\n \n store.newLine();\n\n store.close();\n\n file.close();\n }\n catch(IOException Error)\n {\n Bugs_Log.exceptions(String.valueOf(Error));\n }\n }\n}" }, { "identifier": "ID_Genarator", "path": "IOT_Farm_V.2/src/Core/Background/ID_Genarator.java", "snippet": "public class ID_Genarator \n{\n public static int id()\n {\n Random rand = new Random();\n \n int random_id = rand.nextInt(99999);\n\n return random_id;\n }\n \n}" }, { "identifier": "Upcomming_Events", "path": "IOT_Farm_V.2/src/Core/Background/Upcomming_Events.java", "snippet": "public class Upcomming_Events \n{\n \n public static void noticeboard_update()\n {\n //noticeBoard1\n \n Connection connection = Connector.connection();\n \n String SQL = \"SELECT * FROM to_do\";\n \n int counter = 0;\n \n int events = 0;\n \n try\n {\n Statement stmt = connection.createStatement();\n \n ResultSet rs = stmt.executeQuery(SQL);\n \n while(rs.next())\n {\n int days = time_management.time_management(rs.getString(\"TASK_DATE\"));\n \n if(days < 7)\n {\n UI.task.noticeBoard.addDate(rs.getString(\"TASK_DATE\"));\n \n UI.task.noticeBoard.addNoticeBoard(new ModelNoticeBoard(new Color(50, 93, 215), rs.getString(\"LOCATION_data\"), String.valueOf(days)+\" Available\", rs.getString(\"Activity\")+\"\\n\"));\n \n UI.task.noticeBoard.scrollToTop();\n \n events ++;\n }\n\n \n counter++;\n }\n }\n catch(SQLException ERROR)\n {\n Core.Background.Bugs_Log.exceptions(String.valueOf(ERROR));\n }\n \n // UI.task.jLabel4.setText(\"TODO LIST : total tasks(\"+String.valueOf(counter)+\")\");\n \n UI.task.jLabel14.setText(\"UPCOMMING EVENTS (\"+events+\")\");\n \n UI.task.jLabel18.setText(\"0\"+String.valueOf(counter));\n \n UI.task.jLabel19.setText(\"0\"+String.valueOf(events));\n }\n}" }, { "identifier": "Connector", "path": "IOT_Farm_V.2/src/Core/MySql/Connector.java", "snippet": "public class Connector\n{\n public static Connection connection()\n {\n Connection conn = null;\n \n String host = Load_Settings.load_data(\"HOST\");\n \n String port = Load_Settings.load_data(\"PORT\");\n \n String user_name = Load_Settings.load_data(\"UNAME\");\n \n String password = Load_Settings.load_data(\"PASSWORD\");\n \n String db_name = Load_Settings.load_data(\"DBNAME\");\n\n String database_url = \"jdbc:mysql://\"+host+\":\"+port+\"/\"+db_name+\"?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC\";\n\n try\n {\n conn = DriverManager.getConnection(database_url, user_name, password);\n \n }\n catch (Exception ERROR)\n {\n System.out.println(\"Error Message : \"+ERROR);\n }\n return conn;\n }\n \n}" }, { "identifier": "ModelStaff", "path": "IOT_Farm_V.2/src/com/deshan/model/ModelStaff.java", "snippet": "public class ModelStaff {\n\n public Icon getIcon() {\n return icon;\n }\n\n public void setIcon(Icon icon) {\n this.icon = icon;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getGender() {\n return gender;\n }\n\n public void setGender(String gender) {\n this.gender = gender;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public ModelStaff(Icon icon, String name, String gender, String email, String status) {\n this.icon = icon;\n this.name = name;\n this.gender = gender;\n this.email = email;\n this.status = status;\n }\n\n public ModelStaff() {\n }\n\n private Icon icon;\n private String name;\n private String gender;\n private String email;\n private String status;\n\n public Object[] toDataTable() {\n return new Object[]{icon, name, gender, email, status};\n }\n}" } ]
import Core.Background.Bugs_Log; import Core.Background.ID_Genarator; import Core.Background.Upcomming_Events; import Core.MySql.Connector; import com.deshan.model.ModelStaff; import java.awt.Color; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.ImageIcon; import javax.swing.plaf.basic.BasicInternalFrameUI; import javax.swing.table.DefaultTableModel;
4,113
}, new String [] { "ICO", "ACTIVITY INFO", "SCHEDULED DATE", "ACTIVITY ID", "ACTIVITY STATUS" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); table2.setFont(new java.awt.Font("Yu Gothic UI", 0, 14)); // NOI18N table2.setGridColor(new java.awt.Color(255, 255, 255)); table2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { table2MouseClicked(evt); } }); jScrollPane2.setViewportView(table2); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1247, Short.MAX_VALUE) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel8) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)) ); materialTabbed1.addTab("ALL EVENTS", jPanel2); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 1252, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 28, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 688, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 52, Short.MAX_VALUE)) ); getContentPane().add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 740)); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained if(jTextField1.getText().equals("Add Location")) { jTextField1.setText(""); jTextField1.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField1FocusGained private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost if(jTextField1.getText().equals("")) { jTextField1.setText("Add Location"); jTextField1.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField1FocusLost private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked add_task(); }//GEN-LAST:event_jLabel4MouseClicked private void table2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table2MouseClicked int row = table2.getSelectedRow(); String ID = table2.getValueAt(row,3).toString(); View view = new View(); view.load(ID); view.setVisible(true); }//GEN-LAST:event_table2MouseClicked public void table_clean() { DefaultTableModel model = (DefaultTableModel) table2.getModel(); int rowCount = model.getRowCount(); for (int i = rowCount - 1; i >= 0; i--) { model.removeRow(i); } } public void add_task() {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UI; /** * * @author Jayashanka Deshan */ public class task extends javax.swing.JInternalFrame { Integer value; public task() { initComponents(); this.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); BasicInternalFrameUI bis = (BasicInternalFrameUI) this.getUI(); bis.setNorthPane(null); jLabel2.setText("Activity ID : "+String.valueOf(ID_Genarator.id())); initData(); Upcomming_Events.noticeboard_update(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel7 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); materialTabbed1 = new tabbed.MaterialTabbed(); jPanel3 = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); roundPanel7 = new com.deshan.swing.RoundPanel(); noticeBoard = new com.deshan.swing.noticeboard.NoticeBoard(); jLabel14 = new javax.swing.JLabel(); roundPanel10 = new com.deshan.swing.RoundPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); roundPanel11 = new com.deshan.swing.RoundPanel(); jLabel9 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel21 = new javax.swing.JLabel(); roundPanel12 = new com.deshan.swing.RoundPanel(); jLabel16 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jLabel20 = new javax.swing.JLabel(); jLabel22 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); roundPanel2 = new com.deshan.swing.RoundPanel(); jLabel3 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); roundPanel3 = new com.deshan.swing.RoundPanel(); jTextField1 = new javax.swing.JTextField(); roundPanel4 = new com.deshan.swing.RoundPanel(); date = new com.toedter.calendar.JDateChooser(); roundPanel5 = new com.deshan.swing.RoundPanel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel15 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel8 = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); table2 = new com.deshans.swing.Table(); jLabel7.setText("jLabel7"); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel6.setBackground(new java.awt.Color(242, 242, 242)); materialTabbed1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM); materialTabbed1.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N jPanel3.setBackground(new java.awt.Color(242, 242, 242)); jPanel3.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel6.setForeground(new java.awt.Color(102, 102, 102)); jLabel6.setText("ICEBURG KEEP EVENTS "); roundPanel7.setBackground(new java.awt.Color(255, 255, 255)); noticeBoard.setBackground(new java.awt.Color(204, 204, 204)); jLabel14.setFont(new java.awt.Font("Yu Gothic UI Semibold", 1, 16)); // NOI18N jLabel14.setForeground(new java.awt.Color(102, 102, 102)); jLabel14.setText("UPCOMMING EVENTS"); javax.swing.GroupLayout roundPanel7Layout = new javax.swing.GroupLayout(roundPanel7); roundPanel7.setLayout(roundPanel7Layout); roundPanel7Layout.setHorizontalGroup( roundPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel7Layout.createSequentialGroup() .addContainerGap() .addGroup(roundPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(noticeBoard, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); roundPanel7Layout.setVerticalGroup( roundPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel7Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(noticeBoard, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE) .addContainerGap()) ); roundPanel10.setBackground(new java.awt.Color(255, 255, 255)); jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-17.jpg"))); // NOI18N jLabel11.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N jLabel11.setForeground(new java.awt.Color(102, 102, 102)); jLabel11.setText("ICEBURG"); jLabel12.setFont(new java.awt.Font("Yu Gothic UI Semibold", 1, 30)); // NOI18N jLabel12.setForeground(new java.awt.Color(102, 102, 102)); jLabel12.setText("KEEP EVENTS"); javax.swing.GroupLayout roundPanel10Layout = new javax.swing.GroupLayout(roundPanel10); roundPanel10.setLayout(roundPanel10Layout); roundPanel10Layout.setHorizontalGroup( roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel10Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE) .addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)) .addContainerGap()) ); roundPanel10Layout.setVerticalGroup( roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel10Layout.createSequentialGroup() .addContainerGap() .addGroup(roundPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel10Layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)) .addContainerGap()) ); roundPanel11.setBackground(new java.awt.Color(255, 255, 255)); jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-15.jpg"))); // NOI18N jLabel17.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N jLabel17.setForeground(new java.awt.Color(102, 102, 102)); jLabel17.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel17.setText("TOTAL"); jLabel18.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 80)); // NOI18N jLabel18.setForeground(new java.awt.Color(102, 102, 102)); jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel18.setText("29"); jLabel21.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N jLabel21.setForeground(new java.awt.Color(102, 102, 102)); jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel21.setText("EVENTS"); javax.swing.GroupLayout roundPanel11Layout = new javax.swing.GroupLayout(roundPanel11); roundPanel11.setLayout(roundPanel11Layout); roundPanel11Layout.setHorizontalGroup( roundPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel11Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(roundPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel21, javax.swing.GroupLayout.DEFAULT_SIZE, 166, Short.MAX_VALUE))) ); roundPanel11Layout.setVerticalGroup( roundPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel11Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)) .addGroup(roundPanel11Layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel21, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(roundPanel11Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); roundPanel12.setBackground(new java.awt.Color(255, 255, 255)); jLabel16.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-13.jpg"))); // NOI18N jLabel19.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 80)); // NOI18N jLabel19.setForeground(new java.awt.Color(102, 102, 102)); jLabel19.setText("06 "); jLabel20.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 36)); // NOI18N jLabel20.setForeground(new java.awt.Color(102, 102, 102)); jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel20.setText("EVENTS"); jLabel22.setFont(new java.awt.Font("Yu Gothic UI Semibold", 0, 18)); // NOI18N jLabel22.setForeground(new java.awt.Color(102, 102, 102)); jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel22.setText("UPCOMMING"); javax.swing.GroupLayout roundPanel12Layout = new javax.swing.GroupLayout(roundPanel12); roundPanel12.setLayout(roundPanel12Layout); roundPanel12Layout.setHorizontalGroup( roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel12Layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel22, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(268, 268, 268)) ); roundPanel12Layout.setVerticalGroup( roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel12Layout.createSequentialGroup() .addGap(51, 51, 51) .addComponent(jLabel20, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel22, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(roundPanel12Layout.createSequentialGroup() .addContainerGap() .addGroup(roundPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE) .addComponent(jLabel19, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(roundPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(roundPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(roundPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(roundPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, 403, Short.MAX_VALUE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel6) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel6) .addGap(14, 14, 14) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(roundPanel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(roundPanel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(roundPanel10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(roundPanel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); materialTabbed1.addTab("EVENT HOME", jPanel3); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(102, 102, 102)); jLabel1.setText("ADD EVENTS"); jPanel5.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 24, 199, -1)); roundPanel2.setBackground(new java.awt.Color(242, 242, 242)); jLabel3.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N jLabel3.setForeground(new java.awt.Color(102, 102, 102)); jLabel3.setText("Discription : "); jScrollPane1.setBackground(new java.awt.Color(255, 255, 255)); jScrollPane1.setBorder(null); jScrollPane1.setForeground(new java.awt.Color(255, 255, 255)); jTextArea1.setBackground(new java.awt.Color(242, 242, 242)); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Yu Gothic UI", 0, 15)); // NOI18N jTextArea1.setForeground(new java.awt.Color(102, 102, 102)); jTextArea1.setRows(5); jTextArea1.setBorder(null); jScrollPane1.setViewportView(jTextArea1); javax.swing.GroupLayout roundPanel2Layout = new javax.swing.GroupLayout(roundPanel2); roundPanel2.setLayout(roundPanel2Layout); roundPanel2Layout.setHorizontalGroup( roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel2Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 704, Short.MAX_VALUE)) .addContainerGap()) ); roundPanel2Layout.setVerticalGroup( roundPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(19, Short.MAX_VALUE)) ); jPanel5.add(roundPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 245, -1, -1)); roundPanel3.setBackground(new java.awt.Color(242, 242, 242)); jTextField1.setBackground(new java.awt.Color(242, 242, 242)); jTextField1.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N jTextField1.setForeground(new java.awt.Color(102, 102, 102)); jTextField1.setText("Add Location"); jTextField1.setBorder(null); jTextField1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField1FocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextField1FocusLost(evt); } }); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); javax.swing.GroupLayout roundPanel3Layout = new javax.swing.GroupLayout(roundPanel3); roundPanel3.setLayout(roundPanel3Layout); roundPanel3Layout.setHorizontalGroup( roundPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 694, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(20, Short.MAX_VALUE)) ); roundPanel3Layout.setVerticalGroup( roundPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE) .addContainerGap()) ); jPanel5.add(roundPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 164, -1, -1)); roundPanel4.setBackground(new java.awt.Color(242, 242, 242)); date.setBackground(new java.awt.Color(242, 242, 242)); date.setForeground(new java.awt.Color(204, 204, 204)); date.setFocusable(false); date.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N javax.swing.GroupLayout roundPanel4Layout = new javax.swing.GroupLayout(roundPanel4); roundPanel4.setLayout(roundPanel4Layout); roundPanel4Layout.setHorizontalGroup( roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(date, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE) .addContainerGap()) ); roundPanel4Layout.setVerticalGroup( roundPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel4Layout.createSequentialGroup() .addGap(14, 14, 14) .addComponent(date, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); jPanel5.add(roundPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(401, 83, -1, -1)); roundPanel5.setBackground(new java.awt.Color(242, 242, 242)); jLabel2.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N jLabel2.setForeground(new java.awt.Color(102, 102, 102)); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); jLabel2.setText("Activity ID : 165383"); jLabel2.setToolTipText(""); javax.swing.GroupLayout roundPanel5Layout = new javax.swing.GroupLayout(roundPanel5); roundPanel5.setLayout(roundPanel5Layout); roundPanel5Layout.setHorizontalGroup( roundPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 330, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(22, Short.MAX_VALUE)) ); roundPanel5Layout.setVerticalGroup( roundPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel5.add(roundPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 83, -1, 63)); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel4.setForeground(new java.awt.Color(102, 102, 102)); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icons/registration_30px.png"))); // NOI18N jLabel4.setText("ADD CURRENT EVENT"); jLabel4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel4MouseClicked(evt); } }); jPanel5.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 560, 190, 30)); jPanel5.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 554, 350, 40)); jSeparator1.setForeground(new java.awt.Color(255, 255, 255)); jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL); jPanel5.add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 10, -1, 630)); jLabel15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/history/2002.i039.018_remote_management_distant_work_isometric_icons-01.jpg"))); // NOI18N jPanel5.add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(770, 80, 470, 500)); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, 1247, Short.MAX_VALUE) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); materialTabbed1.addTab("ADD EVENT", jPanel4); jPanel2.setBackground(new java.awt.Color(242, 242, 242)); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel8.setForeground(new java.awt.Color(102, 102, 102)); jLabel8.setText("EVENTS MANEGAR"); table2.setForeground(new java.awt.Color(255, 255, 255)); table2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ICO", "ACTIVITY INFO", "SCHEDULED DATE", "ACTIVITY ID", "ACTIVITY STATUS" } ) { boolean[] canEdit = new boolean [] { false, false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); table2.setFont(new java.awt.Font("Yu Gothic UI", 0, 14)); // NOI18N table2.setGridColor(new java.awt.Color(255, 255, 255)); table2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { table2MouseClicked(evt); } }); jScrollPane2.setViewportView(table2); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 1247, Short.MAX_VALUE) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel8) .addGap(18, 18, 18) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)) ); materialTabbed1.addTab("ALL EVENTS", jPanel2); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 1252, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 28, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(materialTabbed1, javax.swing.GroupLayout.PREFERRED_SIZE, 688, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 52, Short.MAX_VALUE)) ); getContentPane().add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1280, 740)); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained if(jTextField1.getText().equals("Add Location")) { jTextField1.setText(""); jTextField1.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField1FocusGained private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusLost if(jTextField1.getText().equals("")) { jTextField1.setText("Add Location"); jTextField1.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField1FocusLost private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked add_task(); }//GEN-LAST:event_jLabel4MouseClicked private void table2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table2MouseClicked int row = table2.getSelectedRow(); String ID = table2.getValueAt(row,3).toString(); View view = new View(); view.load(ID); view.setVisible(true); }//GEN-LAST:event_table2MouseClicked public void table_clean() { DefaultTableModel model = (DefaultTableModel) table2.getModel(); int rowCount = model.getRowCount(); for (int i = rowCount - 1; i >= 0; i--) { model.removeRow(i); } } public void add_task() {
Connection conn = Connector.connection();
3
2023-11-11 08:23:10+00:00
8k
Outer-Fields/item-server
src/main/java/io/mindspice/itemserver/monitor/BlockchainMonitor.java
[ { "identifier": "PackType", "path": "src/main/java/io/mindspice/itemserver/schema/PackType.java", "snippet": "public enum PackType {\n BOOSTER(12),\n STARTER(39);\n\n public int cardAmount;\n\n PackType(int cardAmount) {\n this.cardAmount = cardAmount;\n }\n\n}" }, { "identifier": "Settings", "path": "src/main/java/io/mindspice/itemserver/Settings.java", "snippet": "public class Settings {\n static Settings INSTANCE;\n\n /* Monitor */\n public volatile int startHeight;\n public volatile int chainScanInterval;\n public volatile int heightBuffer;\n public volatile boolean isPaused;\n\n /* Database Config */\n public String okraDBUri;\n public String okraDBUser;\n public String okraDBPass;\n public String chiaDBUri;\n public String chiaDBUser;\n public String chiaDBPass;\n\n /* Internal Services */\n public String authServiceUri;\n public int authServicePort;\n public String authServiceUser;\n public String authServicePass;\n\n /* Card Rarity */\n public int holoPct = 3;\n public int goldPct = 20;\n public int highLvl = 40;\n public String currCollection;\n\n /* Config Paths */\n public String mainNodeConfig;\n public String mintWalletConfig;\n public String transactionWalletConfig;\n public String mintJobConfig;\n public String okraJobConfig;\n public String outrJobConfig;\n\n /* S3 */\n public String s3AccessKey;\n public String s3SecretKey;\n\n\n /* Assets */\n public String boosterAddress;\n public String boosterTail;\n public String starterAddress;\n public String starterTail;\n\n\n /* DID Mint */\n public String didMintToAddr;\n public List<String> didUris;\n public List<String> didMetaUris;\n public List<String> didLicenseUris;\n public String didHash;\n public String didMetaHash;\n public String didLicenseHash;\n\n /* Dispersal Limits */\n public int nftFlagAmount;\n public int okraFlagAmount;\n public int outrFlagAmount;\n\n\n\n static {\n ObjectMapper mapper = new ObjectMapper(new YAMLFactory());\n mapper.findAndRegisterModules();\n\n File file = new File(\"config.yaml\");\n\n try {\n INSTANCE = mapper.readValue(file, Settings.class);\n } catch (IOException e) {\n try {\n writeBlank();\n } catch (IOException ex) { throw new RuntimeException(ex); }\n throw new RuntimeException(\"Failed to read config file.\", e);\n }\n }\n\n public static Settings get() {\n return INSTANCE;\n }\n\n public static MetaData getAccountMintMetaData() {\n return null;\n }\n\n public static void writeBlank() throws IOException {\n var mapper = new ObjectMapper(new YAMLFactory());\n mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);\n File yamlFile = new File(\"defaults.yaml\");\n mapper.writeValue(yamlFile, new Settings());\n }\n\n\n}" }, { "identifier": "CustomLogger", "path": "src/main/java/io/mindspice/itemserver/util/CustomLogger.java", "snippet": "public class CustomLogger implements TLogger {\n private static final Logger MINT_LOG = LoggerFactory.getLogger(\"MINT\");\n private static final Logger FAILED_LOG = LoggerFactory.getLogger(\"FAILED\");\n private static final Logger APP_LOG = LoggerFactory.getLogger(\"APP\");\n\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg);\n case INFO -> APP_LOG.info(msg);\n case WARNING -> APP_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> APP_LOG.debug(msg);\n }\n }\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg, e);\n case INFO -> APP_LOG.info(msg, e);\n case WARNING -> APP_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> APP_LOG.debug(msg, e);\n }\n }\n\n\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg);\n case INFO -> MINT_LOG.info(msg);\n case WARNING -> MINT_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> MINT_LOG.debug(msg);\n }\n }\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg, e);\n case INFO -> MINT_LOG.info(msg, e);\n case WARNING -> MINT_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> MINT_LOG.debug(msg, e);\n }\n }\n}" }, { "identifier": "PackMint", "path": "src/main/java/io/mindspice/itemserver/services/PackMint.java", "snippet": "public class PackMint implements Runnable {\n private final List<PackPurchase> packPurchases;\n private final MintService mintService;\n private final List<Card> cardList;\n private final OkraNFTAPI nftAPI;\n private final Random rand;\n private final CustomLogger logger;\n private final ExecutorService virtualExec;\n private double[] lvlList = new double[]{2.0, 2.1, 2.2, 2.3, 2.4};\n IntPredicate chance = threshold -> ThreadLocalRandom.current().nextInt(100) < threshold;\n\n public PackMint(List<Card> cardList, List<PackPurchase> packPurchases, MintService mintService, OkraNFTAPI nftAPI\n , CustomLogger logger, ExecutorService virtExec) {\n this.packPurchases = packPurchases;\n this.mintService = mintService;\n this.nftAPI = nftAPI;\n this.cardList = cardList;\n this.logger = logger;\n this.virtualExec = virtExec;\n rand = new Random();\n }\n\n private double getRandomLvl() {\n return lvlList[ThreadLocalRandom.current().nextInt(lvlList.length)];\n }\n\n @Override\n public void run() {\n List<MintItem> mintItems = new ArrayList<>(packPurchases.stream().mapToInt(p -> p.packType().cardAmount).sum());\n\n for (var pack : packPurchases) {\n try {\n List<Card> cards = new ArrayList<>();\n switch (pack.packType()) {\n case BOOSTER -> {\n if (chance.test(25)) {\n cards.addAll(CardSelect.getCards(cardList, 1, CardDomain.PAWN, null));\n }\n if (chance.test(50)) {\n cards.addAll(CardSelect.getCards(cardList, 1, CardDomain.TALISMAN, null));\n }\n cards.addAll(\n CardSelect.getCards(cardList, chance.test(50) ? 2 : 1, CardDomain.WEAPON, null)\n );\n cards.addAll(CardSelect.getCards(cardList, chance.test(50) ? 2 : 1, CardDomain.POWER, null));\n cards.addAll(\n CardSelect.getCards(cardList, cards.size() == 3 ? (chance.test(50) ? 4 : 3) : 3, CardDomain.ABILITY, null)\n );\n cards.addAll(\n CardSelect.getCards(cardList, 12 - cards.size(), CardDomain.ACTION, null)\n );\n }\n\n case STARTER -> { ;\n List<Card> pawnCards = CardSelect.getCards(cardList, 3, CardDomain.PAWN, null);\n\n for (Card pawn : pawnCards) {\n cards.addAll(CardSelect.getCards(cardList, 2, CardDomain.WEAPON, pawn.type()));\n cards.addAll(CardSelect.getCards(cardList, 1, CardDomain.TALISMAN, null));\n cards.addAll(CardSelect.getCardsWithLimit(cardList, 3, CardDomain.POWER, null, getRandomLvl()));\n cards.addAll(CardSelect.getCardsWithLimit(cardList, 6, CardDomain.ACTION, pawn.type(), getRandomLvl()));\n cards.addAll(CardSelect.getCardsWithLimit(cardList, 6, CardDomain.ABILITY, null, getRandomLvl()));\n }\n cards.addAll(pawnCards);\n }\n }\n CountDownLatch latch = new CountDownLatch(cards.size());\n List<MintItem> packMints = Collections.synchronizedList(new ArrayList<>(cards.size()));\n var failed = new AtomicBoolean(false);\n for (Card card : cards) {\n virtualExec.submit(() -> {\n try {\n var edt = nftAPI.getAndIncEdt(Settings.get().currCollection, card.uid()).data().orElseThrow();\n var updatedMeta = card.metaData().cloneSetEdt(edt);\n MintItem item = new MintItem(pack.address(), updatedMeta, pack.uuid());\n packMints.add(item);\n } catch (Exception e) {\n logger.logApp(this.getClass(), TLogLevel.ERROR, \"Virtual thread from card calculation for card: \" + card.uid(), e);\n failed.set(true);\n } finally {\n latch.countDown();\n }\n });\n }\n latch.await();\n mintItems.addAll(packMints);\n if (failed.get()) {\n logger.logApp(this.getClass(), TLogLevel.FAILED, \"Error encountered while generating card pack: \" + pack +\n \" | Pack not minted: virtual thread threw exception\");\n }\n } catch (Exception e) {\n logger.logApp(this.getClass(), TLogLevel.FAILED, \"Error encountered while generating card pack: \" + pack\n + \" | Pack not minted: pack calculations threw exception\", e);\n }\n }\n mintService.submit(mintItems);\n }\n\n}" }, { "identifier": "Utils", "path": "src/main/java/io/mindspice/itemserver/util/Utils.java", "snippet": "public class Utils {\n\n public static NftInfo nftGetInfoWrapper(WalletAPI walletAPI, String coinId) throws RPCException, InterruptedException {\n int i = 100;\n Thread.sleep(10);\n ApiResponse<NftInfo> info = walletAPI.nftGetInfo(coinId);\n while(!info.success() && i > 0) {\n Thread.sleep(50);\n info = walletAPI.nftGetInfo(coinId);\n i--;\n }\n if (info.success()) {\n return info.data().get();\n } else {\n throw new IllegalStateException(\"Failed to get nft info after 20 tries\");\n }\n }\n\n public static String uidFromUrl(String url) {\n String[] parts = url.split(\"/\");\n String lastPart = parts[parts.length - 1];\n return lastPart.replace(\".png\", \"\");\n }\n\n}" } ]
import io.mindspice.databaseservice.client.api.OkraChiaAPI; import io.mindspice.databaseservice.client.api.OkraNFTAPI; import io.mindspice.databaseservice.client.schema.AccountDid; import io.mindspice.databaseservice.client.schema.Card; import io.mindspice.databaseservice.client.schema.CardAndAccountCheck; import io.mindspice.databaseservice.client.schema.NftUpdate; import io.mindspice.itemserver.schema.PackPurchase; import io.mindspice.itemserver.schema.PackType; import io.mindspice.itemserver.Settings; import io.mindspice.itemserver.util.CustomLogger; import io.mindspice.itemserver.services.PackMint; import io.mindspice.itemserver.util.Utils; import io.mindspice.jxch.rpc.http.FullNodeAPI; import io.mindspice.jxch.rpc.http.WalletAPI; import io.mindspice.jxch.rpc.schemas.ApiResponse; import io.mindspice.jxch.rpc.schemas.custom.CatSenderInfo; import io.mindspice.jxch.rpc.schemas.fullnode.AdditionsAndRemovals; import io.mindspice.jxch.rpc.schemas.object.CoinRecord; import io.mindspice.jxch.rpc.schemas.wallet.nft.NftInfo; import io.mindspice.jxch.rpc.util.ChiaUtils; import io.mindspice.jxch.rpc.util.RPCException; import io.mindspice.jxch.transact.service.mint.MintService; import io.mindspice.jxch.transact.logging.TLogLevel; import io.mindspice.mindlib.data.tuples.Pair; import java.util.*; import java.util.concurrent.*; import java.util.function.Supplier; import java.util.stream.Stream;
4,570
public void run() { if (Settings.get().isPaused) { return; } if (semaphore.availablePermits() == 0) { return; } try { semaphore.acquire(); if (!((nodeAPI.getHeight().data().orElseThrow() - Settings.get().heightBuffer) >= nextHeight)) { return; } long start = System.currentTimeMillis(); AdditionsAndRemovals coinRecords = chiaAPI.getCoinRecordsByHeight(nextHeight) .data().orElseThrow(chiaExcept); List<CoinRecord> additions = coinRecords.additions().stream().filter(a -> !a.coinbase()).toList(); List<CoinRecord> removals = coinRecords.removals().stream().filter(a -> !a.coinbase()).toList(); if (additions.isEmpty()) { logger.logApp(this.getClass(), TLogLevel.INFO, "Finished scan of block height: " + nextHeight + " | Additions: 0" + " | Block scan took: " + (System.currentTimeMillis() - start) + " ms"); nextHeight++; // Non-atomic inc doesn't matter, non-critical, is volatile to observe when monitoring return; } // NOTE offer transactions need to be discovered via finding the parent in the removals // since they do some intermediate operations CompletableFuture<CardAndAccountCheck> cardAndAccountCheck = CompletableFuture.supplyAsync(() -> { var cardOrAccountUpdates = nftAPI.checkIfCardOrAccountExists( Stream.concat(additions.stream(), removals.stream()) .map(a -> a.coin().parentCoinInfo()) .distinct().toList() ); if (cardOrAccountUpdates.data().isPresent()) { return cardOrAccountUpdates.data().get(); } return null; }, virtualExec); CompletableFuture<List<PackPurchase>> packCheck = CompletableFuture.supplyAsync(() -> { List<PackPurchase> packPurchases = null; var packRecords = additions.stream().filter(a -> assetMap.containsKey(a.coin().puzzleHash())).toList(); if (!packRecords.isEmpty()) { packPurchases = new ArrayList<>(packRecords.size()); for (var record : packRecords) { int amount = (int) (record.coin().amount() / 1000); try { ApiResponse<CatSenderInfo> catInfoResp = nodeAPI.getCatSenderInfo(record); if (!catInfoResp.success()) { logger.logApp(this.getClass(), TLogLevel.ERROR, " Failed asset lookup, wrong asset?" + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Amount(mojos / 1000): " + amount + " | Error: " + catInfoResp.error()); continue; } CatSenderInfo catInfo = catInfoResp.data().orElseThrow(chiaExcept); if (!catInfo.assetId().equals(assetMap.get(record.coin().puzzleHash()).first())) { logger.logApp(this.getClass(), TLogLevel.INFO, "Wrong Asset Received: " + catInfo.assetId() + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Expected: " + assetMap.get(record.coin().puzzleHash()).first() + " | Amount: " + record.coin().amount()); continue; } PackType packType = assetMap.get(record.coin().puzzleHash()).second(); for (int i = 0; i < amount; ++i) { String uuid = UUID.randomUUID().toString(); logger.logApp(this.getClass(), TLogLevel.INFO, "Submitted pack purchase " + " | UUID: " + uuid + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Amount(mojos / 1000): " + amount + " | Asset: " + catInfo.assetId() + " | Sender Address" + catInfo.senderPuzzleHash() ); packPurchases.add(new PackPurchase( catInfo.senderPuzzleHash(), packType, uuid, nextHeight, ChiaUtils.getCoinId(record.coin())) ); } } catch (RPCException e) { logger.logApp(this.getClass(), TLogLevel.FAILED, "Failed asset lookups at height: " + nextHeight + " | Reason: " + e.getMessage() + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Amount(mojos / 1000): " + amount); } } return packPurchases; } return null; }, virtualExec); CardAndAccountCheck cardAndAccountResults = cardAndAccountCheck.get(); List<PackPurchase> packPurchasesResults = packCheck.get(); boolean foundChange = false; if (cardAndAccountResults != null) { if (!cardAndAccountResults.existingCards().isEmpty() || !cardAndAccountResults.existingAccounts().isEmpty()) { virtualExec.submit(new UpdateDbInfo( cardAndAccountResults.existingCards(), cardAndAccountResults.existingAccounts()) ); foundChange = true; } } if (packPurchasesResults != null && !packPurchasesResults.isEmpty()) { packPurchasesResults.forEach( p -> virtualExec.submit(() -> nftAPI.addPackPurchases( p.uuid(), p.address(), p.packType().name(), p.height(), p.coinId()) ) ); logger.logApp(this.getClass(), TLogLevel.DEBUG, "Submitting purchases");
package io.mindspice.itemserver.monitor; public class BlockchainMonitor implements Runnable { private volatile int nextHeight; private final FullNodeAPI nodeAPI; private final WalletAPI walletAPI; private final OkraChiaAPI chiaAPI; private final OkraNFTAPI nftAPI; private final MintService mintService; private final Map<String, Pair<String, PackType>> assetMap; private final List<Card> cardList; private final CustomLogger logger; private final Semaphore semaphore = new Semaphore(1); protected final Supplier<RPCException> chiaExcept = () -> new RPCException("Required Chia RPC call returned Optional.empty"); private final ExecutorService virtualExec = Executors.newVirtualThreadPerTaskExecutor(); public BlockchainMonitor( FullNodeAPI nodeAPI, WalletAPI walletAPI, OkraChiaAPI chiaAPI, OkraNFTAPI nftAPI, MintService mintService, Map<String, Pair<String, PackType>> assetMap, List<Card> cardList, int startHeight, CustomLogger logger) { nextHeight = startHeight; this.nodeAPI = nodeAPI; this.walletAPI = walletAPI; this.chiaAPI = chiaAPI; this.nftAPI = nftAPI; this.mintService = mintService; this.assetMap = assetMap; this.cardList = cardList; this.logger = logger; logger.logApp(this.getClass(), TLogLevel.INFO, "Started Blockchain Monitor"); } public int getNextHeight() { return nextHeight; } @Override public void run() { if (Settings.get().isPaused) { return; } if (semaphore.availablePermits() == 0) { return; } try { semaphore.acquire(); if (!((nodeAPI.getHeight().data().orElseThrow() - Settings.get().heightBuffer) >= nextHeight)) { return; } long start = System.currentTimeMillis(); AdditionsAndRemovals coinRecords = chiaAPI.getCoinRecordsByHeight(nextHeight) .data().orElseThrow(chiaExcept); List<CoinRecord> additions = coinRecords.additions().stream().filter(a -> !a.coinbase()).toList(); List<CoinRecord> removals = coinRecords.removals().stream().filter(a -> !a.coinbase()).toList(); if (additions.isEmpty()) { logger.logApp(this.getClass(), TLogLevel.INFO, "Finished scan of block height: " + nextHeight + " | Additions: 0" + " | Block scan took: " + (System.currentTimeMillis() - start) + " ms"); nextHeight++; // Non-atomic inc doesn't matter, non-critical, is volatile to observe when monitoring return; } // NOTE offer transactions need to be discovered via finding the parent in the removals // since they do some intermediate operations CompletableFuture<CardAndAccountCheck> cardAndAccountCheck = CompletableFuture.supplyAsync(() -> { var cardOrAccountUpdates = nftAPI.checkIfCardOrAccountExists( Stream.concat(additions.stream(), removals.stream()) .map(a -> a.coin().parentCoinInfo()) .distinct().toList() ); if (cardOrAccountUpdates.data().isPresent()) { return cardOrAccountUpdates.data().get(); } return null; }, virtualExec); CompletableFuture<List<PackPurchase>> packCheck = CompletableFuture.supplyAsync(() -> { List<PackPurchase> packPurchases = null; var packRecords = additions.stream().filter(a -> assetMap.containsKey(a.coin().puzzleHash())).toList(); if (!packRecords.isEmpty()) { packPurchases = new ArrayList<>(packRecords.size()); for (var record : packRecords) { int amount = (int) (record.coin().amount() / 1000); try { ApiResponse<CatSenderInfo> catInfoResp = nodeAPI.getCatSenderInfo(record); if (!catInfoResp.success()) { logger.logApp(this.getClass(), TLogLevel.ERROR, " Failed asset lookup, wrong asset?" + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Amount(mojos / 1000): " + amount + " | Error: " + catInfoResp.error()); continue; } CatSenderInfo catInfo = catInfoResp.data().orElseThrow(chiaExcept); if (!catInfo.assetId().equals(assetMap.get(record.coin().puzzleHash()).first())) { logger.logApp(this.getClass(), TLogLevel.INFO, "Wrong Asset Received: " + catInfo.assetId() + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Expected: " + assetMap.get(record.coin().puzzleHash()).first() + " | Amount: " + record.coin().amount()); continue; } PackType packType = assetMap.get(record.coin().puzzleHash()).second(); for (int i = 0; i < amount; ++i) { String uuid = UUID.randomUUID().toString(); logger.logApp(this.getClass(), TLogLevel.INFO, "Submitted pack purchase " + " | UUID: " + uuid + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Amount(mojos / 1000): " + amount + " | Asset: " + catInfo.assetId() + " | Sender Address" + catInfo.senderPuzzleHash() ); packPurchases.add(new PackPurchase( catInfo.senderPuzzleHash(), packType, uuid, nextHeight, ChiaUtils.getCoinId(record.coin())) ); } } catch (RPCException e) { logger.logApp(this.getClass(), TLogLevel.FAILED, "Failed asset lookups at height: " + nextHeight + " | Reason: " + e.getMessage() + " | Coin: " + ChiaUtils.getCoinId(record.coin()) + " | Amount(mojos / 1000): " + amount); } } return packPurchases; } return null; }, virtualExec); CardAndAccountCheck cardAndAccountResults = cardAndAccountCheck.get(); List<PackPurchase> packPurchasesResults = packCheck.get(); boolean foundChange = false; if (cardAndAccountResults != null) { if (!cardAndAccountResults.existingCards().isEmpty() || !cardAndAccountResults.existingAccounts().isEmpty()) { virtualExec.submit(new UpdateDbInfo( cardAndAccountResults.existingCards(), cardAndAccountResults.existingAccounts()) ); foundChange = true; } } if (packPurchasesResults != null && !packPurchasesResults.isEmpty()) { packPurchasesResults.forEach( p -> virtualExec.submit(() -> nftAPI.addPackPurchases( p.uuid(), p.address(), p.packType().name(), p.height(), p.coinId()) ) ); logger.logApp(this.getClass(), TLogLevel.DEBUG, "Submitting purchases");
virtualExec.submit(new PackMint(cardList, packPurchasesResults, mintService, nftAPI, logger, virtualExec));
3
2023-11-14 14:56:37+00:00
8k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/Client.java
[ { "identifier": "MainCommand", "path": "src/main/java/com/github/codecnomad/codecclient/command/MainCommand.java", "snippet": "@SuppressWarnings(\"unused\")\n@Command(value = \"codecclient\", aliases = {\"codec\"})\npublic class MainCommand {\n List<BlockPos> waypoints = new ArrayList<>();\n @Main\n public void mainCommand() {\n Client.guiConfig.openGui();\n }\n\n Collection<BlockPos> path = new ArrayList<>();\n public static Pathfinding pathfinding = new Pathfinding();\n\n @SubCommand\n public void add(int x, int y, int z) {\n new Thread(() -> {\n MinecraftForge.EVENT_BUS.register(this);\n long start = System.currentTimeMillis();\n path = pathfinding.createPath(Client.mc.thePlayer.getPosition().add(0, -1, 0), new BlockPos(x, y - 1, z));\n Chat.sendMessage(System.currentTimeMillis() - start + \" ms\");\n if (path != null) {\n waypoints.clear();\n waypoints.addAll(path);\n Chat.sendMessage(String.format(\"Added waypoint: %d\", waypoints.size()));\n } else {\n Chat.sendMessage(\"Failed to find path..\");\n }\n }).start();\n }\n\n @SubscribeEvent\n public void renderWorld(RenderWorldLastEvent event) {\n if (path != null) {\n for (BlockPos pos : path) {\n Render.drawOutlinedFilledBoundingBox(pos.add(0, 1, 0), Config.VisualColor.toJavaColor(), event.partialTicks);\n }\n }\n }\n\n @SubCommand\n public void clear() {\n waypoints.clear();\n }\n\n @SubCommand\n public void start() {\n Chat.sendMessage(\"STARTED!!\");\n new Walker(waypoints, () -> Chat.sendMessage(\"Walked it!!\")).start();\n }\n}" }, { "identifier": "FishingMacro", "path": "src/main/java/com/github/codecnomad/codecclient/modules/FishingMacro.java", "snippet": "@SuppressWarnings(\"DuplicatedCode\")\npublic class FishingMacro extends Module {\n public static final String[] FAILSAFE_TEXT = new String[]{\"?\", \"you good?\", \"HI IM HERE\", \"can you not bro\", \"can you dont\", \"j g growl wtf\", \"can i get friend request??\", \"hello i'm here\",};\n public static int startTime = 0;\n public static int catches = 0;\n public static float xpGain = 0;\n public static FishingSteps currentStep = FishingSteps.FIND_ROD;\n public static Counter MainCounter = new Counter();\n public static Counter AlternativeCounter = new Counter();\n public static Counter FailsafeCounter = new Counter();\n public static boolean failSafe = false;\n Entity fishingHook = null;\n Entity fishingMarker = null;\n Entity fishingMonster = null;\n public static float lastYaw = 0;\n public static float lastPitch = 0;\n public static AxisAlignedBB lastAABB = null;\n public BlockPos startPos = null;\n public static Pathfinding pathfinding = new Pathfinding();\n\n @Override\n public void register() {\n MinecraftForge.EVENT_BUS.register(this);\n this.state = true;\n lastYaw = Client.mc.thePlayer.rotationYaw;\n lastPitch = Client.mc.thePlayer.rotationPitch;\n\n Sound.disableSounds();\n\n startTime = (int) java.lang.Math.floor((double) System.currentTimeMillis() / 1000);\n\n startPos = Client.mc.thePlayer.getPosition();\n }\n\n @Override\n public void unregister() {\n MinecraftForge.EVENT_BUS.unregister(this);\n this.state = false;\n\n Client.rotation.updatePitch = false;\n Client.rotation.updateYaw = false;\n lastPitch = 0;\n lastYaw = 0;\n\n Sound.enableSounds();\n\n startTime = 0;\n catches = 0;\n xpGain = 0;\n\n currentStep = FishingSteps.FIND_ROD;\n MainCounter.reset();\n FailsafeCounter.reset();\n failSafe = false;\n fishingHook = null;\n fishingMarker = null;\n fishingMonster = null;\n\n lastAABB = null;\n\n startPos = null;\n }\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (failSafe) {\n return;\n }\n\n switch (currentStep) {\n case GO_BACK_TO_ORIGINAL: {\n currentStep = FishingSteps.EMPTY;\n List<BlockPos> path = pathfinding.createPath(Client.mc.thePlayer.getPosition().add(0, -1 , 0), startPos.add(0, -1, 0));\n new Walker(path, () -> {\n currentStep = FishingSteps.FIND_ROD;\n }).start();\n return;\n }\n\n case FIND_ROD: {\n if (startPos != null && Client.mc.thePlayer.getPosition().distanceSq(startPos) > 1.5) {\n currentStep = FishingSteps.GO_BACK_TO_ORIGINAL;\n return;\n }\n\n for (int slotIndex = 0; slotIndex < 9; slotIndex++) {\n ItemStack stack = Client.mc.thePlayer.inventory.getStackInSlot(slotIndex);\n if (stack != null && stack.getItem() instanceof ItemFishingRod) {\n Client.rotation.setYaw(lastYaw, Config.RotationSmoothing);\n Client.rotation.setPitch(lastPitch, Config.RotationSmoothing);\n Client.mc.thePlayer.inventory.currentItem = slotIndex;\n currentStep = FishingSteps.CAST_HOOK;\n return;\n }\n }\n\n Chat.sendMessage(\"Disabled macro -> couldn't find rod.\");\n this.unregister();\n\n return;\n }\n\n case CAST_HOOK: {\n if (Client.rotation.updateYaw || Client.rotation.updatePitch) {\n return;\n }\n\n KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());\n\n currentStep = FishingSteps.WAIT_FOR_CATCH;\n return;\n }\n\n case WAIT_FOR_CATCH: {\n if (MainCounter.countUntil(Config.FishingDelay)) {\n return;\n }\n\n if (!AlternativeCounter.countUntil(Config.MovementFrequency)) {\n if (fishingHook == null) {\n currentStep = FishingSteps.FIND_ROD;\n return;\n }\n\n AxisAlignedBB aabb = fishingHook.getEntityBoundingBox();\n\n double expandedMinX = aabb.minX - 1;\n double expandedMinY = aabb.minY - 1;\n double expandedMinZ = aabb.minZ - 1;\n double expandedMaxX = aabb.maxX + 1;\n double expandedMaxY = aabb.maxY + 1;\n double expandedMaxZ = aabb.maxZ + 1;\n\n lastAABB = new AxisAlignedBB(expandedMinX, expandedMinY, expandedMinZ, expandedMaxX, expandedMaxY, expandedMaxZ);\n\n double randomX = expandedMinX + java.lang.Math.random() * (expandedMaxX - expandedMinX);\n double randomY = expandedMinY + java.lang.Math.random() * (expandedMaxY - expandedMinY);\n double randomZ = expandedMinZ + java.lang.Math.random() * (expandedMaxZ - expandedMinZ);\n\n Client.rotation.setYaw(Math.getYaw(new BlockPos(randomX, randomY, randomZ)), 5);\n Client.rotation.setPitch(Math.getPitch(new BlockPos(randomX, randomY, randomZ)), 5);\n }\n\n for (Entity entity : Client.mc.theWorld.loadedEntityList) {\n if (entity instanceof EntityFishHook && ((EntityFishHook) entity).angler == Client.mc.thePlayer) {\n fishingHook = entity;\n }\n }\n\n if (fishingHook == null) {\n currentStep = FishingSteps.FIND_ROD;\n return;\n }\n\n if (fishingMarker != null && fishingMarker.isEntityAlive() && fishingMarker.getName().contains(\"!!!\")) {\n currentStep = FishingSteps.CATCH;\n fishingMarker = null;\n return;\n }\n\n return;\n }\n\n case CATCH: {\n KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());\n\n if (Config.AutoKill) {\n currentStep = FishingSteps.KILL_DELAY;\n } else {\n currentStep = FishingSteps.FIND_ROD;\n }\n catches++;\n }\n\n case KILL_DELAY: {\n if (MainCounter.countUntil(Config.KillDelay)) {\n return;\n }\n\n currentStep = FishingSteps.KILL_MONSTER;\n }\n\n case KILL_MONSTER: {\n if (fishingMonster == null || !fishingMonster.isEntityAlive() || !Client.mc.thePlayer.canEntityBeSeen(fishingMonster)) {\n currentStep = FishingSteps.FIND_ROD;\n fishingMonster = null;\n return;\n }\n\n Client.mc.thePlayer.inventory.currentItem = Config.WeaponSlot - 1;\n\n AxisAlignedBB boundingBox = fishingMonster.getEntityBoundingBox();\n double deltaX = boundingBox.maxX - boundingBox.minX;\n double deltaY = boundingBox.maxY - boundingBox.minY;\n double deltaZ = boundingBox.maxZ - boundingBox.minZ;\n\n BlockPos randomPositionOnBoundingBox = new BlockPos(boundingBox.minX + deltaX, boundingBox.minY + deltaY, boundingBox.minZ + deltaZ);\n Client.rotation.setYaw(Math.getYaw(randomPositionOnBoundingBox), Config.RotationSmoothing);\n Client.rotation.setPitch(Math.getPitch(randomPositionOnBoundingBox), Config.RotationSmoothing);\n\n if (!MainCounter.countUntil(20 / Config.AttackCps)) {\n MainCounter.add(java.lang.Math.random() * 100 > 70 ? 1 : 0);\n if (Config.RightClick) {\n KeyBinding.onTick(Client.mc.gameSettings.keyBindUseItem.getKeyCode());\n return;\n }\n KeyBinding.onTick(Client.mc.gameSettings.keyBindAttack.getKeyCode());\n }\n }\n }\n }\n\n @SubscribeEvent\n public void renderWorld(RenderWorldLastEvent event) {\n if (lastAABB != null) {\n Render.drawOutlinedFilledBoundingBox(lastAABB, Config.VisualColor.toJavaColor(), event.partialTicks);\n }\n }\n\n @SubscribeEvent\n public void entitySpawn(EntityJoinWorldEvent event) {\n if (fishingHook == null || event.entity instanceof EntitySquid || event.entity.getName().equals(\"item.tile.stone.stone\")) {\n return;\n }\n\n if (event.entity instanceof EntityArmorStand && event.entity.getDistanceToEntity(fishingHook) <= 0.1) {\n fishingMarker = event.entity;\n return;\n }\n\n if (fishingMonster == null &&\n event.entity.getDistanceToEntity(fishingHook) <= 1.5\n ) {\n fishingMonster = event.entity;\n }\n }\n\n @SubscribeEvent\n public void chatReceive(ClientChatReceivedEvent event) {\n if (event.type != 2) {\n return;\n }\n\n Matcher matcher = Regex.FishingSkillPattern.matcher(event.message.getFormattedText());\n if (matcher.find()) {\n xpGain += Float.parseFloat(matcher.group(1));\n }\n }\n\n @SubscribeEvent\n public void packetReceive(PacketEvent.ReceiveEvent event) {\n if (\n event.packet instanceof S08PacketPlayerPosLook ||\n event.packet instanceof S09PacketHeldItemChange ||\n (\n event.packet instanceof S19PacketEntityHeadLook && ((S19PacketAccessor) event.packet).getEntityId() == Client.mc.thePlayer.getEntityId()\n ) ||\n (\n event.packet instanceof S1BPacketEntityAttach && ((S1BPacketEntityAttach) event.packet).getEntityId() == Client.mc.thePlayer.getEntityId()\n ) ||\n (\n event.packet instanceof S18PacketEntityTeleport && ((S18PacketEntityTeleport) event.packet).getEntityId() == Client.mc.thePlayer.getEntityId()\n )\n ) {\n Chat.sendMessage(\"Disabled macro -> failsafe has been triggered\");\n Client.rotation.reset();\n failSafe = true;\n }\n }\n\n @SubscribeEvent\n public void clientTick(TickEvent.ClientTickEvent event) {\n if (!failSafe) {\n return;\n }\n\n if (FailsafeCounter.countUntil(120)) {\n\n Sound.enableSounds();\n Client.mc.thePlayer.playSound(\"random.anvil_land\", 10.f, 1.f);\n\n if (Config.OnlySound) {\n return;\n }\n\n switch (FailsafeCounter.get()) {\n case 20: {\n Client.rotation.setYaw((float) (Client.mc.thePlayer.rotationYaw - 89 + (java.lang.Math.random() * 180)), Config.RotationSmoothing);\n Client.rotation.setPitch((float) (Client.mc.thePlayer.rotationPitch - 14 + (java.lang.Math.random() * 30)), Config.RotationSmoothing);\n\n KeyBinding.setKeyBindState(Minecraft.getMinecraft().gameSettings.keyBindBack.getKeyCode(), true);\n KeyBinding.setKeyBindState(Minecraft.getMinecraft().gameSettings.keyBindRight.getKeyCode(), true);\n break;\n }\n\n case 45: {\n KeyBinding.setKeyBindState(Minecraft.getMinecraft().gameSettings.keyBindBack.getKeyCode(), false);\n KeyBinding.setKeyBindState(Minecraft.getMinecraft().gameSettings.keyBindRight.getKeyCode(), false);\n break;\n }\n\n case 60: {\n Client.mc.thePlayer.sendChatMessage(FAILSAFE_TEXT[(int) (java.lang.Math.random() * FAILSAFE_TEXT.length)]);\n\n Client.rotation.setYaw((float) (Client.mc.thePlayer.rotationYaw - 89 + (java.lang.Math.random() * 180)), Config.RotationSmoothing);\n Client.rotation.setPitch((float) (Client.mc.thePlayer.rotationPitch - 14 + (java.lang.Math.random() * 30)), Config.RotationSmoothing);\n break;\n }\n\n case 80: {\n Client.rotation.setYaw((float) (Client.mc.thePlayer.rotationYaw - 89 + (java.lang.Math.random() * 180)), Config.RotationSmoothing);\n Client.rotation.setPitch((float) (Client.mc.thePlayer.rotationPitch - 14 + (java.lang.Math.random() * 30)), Config.RotationSmoothing);\n break;\n }\n\n case 90: {\n KeyBinding.setKeyBindState(Minecraft.getMinecraft().gameSettings.keyBindForward.getKeyCode(), true);\n break;\n }\n\n case 105: {\n KeyBinding.setKeyBindState(Minecraft.getMinecraft().gameSettings.keyBindForward.getKeyCode(), false);\n break;\n }\n }\n } else {\n failSafe = false;\n this.unregister();\n }\n }\n\n public enum FishingSteps {\n EMPTY,\n GO_BACK_TO_ORIGINAL,\n FIND_ROD,\n CAST_HOOK,\n WAIT_FOR_CATCH,\n CATCH,\n KILL_DELAY,\n KILL_MONSTER\n }\n}" }, { "identifier": "Module", "path": "src/main/java/com/github/codecnomad/codecclient/modules/Module.java", "snippet": "public class Module {\n public boolean state;\n\n public void register() {\n MinecraftForge.EVENT_BUS.register(this);\n this.state = true;\n }\n\n public void unregister() {\n MinecraftForge.EVENT_BUS.unregister(this);\n this.state = false;\n }\n}" }, { "identifier": "Config", "path": "src/main/java/com/github/codecnomad/codecclient/ui/Config.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Config extends cc.polyfrost.oneconfig.config.Config {\n @Color(\n name = \"Color\",\n category = \"Visuals\"\n )\n public static OneColor VisualColor = new OneColor(100, 60, 160, 200);\n @KeyBind(\n name = \"Fishing key-bind\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);\n @Number(\n name = \"Catch delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 20\n )\n public static int FishingDelay = 10;\n @Number(\n name = \"Kill delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 40\n )\n public static int KillDelay = 20;\n @Number(\n name = \"Attack c/s\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 20\n )\n public static int AttackCps = 10;\n\n @Number(\n name = \"Smoothing\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 2,\n max = 10\n )\n public static int RotationSmoothing = 4;\n\n @Number(\n name = \"Random movement frequency\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 50\n )\n public static int MovementFrequency = 15;\n\n @Switch(\n name = \"Auto kill\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean AutoKill = true;\n\n @Switch(\n name = \"Only sound failsafe\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean OnlySound = false;\n\n @Number(\n name = \"Weapon slot\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 9\n )\n public static int WeaponSlot = 9;\n\n @Switch(\n name = \"Right click attack\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean RightClick = false;\n\n @HUD(\n name = \"Fishing HUD\",\n category = \"Visuals\"\n )\n public FishingHud hudFishing = new FishingHud();\n\n public Config() {\n super(new Mod(\"CodecClient\", ModType.UTIL_QOL), \"config.json\");\n initialize();\n\n registerKeyBind(FishingKeybinding, () -> toggle(\"FishingMacro\"));\n save();\n }\n\n private static void toggle(String name) {\n Module helperClassModule = Client.modules.get(name);\n if (helperClassModule.state) {\n helperClassModule.unregister();\n } else {\n helperClassModule.register();\n }\n }\n}" }, { "identifier": "Rotation", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Rotation.java", "snippet": "public class Rotation {\n public boolean updateYaw = false;\n public boolean updatePitch = false;\n private float yawGoal = 0;\n private float pitchGoal = 0;\n private int yawSmooth;\n private int pitchSmooth;\n\n public void setYaw(float yaw, int smoothing) {\n yawGoal = yaw;\n yawSmooth = smoothing;\n updateYaw = true;\n }\n\n public void setPitch(float pitch, int smoothing) {\n pitchGoal = pitch;\n pitchSmooth = smoothing;\n updatePitch = true;\n }\n\n public void reset() {\n updateYaw = false;\n updatePitch = false;\n }\n\n @SubscribeEvent\n public void clientTick(TickEvent.ClientTickEvent event) {\n if (updateYaw) {\n Client.mc.thePlayer.rotationYaw = Math.interpolate(yawGoal, Client.mc.thePlayer.rotationYaw, (float) 1 / yawSmooth);\n if (java.lang.Math.abs(Client.mc.thePlayer.rotationYaw - yawGoal) < java.lang.Math.random() * 3) {\n updateYaw = false;\n }\n }\n\n if (updatePitch) {\n Client.mc.thePlayer.rotationPitch = Math.interpolate(pitchGoal, Client.mc.thePlayer.rotationPitch, (float) 1 / pitchSmooth);\n if (java.lang.Math.abs(Client.mc.thePlayer.rotationPitch - pitchGoal) < java.lang.Math.random() * 3) {\n updatePitch = false;\n }\n }\n }\n}" } ]
import cc.polyfrost.oneconfig.utils.commands.CommandManager; import com.github.codecnomad.codecclient.command.MainCommand; import com.github.codecnomad.codecclient.modules.FishingMacro; import com.github.codecnomad.codecclient.modules.Module; import com.github.codecnomad.codecclient.ui.Config; import com.github.codecnomad.codecclient.utils.Rotation; import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.network.FMLNetworkEvent; import java.util.HashMap; import java.util.Map;
5,009
package com.github.codecnomad.codecclient; @Mod(modid = "codecclient", useMetadata = true) public class Client { public static Map<String, Module> modules = new HashMap<>(); public static Minecraft mc = Minecraft.getMinecraft(); public static Rotation rotation = new Rotation(); public static Config guiConfig; static {
package com.github.codecnomad.codecclient; @Mod(modid = "codecclient", useMetadata = true) public class Client { public static Map<String, Module> modules = new HashMap<>(); public static Minecraft mc = Minecraft.getMinecraft(); public static Rotation rotation = new Rotation(); public static Config guiConfig; static {
modules.put("FishingMacro", new FishingMacro());
1
2023-11-16 10:12:20+00:00
8k
maarlakes/common
src/main/java/cn/maarlakes/common/factory/bean/BeanFactories.java
[ { "identifier": "SpiServiceLoader", "path": "src/main/java/cn/maarlakes/common/spi/SpiServiceLoader.java", "snippet": "public final class SpiServiceLoader<T> implements Iterable<T> {\n\n private static final String PREFIX = \"META-INF/services/\";\n\n private static final ConcurrentMap<ClassLoader, ConcurrentMap<Class<?>, SpiServiceLoader<?>>> SERVICE_LOADER_CACHE = new ConcurrentHashMap<>();\n\n private final Class<T> service;\n\n private final ClassLoader loader;\n private final boolean isShared;\n\n private final Supplier<List<Holder>> holders = Lazy.of(this::loadServiceHolder);\n private final ConcurrentMap<Class<?>, T> serviceCache = new ConcurrentHashMap<>();\n\n private SpiServiceLoader(@Nonnull Class<T> service, ClassLoader loader, boolean isShared) {\n this.service = Objects.requireNonNull(service, \"Service interface cannot be null\");\n this.loader = (loader == null) ? ClassLoader.getSystemClassLoader() : loader;\n this.isShared = isShared;\n }\n\n public boolean isEmpty() {\n return this.holders.get().isEmpty();\n }\n\n @Nonnull\n public T first() {\n return this.firstOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public T first(@Nonnull Class<? extends T> serviceType) {\n return this.firstOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> firstOptional() {\n return this.firstOptional(this.service);\n }\n\n @Nonnull\n public Optional<T> firstOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream().filter(item -> serviceType.isAssignableFrom(item.serviceType)).map(this::loadService).findFirst();\n }\n\n @Nonnull\n public T last() {\n return this.lastOptional().orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + this.service.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional() {\n return this.lastOptional(this.service);\n }\n\n @Nonnull\n public T last(@Nonnull Class<? extends T> serviceType) {\n return this.lastOptional(serviceType).orElseThrow(() -> new SpiServiceException(\"No service provider found for \" + serviceType.getName()));\n }\n\n @Nonnull\n public Optional<T> lastOptional(@Nonnull Class<? extends T> serviceType) {\n return this.holders.get().stream()\n .filter(item -> serviceType.isAssignableFrom(item.serviceType))\n .sorted((left, right) -> Holder.compare(right, left))\n .map(this::loadService)\n .findFirst();\n }\n\n @Nonnull\n @Override\n public Iterator<T> iterator() {\n return this.holders.get().stream().map(this::loadService).iterator();\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service) {\n return load(service, Thread.currentThread().getContextClassLoader());\n }\n\n @Nonnull\n public static <S> SpiServiceLoader<S> load(@Nonnull Class<S> service, @Nonnull ClassLoader loader) {\n return new SpiServiceLoader<>(service, loader, false);\n }\n\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service) {\n return loadShared(service, Thread.currentThread().getContextClassLoader());\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <S> SpiServiceLoader<S> loadShared(@Nonnull Class<S> service, @Nonnull ClassLoader loader) {\n return (SpiServiceLoader<S>) SERVICE_LOADER_CACHE.computeIfAbsent(loader, k -> new ConcurrentHashMap<>())\n .computeIfAbsent(service, k -> new SpiServiceLoader<>(service, loader, true));\n }\n\n private T loadService(@Nonnull Holder holder) {\n if (holder.spiService != null && holder.spiService.lifecycle() == SpiService.Lifecycle.SINGLETON) {\n return this.serviceCache.computeIfAbsent(holder.serviceType, k -> this.createService(holder));\n }\n return this.createService(holder);\n }\n\n private T createService(@Nonnull Holder holder) {\n try {\n return this.service.cast(holder.serviceType.getConstructor().newInstance());\n } catch (Exception e) {\n throw new SpiServiceException(e.getMessage(), e);\n }\n }\n\n\n private List<Holder> loadServiceHolder() {\n final Enumeration<URL>[] configArray = this.loadConfigs();\n try {\n final Map<String, Holder> map = new HashMap<>();\n for (Enumeration<URL> configs : configArray) {\n while (configs.hasMoreElements()) {\n final URL url = configs.nextElement();\n try (InputStream in = url.openStream()) {\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {\n String ln;\n int lineNumber = 0;\n while ((ln = reader.readLine()) != null) {\n lineNumber++;\n final int ci = ln.indexOf('#');\n if (ci >= 0) {\n ln = ln.substring(0, ci);\n }\n ln = ln.trim();\n if (!ln.isEmpty()) {\n this.check(url, ln, lineNumber);\n if (!map.containsKey(ln)) {\n final Class<?> type = Class.forName(ln, false, loader);\n if (!this.service.isAssignableFrom(type)) {\n throw new SpiServiceException(this.service.getName() + \": Provider\" + ln + \" not a subtype\");\n }\n map.put(ln, new Holder(type, type.getAnnotation(SpiService.class)));\n }\n }\n }\n }\n }\n }\n }\n if (map.isEmpty() && this.isShared) {\n // 移除\n SERVICE_LOADER_CACHE.remove(this.loader);\n }\n\n return map.values().stream().sorted().collect(Collectors.toList());\n } catch (IOException | ClassNotFoundException e) {\n if (this.isShared) {\n SERVICE_LOADER_CACHE.remove(this.loader);\n }\n throw new SpiServiceException(e);\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n private Enumeration<URL>[] loadConfigs() {\n final String fullName = PREFIX + service.getName();\n try {\n return new Enumeration[]{this.loader.getResources(fullName), ClassLoader.getSystemResources(fullName)};\n } catch (IOException e) {\n throw new SpiServiceException(service.getName() + \": Error locating configuration files\", e);\n }\n }\n\n private void check(@Nonnull URL url, @Nonnull String className, int lineNumber) {\n if ((className.indexOf(' ') >= 0) || (className.indexOf('\\t') >= 0)) {\n throw new SpiServiceException(this.service.getName() + \": \" + className + \":\" + lineNumber + \":Illegal configuration-file syntax\");\n }\n int cp = className.codePointAt(0);\n if (!Character.isJavaIdentifierStart(cp)) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n final int length = className.length();\n for (int i = Character.charCount(cp); i < length; i += Character.charCount(cp)) {\n cp = className.codePointAt(i);\n if (!Character.isJavaIdentifierPart(cp) && (cp != '.')) {\n throw new SpiServiceException(this.service.getName() + \": \" + url + \":\" + lineNumber + \":Illegal provider-class name: \" + className);\n }\n }\n }\n\n private static final class Holder implements Comparable<Holder> {\n\n private final Class<?> serviceType;\n\n private final SpiService spiService;\n\n private Holder(@Nonnull Class<?> serviceType, SpiService spiService) {\n this.serviceType = serviceType;\n this.spiService = spiService;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj instanceof Holder) {\n return this.serviceType == ((Holder) obj).serviceType;\n }\n return false;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(serviceType);\n }\n\n @Override\n public int compareTo(@Nullable Holder o) {\n if (o == null) {\n return 1;\n }\n return Integer.compare(this.spiService == null ? Integer.MAX_VALUE : this.spiService.order(), o.spiService == null ? Integer.MAX_VALUE : o.spiService.order());\n }\n\n public static int compare(Holder left, Holder right) {\n if (left == right) {\n return 0;\n }\n if (left == null) {\n return -1;\n }\n return left.compareTo(right);\n }\n }\n}" }, { "identifier": "ClassUtils", "path": "src/main/java/cn/maarlakes/common/utils/ClassUtils.java", "snippet": "public final class ClassUtils {\n private ClassUtils() {\n }\n\n private static final Map<Class<?>, Class<?>> PRIMITIVE_WRAPPER_MAP = new HashMap<>();\n\n static {\n PRIMITIVE_WRAPPER_MAP.put(Boolean.TYPE, Boolean.class);\n PRIMITIVE_WRAPPER_MAP.put(Byte.TYPE, Byte.class);\n PRIMITIVE_WRAPPER_MAP.put(Character.TYPE, Character.class);\n PRIMITIVE_WRAPPER_MAP.put(Short.TYPE, Short.class);\n PRIMITIVE_WRAPPER_MAP.put(Integer.TYPE, Integer.class);\n PRIMITIVE_WRAPPER_MAP.put(Long.TYPE, Long.class);\n PRIMITIVE_WRAPPER_MAP.put(Double.TYPE, Double.class);\n PRIMITIVE_WRAPPER_MAP.put(Float.TYPE, Float.class);\n PRIMITIVE_WRAPPER_MAP.put(Void.TYPE, Void.TYPE);\n }\n\n @Nonnull\n public static Constructor<?> getMatchingAccessibleDeclaredConstructor(Class<?> clazz, Object... args) {\n return getMatchingAccessibleDeclaredConstructor(clazz, parameterTypes(args));\n }\n\n @Nonnull\n public static Constructor<?> getMatchingAccessibleDeclaredConstructor(Class<?> clazz, Class<?>... parameterTypes) {\n Exception exception = null;\n try {\n return clazz.getDeclaredConstructor(parameterTypes);\n } catch (NoSuchMethodException e) {\n exception = e;\n }\n\n final Constructor<?>[] constructors = clazz.getDeclaredConstructors();\n final Constructor<?> ctr = Arrays.stream(constructors)\n .filter(constructor -> matchTypes(constructor.getParameterTypes(), parameterTypes))\n .findFirst()\n .orElse(null);\n if (ctr != null) {\n return ctr;\n }\n throw new IllegalStateException(exception);\n }\n\n public static Class<?>[] parameterTypes(@Nonnull Object... args) {\n final Class<?>[] types = new Class[args.length];\n for (int i = 0; i < args.length; i++) {\n final Object arg = args[i];\n if (arg != null) {\n types[i] = arg.getClass();\n }\n }\n return types;\n }\n\n private static boolean matchTypes(Class<?>[] left, Class<?>[] right) {\n if (left.length != right.length) {\n return false;\n }\n for (int i = 0; i < left.length; i++) {\n final Class<?> l = wrapperType(left[i]);\n final Class<?> r = wrapperType(right[i]);\n if (r == null) {\n if (l.isPrimitive()) {\n return false;\n }\n } else {\n if (!l.isAssignableFrom(r)) {\n return false;\n }\n }\n }\n return true;\n }\n\n private static Class<?> wrapperType(Class<?> type) {\n if (type != null && type.isPrimitive()) {\n final Class<?> tmp = PRIMITIVE_WRAPPER_MAP.get(type);\n if (tmp != null) {\n return tmp;\n }\n }\n return type;\n }\n}" }, { "identifier": "Lazy", "path": "src/main/java/cn/maarlakes/common/utils/Lazy.java", "snippet": "public final class Lazy {\n private Lazy() {\n }\n\n @Nonnull\n public static <T> Supplier<T> of(@Nonnull Supplier<T> action) {\n return new Supplier<T>() {\n\n private volatile T value = null;\n private final Object sync = new Object();\n\n @Override\n public T get() {\n if (this.value == null) {\n synchronized (this.sync) {\n if (this.value == null) {\n this.value = action.get();\n }\n }\n }\n return this.value;\n }\n };\n }\n}" } ]
import cn.maarlakes.common.spi.SpiServiceLoader; import cn.maarlakes.common.utils.ClassUtils; import cn.maarlakes.common.utils.Lazy; import jakarta.annotation.Nonnull; import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.*; import java.util.function.Supplier;
4,174
throw new BeanException("Bean of type " + beanType.getName() + " not found."); } @Nonnull public static <T> Optional<T> getBeanOptional(@Nonnull Class<T> beanType) { return Optional.ofNullable(getBeanOrNull(beanType)); } @Nonnull public static <T> T getBean(@Nonnull Class<T> beanType, @Nonnull Object... args) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBean(beanType, args); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanType)) { return provider.getBean(beanType, args); } } throw new BeanException("Bean of type " + beanType.getName() + " not found."); } public static <T> T getBeanOrNull(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeanOrNull(beanType); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanType)) { return provider.getBeanOrNull(beanType); } } return null; } @Nonnull public static <T> T getBean(@Nonnull String beanName) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBean(beanName); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanName)) { return provider.getBean(beanName); } } throw new BeanException("Bean of name " + beanName + " not found."); } @Nonnull public static <T> Optional<T> getBeanOptional(@Nonnull String beanName) { return Optional.ofNullable(getBeanOrNull(beanName)); } public static <T> T getBeanOrNull(@Nonnull String beanName) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeanOrNull(beanName); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanName)) { return provider.getBeanOrNull(beanName); } } return null; } public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull T defaultValue) { final T bean = getBeanOrNull(beanType); if (bean == null) { return defaultValue; } return bean; } public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull Supplier<T> defaultValue) { final T bean = getBeanOrNull(beanType); if (bean == null) { return defaultValue.get(); } return bean; } @Nonnull public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Object... args) { return getBeanOrNew(beanType, ClassUtils.parameterTypes(args), args); } @Nonnull @SuppressWarnings("unchecked") public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Class<?>[] argTypes, @Nonnull Object[] args) { final T bean = getBeanOrNull(beanType); if (bean != null) { return bean; } return (T) newInstance(ClassUtils.getMatchingAccessibleDeclaredConstructor(beanType, argTypes), args); } @Nonnull public static <T> List<T> getBeans(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeans(beanType); } final List<T> list = new ArrayList<>(); for (BeanProvider provider : SERVICES) { list.addAll(provider.getBeans(beanType)); } return list; } @Nonnull public static <T> Map<String, T> getBeanMap(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeanMap(beanType); } final Map<String, T> map = new HashMap<>(); for (BeanProvider provider : SERVICES) { map.putAll(provider.getBeanMap(beanType)); } return map; } @Nonnull public static <T> Supplier<T> getBeanLazy(@Nonnull Class<T> beanType) {
package cn.maarlakes.common.factory.bean; /** * @author linjpxc */ public final class BeanFactories { private BeanFactories() { } private static final SpiServiceLoader<BeanProvider> SERVICES = SpiServiceLoader.loadShared(BeanProvider.class); public static boolean contains(@Nonnull Class<?> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().contains(beanType); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanType)) { return true; } } return false; } public static boolean contains(@Nonnull String beanName) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().contains(beanName); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanName)) { return true; } } return false; } @Nonnull public static <T> T getBean(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBean(beanType); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanType)) { return provider.getBean(beanType); } } throw new BeanException("Bean of type " + beanType.getName() + " not found."); } @Nonnull public static <T> Optional<T> getBeanOptional(@Nonnull Class<T> beanType) { return Optional.ofNullable(getBeanOrNull(beanType)); } @Nonnull public static <T> T getBean(@Nonnull Class<T> beanType, @Nonnull Object... args) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBean(beanType, args); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanType)) { return provider.getBean(beanType, args); } } throw new BeanException("Bean of type " + beanType.getName() + " not found."); } public static <T> T getBeanOrNull(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeanOrNull(beanType); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanType)) { return provider.getBeanOrNull(beanType); } } return null; } @Nonnull public static <T> T getBean(@Nonnull String beanName) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBean(beanName); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanName)) { return provider.getBean(beanName); } } throw new BeanException("Bean of name " + beanName + " not found."); } @Nonnull public static <T> Optional<T> getBeanOptional(@Nonnull String beanName) { return Optional.ofNullable(getBeanOrNull(beanName)); } public static <T> T getBeanOrNull(@Nonnull String beanName) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeanOrNull(beanName); } for (BeanProvider provider : SERVICES) { if (provider.contains(beanName)) { return provider.getBeanOrNull(beanName); } } return null; } public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull T defaultValue) { final T bean = getBeanOrNull(beanType); if (bean == null) { return defaultValue; } return bean; } public static <T> T getBeanOrDefault(@Nonnull Class<T> beanType, @Nonnull Supplier<T> defaultValue) { final T bean = getBeanOrNull(beanType); if (bean == null) { return defaultValue.get(); } return bean; } @Nonnull public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Object... args) { return getBeanOrNew(beanType, ClassUtils.parameterTypes(args), args); } @Nonnull @SuppressWarnings("unchecked") public static <T> T getBeanOrNew(@Nonnull Class<T> beanType, @Nonnull Class<?>[] argTypes, @Nonnull Object[] args) { final T bean = getBeanOrNull(beanType); if (bean != null) { return bean; } return (T) newInstance(ClassUtils.getMatchingAccessibleDeclaredConstructor(beanType, argTypes), args); } @Nonnull public static <T> List<T> getBeans(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeans(beanType); } final List<T> list = new ArrayList<>(); for (BeanProvider provider : SERVICES) { list.addAll(provider.getBeans(beanType)); } return list; } @Nonnull public static <T> Map<String, T> getBeanMap(@Nonnull Class<T> beanType) { if (SERVICES.isEmpty()) { return ReflectBeanProvider.getInstance().getBeanMap(beanType); } final Map<String, T> map = new HashMap<>(); for (BeanProvider provider : SERVICES) { map.putAll(provider.getBeanMap(beanType)); } return map; } @Nonnull public static <T> Supplier<T> getBeanLazy(@Nonnull Class<T> beanType) {
return Lazy.of(() -> getBean(beanType));
2
2023-11-18 07:49:00+00:00
8k
Mightinity/store-management-system
src/main/java/com/systeminventory/controller/productController.java
[ { "identifier": "App", "path": "src/main/java/com/systeminventory/App.java", "snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException{\n primaryStage = stage;\n loadLoginScene();\n\n }\n\n public static Stage getPrimaryStage(){\n return primaryStage;\n }\n\n public static void loadLoginScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setResizable(false);\n primaryStage.initStyle(StageStyle.UNDECORATED);\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadLogoutScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"loginLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Login - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"dashboardLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadProductScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"productLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Product - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"cashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Cashier - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n\n }\n public static void loadEmployeeDashboardScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeProductLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n public static void loadEmployeeCashierScene() throws IOException {\n FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(\"employeeCashierLayout.fxml\"));\n Scene scene = new Scene(fxmlLoader.load());\n primaryStage.setTitle(\"Dashboard Employee - Store Inventory System\");\n primaryStage.setScene(scene);\n primaryStage.show();\n }\n\n}" }, { "identifier": "DeleteProductListener", "path": "src/main/java/com/systeminventory/interfaces/DeleteProductListener.java", "snippet": "public interface DeleteProductListener {\n public void clickDeleteProductListener(Product product);\n}" }, { "identifier": "DetailsProductListener", "path": "src/main/java/com/systeminventory/interfaces/DetailsProductListener.java", "snippet": "public interface DetailsProductListener {\n public void clickDetailsProductListener(Product product);\n}" }, { "identifier": "EditProductListener", "path": "src/main/java/com/systeminventory/interfaces/EditProductListener.java", "snippet": "public interface EditProductListener {\n public void clickEditProductListener(Product product);\n}" }, { "identifier": "Product", "path": "src/main/java/com/systeminventory/model/Product.java", "snippet": "public class Product {\n private String productName;\n private String imageSource;\n private String productOriginalPrice;\n private String productSellingPrice;\n private String productStock;\n private String keyProduct;\n private String idProduct;\n\n\n\n public String getProductName() {\n return productName;\n }\n\n public void setProductName(String productName) {\n this.productName = productName;\n }\n\n public String getImageSource() {\n return imageSource;\n }\n\n public void setImageSource(String imageSource) {\n this.imageSource = imageSource;\n }\n\n public String getProductSellingPrice() {\n return productSellingPrice;\n }\n\n public void setProductSellingPrice(String productSellingPrice) {\n this.productSellingPrice = productSellingPrice;\n }\n\n public String getProductStock() {\n return productStock;\n }\n\n public void setProductStock(String productStock) {\n this.productStock = productStock;\n }\n\n public String getKeyProduct() {\n return keyProduct;\n }\n\n public void setKeyProduct(String keyProduct) {\n this.keyProduct = keyProduct;\n }\n\n public String getProductOriginalPrice() {\n return productOriginalPrice;\n }\n\n public void setProductOriginalPrice(String productOriginalPrice) {\n this.productOriginalPrice = productOriginalPrice;\n }\n\n public String getIdProduct() {\n return idProduct;\n }\n\n public void setIdProduct(String idProduct) {\n this.idProduct = idProduct;\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.systeminventory.App; import com.systeminventory.interfaces.DeleteProductListener; import com.systeminventory.interfaces.DetailsProductListener; import com.systeminventory.interfaces.EditProductListener; import com.systeminventory.model.Product; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.*; import java.text.NumberFormat;
3,917
} private static String generateIdProduct(Random random){ StringBuilder randomString = new StringBuilder(); for (int i = 0; i < 12; i++){ char randomCharacter = randomCharacter(random); randomString.append(randomCharacter); } return randomString.toString(); } private static char randomCharacter(Random random){ String characters = "ABDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; int index = random.nextInt(characters.length()); return characters.charAt(index); } @FXML private void onAddProductCancelButtonClick(ActionEvent actionEvent) { backgroundPopup.setVisible(false); addProductPopup.setVisible(false); } @FXML private void onAddProductApplyButtonMouseEnter(MouseEvent mouseEvent) { addProductApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProductApplyButtonMouseExit(MouseEvent mouseEvent) { addProductApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProductCancelButtonMouseEnter(MouseEvent mouseEvent) { addProductCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13"); } @FXML private void onAddProductCancelButtonMouseExit(MouseEvent mouseEvent) { addProductCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13"); } @FXML private void onAddProductChooseFilePaneMouseEnter(MouseEvent mouseEvent) { addProductChooseFilePane.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;"); } @FXML private void onAddProductChooseFilePaneMouseExit(MouseEvent mouseEvent) { addProductChooseFilePane.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;"); } @FXML private void onAddProductChooseFilePaneMouseClick(MouseEvent mouseEvent) { FileChooser filechooser = new FileChooser(); filechooser.setTitle("Select product image"); filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png")); File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage()); if(selectedFile != null){ setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:"); addProductProductImagePathLabel.setText(selectedFile.getName()); addProductProductImageGetFullPathLabel.setText(selectedFile.getPath()); } } @FXML private void onAddProductOriginalPriceKeyTyped(KeyEvent keyEvent) { addProductOriginalPriceField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) { if(!newValue.matches("\\d*")){ addProductOriginalPriceField.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML private void onAddProductSellingPriceKeyTyped(KeyEvent keyEvent) { addProductSellingPriceField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) { if(!newValue.matches("\\d*")){ addProductSellingPriceField.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML private void onAddProductProductStockKeyTyped(KeyEvent keyEvent) { addProductProductStockField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) { if(!newValue.matches("\\d*")){ addProductProductStockField.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML private void onButtonAddProductClick(ActionEvent actionEvent) throws IOException { addProductLabel.setText("Add Product"); addProductProductNameField.setText(""); addProductOriginalPriceField.setText(""); addProductSellingPriceField.setText(""); addProductProductImagePathLabel.setText(""); addProductProductStockField.setText(""); setLabelPropertiesTextFillWhite(addProductProductNameLabel, "Product name:"); setLabelPropertiesTextFillWhite(addProductOriginalPriceLabel, "Original price:"); setLabelPropertiesTextFillWhite(addProductSellingPriceLabel, "Selling price:"); setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:"); setLabelPropertiesTextFillWhite(addProductProductStockLabel, "Product stock:"); backgroundPopup.setVisible(true); addProductPopup.setVisible(true); }
package com.systeminventory.controller; public class productController { @FXML public Pane filterDropdown; @FXML public Button filterButton; public ImageView imageFIlter; @FXML private Pane profileDropdown; @FXML private Button settingsDropdown; @FXML private Button buttonCashier; @FXML private Button buttonProduct; @FXML private Button logoutDropdown; @FXML private Button buttonDashboard; @FXML private ScrollPane scrollPane; @FXML private Button buttonAddProduct; @FXML public Pane backgroundPopup; @FXML private Pane addProductPopup; @FXML private Button addProductApplyButton; @FXML private Button addProductCancelButton; @FXML private TextField addProductProductNameField; @FXML private TextField addProductOriginalPriceField; @FXML private TextField addProductSellingPriceField; @FXML private TextField addProductProductStockField; @FXML private Label addProductProductImagePathLabel; @FXML private Pane addProductChooseFilePane; @FXML private Label addProductProductImageLabel; @FXML private Label addProductSellingPriceLabel; @FXML private Label addProductOriginalPriceLabel; @FXML private Label addProductProductNameLabel; @FXML private Label addProductProductStockLabel; @FXML private GridPane productCardContainer; @FXML private Label addProductProductImageGetFullPathLabel; @FXML private TextField searchProductNameField; @FXML private Label confirmDeleteVariableProductName; @FXML private Button confirmDeleteDeleteButton; @FXML private Button confirmDeleteCancelButton; @FXML private Label confirmDeleteKeyProduct; @FXML public Pane confirmDeletePane; @FXML private Label addProductLabel; @FXML private Label keyProductOnPopUp; @FXML private Pane detailsProductPopup; @FXML private Label varProductNameDetailsProduct; @FXML private Label varOriginalPriceDetailsProduct; @FXML private Label varSellingPriceDetailsProduct; @FXML private Label varProductStockDetailsProduct; @FXML private ImageView barcodeImageDetailsProduct; private DeleteProductListener deleteProductListener; private EditProductListener editProductListener; private DetailsProductListener detailsProductListener; @FXML private Button downloadBarcodeDetailsProduct; @FXML private Button cancelButtonDetailsProduct; @FXML private Label idProductDetailsProduct; @FXML private Pane downloadAlertPopup; @FXML private Label varStatusDownload; @FXML private Button okButtonStatusDownloadPopup; @FXML private Label confirmDeleteKeyProduct1; @FXML private Pane backgroundPopupDownload; @FXML void onButtonCashierClick(ActionEvent event) throws IOException { App.loadCashierScene(); } @FXML void onButtonDashboardClick(ActionEvent event) throws IOException { App.loadDashboardScene(); } @FXML void onButtonProductClick(ActionEvent event) throws IOException { } @FXML void onLogoutClick(ActionEvent event) throws IOException { App.loadLogoutScene(); } @FXML void onProfileClick(MouseEvent event) { profileDropdown.setVisible(!profileDropdown.isVisible()); } @FXML void onLogoutDropdownMouseEnter(MouseEvent event) { logoutDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11"); } @FXML void onLogoutDropdownMouseExit(MouseEvent event) { logoutDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11"); } @FXML void onSettingsDropdownMouseEnter(MouseEvent event) { settingsDropdown.setStyle("-fx-background-color: #2f3d4e;" + "-fx-background-radius: 11"); } @FXML void onSettingsDropdownMouseExit(MouseEvent event) { settingsDropdown.setStyle("-fx-background-color: #1c242e;" + "-fx-background-radius: 11"); } @FXML private void onButtonProductMouseEnter(MouseEvent mouseEvent) { } @FXML private void onButtonProductMouseExit(MouseEvent mouseEvent) { } @FXML private void onCashierProductMouseEnter(MouseEvent mouseEvent) { buttonCashier.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML private void onCashierProductMouseExit(MouseEvent mouseEvent) { buttonCashier.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML private void onProfileDropdownMouseExit(MouseEvent mouseEvent) { profileDropdown.setVisible(false); } @FXML private void onButtonDashboardMouseEnter(MouseEvent mouseEvent) { buttonDashboard.setStyle("-fx-background-color: #697b7b;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #151d26;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } @FXML private void onButtonDashboardMouseExit(MouseEvent mouseEvent) { buttonDashboard.setStyle("-fx-background-color: #151d26;" + "-fx-border-color: #697b7b;" + "-fx-text-fill: #697b7b;" + "-fx-background-radius: 20;" + "-fx-border-radius: 20;"); } public void onFilterButtonClick(ActionEvent actionEvent) { filterDropdown.setVisible(!filterDropdown.isVisible()); } @FXML public void onFilterButtonMouseEnter(MouseEvent mouseEvent) { filterButton.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;"); } @FXML public void onFilterButtonMouseExit(MouseEvent mouseEvent) { filterButton.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 20;"); } @FXML public void onImageFilterMouseEnter(MouseEvent mouseEvent) { filterButton.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;"); } @FXML public void onFilterDropdownMouseExit(MouseEvent mouseEvent) { filterDropdown.setVisible(false); } @FXML private void onImageFilterMouseClick(MouseEvent mouseEvent) { filterDropdown.setVisible(!filterDropdown.isVisible()); } @FXML private void onButtonAddProductMouseExit(MouseEvent mouseEvent) { buttonAddProduct.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 20;"); } @FXML private void onButtonAddProductMouseEnter(MouseEvent mouseEvent) { buttonAddProduct.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 20;"); } private void setLabelPropertiesTextFillWhite(Label label, String text){ label.setText(text); label.setStyle("-fx-text-fill: #f6f6f6;"); } @FXML private void onAddProductApplyButtonClick(ActionEvent actionEvent) throws IOException { String jsonPath = "./src/main/java/com/systeminventory/assets/json/productList.json"; String imageProductPath = "./src/main/java/com/systeminventory/assets/imagesProduct/"; setLabelPropertiesTextFillWhite(addProductProductNameLabel, "Product name:"); setLabelPropertiesTextFillWhite(addProductOriginalPriceLabel, "Original price:"); setLabelPropertiesTextFillWhite(addProductSellingPriceLabel, "Selling price:"); setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:"); setLabelPropertiesTextFillWhite(addProductProductStockLabel, "Product stock:"); TextField[] fields = { addProductProductNameField, addProductOriginalPriceField, addProductSellingPriceField, addProductProductStockField }; Label[] labels = { addProductProductNameLabel, addProductOriginalPriceLabel, addProductSellingPriceLabel, addProductProductStockLabel }; if (addProductLabel.getText().equals("Add Product")){ int status = 0; for (int i = 0; i < fields.length;i++){ TextField field = fields[i]; Label label = labels[i]; if(field.getText().isEmpty()){ label.setText(label.getText()+" (Required)"); label.setStyle("-fx-text-fill: #ff1474;"); status++; } } if (addProductProductImagePathLabel.getText().isEmpty()){ addProductProductImageLabel.setText("Product image: (Required)"); addProductProductImageLabel.setStyle("-fx-text-fill: #ff1474;"); status++; } if (status == 0){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); Random random = new Random(); try (InputStream inputStream = new FileInputStream(jsonPath)){ InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); List<String> productKeys = new ArrayList<>(jsonObject.keySet()); //Collections.sort(productKeys); int nextKeyNumber = productKeys.size()+1; String newProductKey = "product"+nextKeyNumber; while (productKeys.contains(newProductKey)){ nextKeyNumber++; newProductKey = "product"+nextKeyNumber; } JsonObject newProductData = new JsonObject(); int originalPrice = Integer.parseInt(addProductOriginalPriceField.getText()); int sellingPrice = Integer.parseInt(addProductSellingPriceField.getText()); int stock = Integer.parseInt(addProductProductStockField.getText()); String imageFileName = addProductProductImagePathLabel.getText(); Path sourceImagePath = Paths.get(addProductProductImageGetFullPathLabel.getText()); Path targetImagePath = Paths.get(imageProductPath, imageFileName); newProductData.addProperty("idProduct", generateIdProduct(random)); newProductData.addProperty("Title", addProductProductNameField.getText()); newProductData.addProperty("OriginalPrice", originalPrice); newProductData.addProperty("SellingPrice", sellingPrice); newProductData.addProperty("Image", imageProductPath+imageFileName); newProductData.addProperty("Stock", stock); try{ Files.copy(sourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException err){ err.printStackTrace(); } jsonObject.add(newProductKey, newProductData); try (Writer writer = new FileWriter(jsonPath)){ gson.toJson(jsonObject, writer); } } catch (IOException err){ err.printStackTrace(); } App.loadProductScene(); } } else if (addProductLabel.getText().equals("Edit Product")) { int status = 0; for (int i = 0; i < fields.length; i++) { TextField field = fields[i]; Label label = labels[i]; if (field.getText().isEmpty()) { label.setText(label.getText() + " (Required)"); label.setStyle("-fx-text-fill: #ff1474;"); status++; } } if (addProductProductImagePathLabel.getText().isEmpty()) { addProductProductImageLabel.setText("Product image: (Required)"); addProductProductImageLabel.setStyle("-fx-text-fill: #ff1474;"); status++; } if (status == 0) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (InputStream inputStream = new FileInputStream(jsonPath)) { InputStreamReader reader = new InputStreamReader(inputStream); JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); JsonObject productKey = jsonObject.getAsJsonObject(keyProductOnPopUp.getText()); if (keyProductOnPopUp.getText() != null) { int originalPrice = Integer.parseInt(addProductOriginalPriceField.getText()); int sellingPrice = Integer.parseInt(addProductSellingPriceField.getText()); int stock = Integer.parseInt(addProductProductStockField.getText()); String imageFileName = addProductProductImagePathLabel.getText(); if (!(imageProductPath + imageFileName).equals(productKey.get("Image").getAsString())) { Path newSourceImagePath = Paths.get(addProductProductImageGetFullPathLabel.getText()); Path targetImagePath = Paths.get(imageProductPath, imageFileName); try { Files.copy(newSourceImagePath, targetImagePath, StandardCopyOption.REPLACE_EXISTING); } catch (IOException err) { err.printStackTrace(); } } productKey.addProperty("Title", addProductProductNameField.getText()); productKey.addProperty("OriginalPrice", originalPrice); productKey.addProperty("SellingPrice", sellingPrice); productKey.addProperty("Image", imageProductPath + imageFileName); productKey.addProperty("Stock", stock); try (Writer writer = new FileWriter(jsonPath)) { gson.toJson(jsonObject, writer); } } } catch (IOException err) { err.printStackTrace(); } } App.loadProductScene(); } } private static String generateIdProduct(Random random){ StringBuilder randomString = new StringBuilder(); for (int i = 0; i < 12; i++){ char randomCharacter = randomCharacter(random); randomString.append(randomCharacter); } return randomString.toString(); } private static char randomCharacter(Random random){ String characters = "ABDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; int index = random.nextInt(characters.length()); return characters.charAt(index); } @FXML private void onAddProductCancelButtonClick(ActionEvent actionEvent) { backgroundPopup.setVisible(false); addProductPopup.setVisible(false); } @FXML private void onAddProductApplyButtonMouseEnter(MouseEvent mouseEvent) { addProductApplyButton.setStyle("-fx-background-color: #33b8ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProductApplyButtonMouseExit(MouseEvent mouseEvent) { addProductApplyButton.setStyle("-fx-background-color: #00a6ff;" + "-fx-background-radius: 13"); } @FXML private void onAddProductCancelButtonMouseEnter(MouseEvent mouseEvent) { addProductCancelButton.setStyle("-fx-background-color: #e0005c;" + "-fx-background-radius: 13"); } @FXML private void onAddProductCancelButtonMouseExit(MouseEvent mouseEvent) { addProductCancelButton.setStyle("-fx-background-color: #ff1474;" + "-fx-background-radius: 13"); } @FXML private void onAddProductChooseFilePaneMouseEnter(MouseEvent mouseEvent) { addProductChooseFilePane.setStyle("-fx-background-color: #ffa132;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;"); } @FXML private void onAddProductChooseFilePaneMouseExit(MouseEvent mouseEvent) { addProductChooseFilePane.setStyle("-fx-background-color: #fe8a00;" + "-fx-background-radius: 5;" + "-fx-border-color: #f6f6f6;" + "-fx-border-radius: 5;"); } @FXML private void onAddProductChooseFilePaneMouseClick(MouseEvent mouseEvent) { FileChooser filechooser = new FileChooser(); filechooser.setTitle("Select product image"); filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png")); File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage()); if(selectedFile != null){ setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:"); addProductProductImagePathLabel.setText(selectedFile.getName()); addProductProductImageGetFullPathLabel.setText(selectedFile.getPath()); } } @FXML private void onAddProductOriginalPriceKeyTyped(KeyEvent keyEvent) { addProductOriginalPriceField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) { if(!newValue.matches("\\d*")){ addProductOriginalPriceField.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML private void onAddProductSellingPriceKeyTyped(KeyEvent keyEvent) { addProductSellingPriceField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) { if(!newValue.matches("\\d*")){ addProductSellingPriceField.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML private void onAddProductProductStockKeyTyped(KeyEvent keyEvent) { addProductProductStockField.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) { if(!newValue.matches("\\d*")){ addProductProductStockField.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML private void onButtonAddProductClick(ActionEvent actionEvent) throws IOException { addProductLabel.setText("Add Product"); addProductProductNameField.setText(""); addProductOriginalPriceField.setText(""); addProductSellingPriceField.setText(""); addProductProductImagePathLabel.setText(""); addProductProductStockField.setText(""); setLabelPropertiesTextFillWhite(addProductProductNameLabel, "Product name:"); setLabelPropertiesTextFillWhite(addProductOriginalPriceLabel, "Original price:"); setLabelPropertiesTextFillWhite(addProductSellingPriceLabel, "Selling price:"); setLabelPropertiesTextFillWhite(addProductProductImageLabel, "Product image:"); setLabelPropertiesTextFillWhite(addProductProductStockLabel, "Product stock:"); backgroundPopup.setVisible(true); addProductPopup.setVisible(true); }
private List<Product> readProductsFromJson(String searchTerm) {
4
2023-11-18 02:53:02+00:00
8k
CivilisationPlot/CivilisationPlot_Papermc
src/main/java/fr/laptoff/civilisationplot/civils/Civil.java
[ { "identifier": "CivilisationPlot", "path": "src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java", "snippet": "public final class CivilisationPlot extends JavaPlugin {\n\n public static final Logger LOGGER = Logger.getLogger(\"CivilisationPlot\");\n private static CivilisationPlot instance;\n private DatabaseManager database;\n private FileConfiguration configMessages; //Messages Manager (at /resources/config/english.yml)\n\n @Override\n public void onEnable() {\n instance = this;\n saveDefaultConfig();\n ConfigManager configManagerMessages = new ConfigManager(getConfig().getString(\"Language.language\"));\n configMessages = configManagerMessages.getFileConfiguration();\n\n if (getConfig().getBoolean(\"Database.enable\")){\n database = new DatabaseManager();\n database.connection();\n\n database.setup();\n\n LOGGER.info(configMessages.getString(\"Messages.Database.success_connection\"));\n }\n\n Civil.load();\n Nation.load();\n\n LOGGER.info(\"#### ## ### ## ## ## ###### ### ##\");\n LOGGER.info(\"## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####\");\n LOGGER.info(\"## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##\");\n LOGGER.info(\"## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###\");\n\n getServer().getPluginManager().registerEvents(new joinListener(), this);\n }\n\n @Override\n public void onDisable() {\n LOGGER.info(\"#### ## ### ## ## ## ###### ### ##\");\n LOGGER.info(\"## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## ## ### ## ### ##### #### ##### ### #### ##### ## ## ## #### #####\");\n LOGGER.info(\"## ## ## ## ## ## ## ## ## ## ## ## ## ## ##### ## ## ## ##\");\n LOGGER.info(\"## ## ## ## ## ## ##### ##### ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"## ## #### ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##\");\n LOGGER.info(\"#### ## #### #### #### ###### ##### ### #### #### ## ## #### #### #### ###\");\n\n if (DatabaseManager.isOnline()){\n database.disconnection();\n\n LOGGER.info(configMessages.getString(\"Messages.Database.success_disconnection\"));\n }\n }\n\n public static CivilisationPlot getInstance(){\n return instance;\n }\n\n public DatabaseManager getDatabase(){\n return database;\n }\n\n}" }, { "identifier": "DatabaseManager", "path": "src/main/java/fr/laptoff/civilisationplot/Managers/DatabaseManager.java", "snippet": "public class DatabaseManager {\n\n private static Connection co;\n private static final CivilisationPlot plugin = CivilisationPlot.getInstance();\n\n public Connection getConnection()\n {\n return co;\n }\n\n public void connection()\n {\n if(!isConnected())\n {\n try\n {\n String motorDriver = \"org.mariadb\";\n\n if (Objects.requireNonNull(plugin.getConfig().getString(\"Database.motor\")).equalsIgnoreCase(\"mysql\"))\n motorDriver = \"com.mysql.cj\";\n\n Class.forName(motorDriver + \".jdbc.Driver\"); //loading of the driver.\n co = DriverManager.getConnection(\"jdbc:\" + plugin.getConfig().getString(\"Database.motor\") + \"://\" + plugin.getConfig().getString(\"Database.host\") + \":\" + plugin.getConfig().getString(\"Database.port\") + \"/\" + plugin.getConfig().getString(\"Database.database_name\"), plugin.getConfig().getString(\"Database.user\"), plugin.getConfig().getString(\"Database.password\"));\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n }\n\n public void disconnection()\n {\n if (isConnected())\n {\n try\n {\n co.close();\n }\n catch(SQLException e)\n {\n e.printStackTrace();\n }\n }\n }\n\n\n\n public static boolean isConnected()\n {\n try {\n return co != null && !co.isClosed() && plugin.getConfig().getBoolean(\"Database.enable\");\n }\n catch (SQLException e)\n {\n e.printStackTrace();\n }\n return false;\n }\n\n public static boolean isOnline() {\n try {\n return !(co == null) || !co.isClosed();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public boolean doesTableExist(String tableName) {\n try {\n DatabaseMetaData metaData = co.getMetaData();\n ResultSet resultSet = metaData.getTables(null, null, tableName, null);\n\n return resultSet.next();\n } catch (SQLException e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n\n public void setup(){\n try {\n\n //create the civils table\n if (!doesTableExist(\"civils\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE civils (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), name VARCHAR(50), money INT, nation VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the nations table\n if (!doesTableExist(\"nations\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE nations (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), uuid VARCHAR(50), leader_uuid VARCHAR(50));\");\n pstmt.execute();\n }\n\n //create the plots table\n if (!doesTableExist(\"plots\")){\n PreparedStatement pstmt = this.getConnection().prepareStatement(\"CREATE TABLE plots (id INT AUTO_INCREMENT PRIMARY KEY, uuid VARCHAR(50), wordlName VARCHAR(50), xCoordinates DOUBLE, yCoordinates DOUBLE, level TINYINT, propertyType VARCHAR(50), uuidProprietary VARCHAR(50));\");\n pstmt.execute();\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n}" }, { "identifier": "FileManager", "path": "src/main/java/fr/laptoff/civilisationplot/Managers/FileManager.java", "snippet": "public class FileManager {\n\n public static void createResourceFile(File file){\n File file_ = new File(CivilisationPlot.getInstance().getDataFolder() + \"/\" + file.getPath());\n if (file_.exists())\n return;\n\n file.getParentFile().mkdirs();\n\n CivilisationPlot.getInstance().saveResource(file.getPath(), false);\n }\n\n public static void createFile(File file){\n if (file.exists())\n return;\n\n file.getParentFile().mkdirs();\n try {\n file.createNewFile();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void rewrite(File file, String text){\n //This method erase the text into the file and write the new text\n if (!file.exists())\n return;\n\n try {\n FileWriter writer = new FileWriter(file);\n BufferedWriter bw = new BufferedWriter(writer);\n bw.write(text);\n bw.flush();\n bw.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n}" }, { "identifier": "Nation", "path": "src/main/java/fr/laptoff/civilisationplot/nation/Nation.java", "snippet": "public class Nation {\n \n private String Name;\n private UUID Uuid;\n private Civil Leader;\n private File file;\n private static Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();\n private static List<String> nationList = new ArrayList<String>();\n\n \n public Nation(String name, UUID uuid, Civil leader){\n this.Name = name;\n this.Uuid = uuid;\n this.Leader = leader;\n leader.setNation(this);\n this.file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/Nations/\" + this.Uuid);\n\n if (!isExistIntoLocal() || !isExistIntoDatabase())\n save();\n }\n\n public String getName(){\n return this.Name;\n }\n\n public UUID getUuid(){\n return this.Uuid;\n }\n\n public Civil getLeader(){\n return this.Leader;\n }\n\n public void setName(String name){\n this.Name = name;\n }\n\n public void setLeader(Civil leader){\n setLeaderDatabase(leader);\n leader.setNation(this);\n this.Leader = leader;\n }\n\n public void setNameDatabase(String name){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE nations SET name = '\" + name + \"' WHERE uuid = '\" + this.Uuid.toString() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void setLeaderDatabase(Civil leader){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"UPDATE nations SET leader_uuid = '\" + leader.getUuid().toString() + \"' WHERE uuid = '\" + this.Uuid.toString() + \"';\");\n pstmt.execute();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n //Registers\n public void registerToList(){\n if (!nationList.contains(this.Uuid.toString()))\n nationList.add(this.Uuid.toString());\n }\n\n public void registerToLocal(){\n Gson gson = new GsonBuilder().create();\n\n FileManager.createFile(this.file);\n\n FileManager.rewrite(this.file, gson.toJson(this));\n }\n\n public void registerToDatabase(){\n if (co == null)\n return;\n\n if(this.isExistIntoDatabase())\n this.delFromDatabase();\n\n\n try{\n PreparedStatement pstmt = co.prepareStatement(\"INSERT INTO nations (name, uuid, leader_uuid) VALUES (?, ?, ?);\");\n pstmt.setString(1, this.Name);\n pstmt.setString(2, this.Uuid.toString());\n pstmt.setString(3, this.Leader.getUuid().toString());\n } catch(SQLException e){\n e.printStackTrace();\n }\n }\n\n //Getters\n public static Nation getFromNationList(UUID uuid){\n for (String nation : nationList){\n if (UUID.fromString(nation) == uuid)\n return getNation(UUID.fromString(nation));\n }\n return null;\n }\n\n public static Nation getFromLocal(UUID uuid){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/Nations/\" + uuid.toString());\n\n if (!file.exists())\n return null;\n\n Gson gson = new GsonBuilder().create();\n\n try {\n return gson.fromJson(Files.readString(Path.of(file.getPath())), Nation.class);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static Nation getFromDatabase(UUID uuid){\n if (!DatabaseManager.isOnline())\n return null;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM nations WHERE uuid = '\" + uuid + \"';\");\n ResultSet result = pstmt.executeQuery();\n\n while(result.next())\n return new Nation(result.getString(\"name\"), uuid, Civil.getCivil(UUID.fromString(result.getString(\"leader_uuid\"))));\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n\n return null;\n }\n\n public static Nation getNation(UUID uuid){\n if (getFromDatabase(uuid) == null)\n return getFromLocal(uuid);\n\n return getFromDatabase(uuid);\n }\n\n //Updates\n public static void updateLocalListFromProgramList(){\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/NationsList.json\");\n Gson gson = new GsonBuilder().create();\n\n\n FileManager.createFile(file);\n FileManager.rewrite(file, gson.toJson(nationList, ArrayList.class));\n }\n\n public static void updateProgramListFromLocalList(){\n Gson gson = new GsonBuilder().create();\n File file = new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/NationsList.json\");\n\n FileManager.createFile(file);\n try {\n nationList = gson.fromJson(Files.readString(Path.of(file.getPath())), ArrayList.class);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void updateProgramListFromDatabase(){\n if (!DatabaseManager.isOnline())\n return;\n\n nationList.clear();\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM nations;\");\n ResultSet result = pstmt.executeQuery();\n\n while(result.next()){\n Nation nation = new Nation(result.getString(\"name\"), UUID.fromString(result.getString(\"uuid\")), Civil.getCivil(UUID.fromString(result.getString(\"leader_uuid\"))));\n nationList.add(nation.getUuid().toString());\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void updateLocalFromDatabase(){\n for (String uuid : nationList){\n\n Nation nation = getFromDatabase(UUID.fromString(uuid));\n\n if (nation == null)\n return;\n\n nation.registerToLocal();\n }\n }\n\n //Warning: This can break data's managements !\n public static void updateDatabaseFromLocal(){\n if (!DatabaseManager.isOnline())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"DELETE FROM nations;\");\n pstmt.execute();\n\n for (String uuid : nationList){\n Nation nation = getFromLocal(UUID.fromString(uuid));\n\n if (nation == null)\n return;\n\n nation.registerToDatabase();\n }\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n //Deletes\n public void delFromNationList(){\n nationList.remove(this.Uuid.toString());\n }\n\n public void delFromLocal(){\n this.file.delete();\n }\n\n public void delFromDatabase(){\n if (co == null)\n return;\n\n if (!isExistIntoDatabase())\n return;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"DELETE FROM nations WHERE uuid = UUID(?);\");\n pstmt.setString(1, this.Uuid.toString());\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void del(){\n this.delFromDatabase();\n this.delFromLocal();\n this.delFromNationList();\n }\n\n public boolean isExistIntoLocal(){\n return new File(CivilisationPlot.getInstance().getDataFolder() + \"/Data/Nations/Nations/\" + this.Uuid).exists();\n }\n\n public boolean isExistIntoDatabase(){\n if (co == null)\n return false;\n\n try {\n PreparedStatement pstmt = co.prepareStatement(\"SELECT * FROM nations WHERE uuid = '\" + this.Uuid + \"';\");\n ResultSet result = pstmt.executeQuery();\n\n return result.next();\n\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public void save(){\n registerToDatabase();\n registerToLocal();\n registerToList();\n updateLocalListFromProgramList();\n }\n\n public static void load(){\n updateProgramListFromDatabase();\n updateLocalListFromProgramList();\n updateLocalFromDatabase();\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fr.laptoff.civilisationplot.CivilisationPlot; import fr.laptoff.civilisationplot.Managers.DatabaseManager; import fr.laptoff.civilisationplot.Managers.FileManager; import fr.laptoff.civilisationplot.nation.Nation; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID;
4,077
package fr.laptoff.civilisationplot.civils; public class Civil { private String PlayerName; private float Money; private UUID Nation;
package fr.laptoff.civilisationplot.civils; public class Civil { private String PlayerName; private float Money; private UUID Nation;
private static final Connection co = CivilisationPlot.getInstance().getDatabase().getConnection();
0
2023-11-11 18:26:55+00:00
8k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/modules/FullFlight.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(\"Rejects\", Items.BARRIER.getDefaultStack());\n public static final HudGroup HUD_GROUP = new HudGroup(\"Rejects\");\n\n @Override\n public void onInitialize() {\n LOG.info(\"Initializing Meteor Rejects Addon\");\n\n // Modules\n Modules modules = Modules.get();\n\n modules.add(new BetterAimbot());\n modules.add(new NewerNewChunks());\n modules.add(new BaseFinderNew());\n modules.add(new Shield());\n modules.add(new TestModule());\n modules.add(((new HitboxDesync())));\n modules.add(new Announcer());\n modules.add(new PacketLogger());\n modules.add(new ManualCrystal());\n modules.add(new TweakedAutoTool());\n modules.add(new MacroAnchorAuto());\n modules.add(new AutoMend());\n modules.add(new BowBomb());\n modules.add(new AutoCityPlus());\n modules.add(new PistonAura());\n modules.add(new CevBreaker());\n\n modules.add(new AimAssist());\n modules.add(new AntiBot());\n modules.add(new AntiCrash());\n modules.add(new AntiSpawnpoint());\n modules.add(new AntiVanish());\n modules.add(new ArrowDmg());\n modules.add(new AutoBedTrap());\n modules.add(new AutoCraft());\n modules.add(new AutoExtinguish());\n modules.add(new AutoFarm());\n modules.add(new AutoGrind());\n modules.add(new AutoLogin());\n modules.add(new AutoPot());\n modules.add(new AutoSoup());\n modules.add(new AutoTNT());\n modules.add(new AutoWither());\n modules.add(new BoatGlitch());\n modules.add(new BlockIn());\n modules.add(new BoatPhase());\n modules.add(new Boost());\n modules.add(new BungeeCordSpoof());\n modules.add(new ChatBot());\n modules.add(new ChestAura());\n modules.add(new ChorusExploit());\n modules.add(new ColorSigns());\n modules.add(new Confuse());\n modules.add(new CoordLogger());\n modules.add(new CustomPackets());\n modules.add(new ExtraElytra());\n modules.add(new FullFlight());\n modules.add(new GamemodeNotifier());\n modules.add(new GhostMode());\n modules.add(new Glide());\n modules.add(new InstaMine());\n modules.add(new ItemGenerator());\n modules.add(new InteractionMenu());\n modules.add(new Jetpack());\n modules.add(new KnockbackPlus());\n modules.add(new Lavacast());\n modules.add(new MossBot());\n modules.add(new NewChunks());\n modules.add(new NoJumpDelay());\n modules.add(new ObsidianFarm());\n modules.add(new OreSim());\n modules.add(new PacketFly());\n modules.add(new Painter());\n modules.add(new Rendering());\n modules.add(new RoboWalk());\n modules.add(new ShieldBypass());\n modules.add(new SilentDisconnect());\n modules.add(new SkeletonESP());\n modules.add(new SoundLocator());\n modules.add(new TreeAura());\n modules.add(new VehicleOneHit());\n\n // Commands\n Commands.add(new CenterCommand());\n Commands.add(new ClearChatCommand());\n Commands.add(new GhostCommand());\n Commands.add(new GiveCommand());\n Commands.add(new HeadsCommand());\n Commands.add(new KickCommand());\n Commands.add(new LocateCommand());\n Commands.add(new PanicCommand());\n Commands.add(new ReconnectCommand());\n Commands.add(new ServerCommand());\n Commands.add(new SaveSkinCommand());\n Commands.add(new SeedCommand());\n Commands.add(new SetBlockCommand());\n Commands.add(new SetVelocityCommand());\n Commands.add(new TeleportCommand());\n Commands.add(new TerrainExport());\n Commands.add(new EntityDesyncCommand());\n Commands.add(new BaseFinderNewCommands());\n Commands.add(new NewChunkCounter());\n\n // HUD\n Hud hud = Systems.get(Hud.class);\n hud.register(RadarHud.INFO);\n\n // Themes\n GuiThemes.add(new MeteorRoundedGuiTheme());\n }\n\n @Override\n public void onRegisterCategories() {\n Modules.registerCategory(CATEGORY);\n }\n\n @Override\n public String getWebsite() {\n return \"https://github.com/JohnTWD/meteor-rejects-vanillacpvp\";\n }\n\n @Override\n public GithubRepo getRepo() {\n return new GithubRepo(\"JohnTWD\", \"meteor-rejects-vanilla-cpvp\");\n }\n\n @Override\n public String getCommit() {\n String commit = FabricLoader\n .getInstance()\n .getModContainer(\"meteor-rejects\")\n .get().getMetadata()\n .getCustomValue(\"github:sha\")\n .getAsString();\n LOG.info(String.format(\"Rejects version: %s\", commit));\n return commit.isEmpty() ? null : commit.trim();\n }\n\n public String getPackage() {\n return \"anticope.rejects\";\n }\n}" }, { "identifier": "RejectsUtils", "path": "src/main/java/anticope/rejects/utils/RejectsUtils.java", "snippet": "public class RejectsUtils {\n @PostInit\n public static void init() {\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n System.out.println(\"saving seeds...\");\n RejectsConfig.get().save(MeteorClient.FOLDER);\n Seeds.get().save(MeteorClient.FOLDER);\n }));\n }\n\n public static String getModuleName(String name) {\n int dupe = 0;\n Modules modules = Modules.get();\n if (modules == null) {\n MeteorRejectsAddon.LOG.warn(\"Module instantiation before Modules initialized.\");\n return name;\n }\n for (Module module : modules.getAll()) {\n if (module.name.equals(name)) {\n dupe++;\n break;\n }\n }\n return dupe == 0 ? name : getModuleName(name + \"*\".repeat(dupe));\n }\n\n public static String getRandomPassword(int num) {\n String str = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\";\n Random random = new Random();\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < num; i++) {\n int number = random.nextInt(63);\n sb.append(str.charAt(number));\n }\n return sb.toString();\n }\n\n public static boolean inFov(Entity entity, double fov) {\n if (fov >= 360) return true;\n float[] angle = PlayerUtils.calculateAngle(entity.getBoundingBox().getCenter());\n double xDist = MathHelper.angleBetween(angle[0], mc.player.getYaw());\n double yDist = MathHelper.angleBetween(angle[1], mc.player.getPitch());\n double angleDistance = Math.hypot(xDist, yDist);\n return angleDistance <= fov;\n }\n\n public static float fullFlightMove(PlayerMoveEvent event, double speed, boolean verticalSpeedMatch) {\n if (PlayerUtils.isMoving()) {\n double dir = getDir();\n\n double xDir = Math.cos(Math.toRadians(dir + 90));\n double zDir = Math.sin(Math.toRadians(dir + 90));\n\n ((IVec3d) event.movement).setXZ(xDir * speed, zDir * speed);\n } else {\n ((IVec3d) event.movement).setXZ(0, 0);\n }\n\n float ySpeed = 0;\n\n if (mc.options.jumpKey.isPressed())\n ySpeed += speed;\n if (mc.options.sneakKey.isPressed())\n ySpeed -= speed;\n ((IVec3d) event.movement).setY(verticalSpeedMatch ? ySpeed : ySpeed / 2);\n\n return ySpeed;\n }\n\n private static double getDir() {\n double dir = 0;\n\n if (Utils.canUpdate()) {\n dir = mc.player.getYaw() + ((mc.player.forwardSpeed < 0) ? 180 : 0);\n\n if (mc.player.sidewaysSpeed > 0) {\n dir += -90F * ((mc.player.forwardSpeed < 0) ? -0.5F : ((mc.player.forwardSpeed > 0) ? 0.5F : 1F));\n } else if (mc.player.sidewaysSpeed < 0) {\n dir += 90F * ((mc.player.forwardSpeed < 0) ? -0.5F : ((mc.player.forwardSpeed > 0) ? 0.5F : 1F));\n }\n }\n return dir;\n }\n}" } ]
import anticope.rejects.MeteorRejectsAddon; import anticope.rejects.utils.RejectsUtils; import com.google.common.collect.Streams; import meteordevelopment.meteorclient.events.entity.player.PlayerMoveEvent; import meteordevelopment.meteorclient.events.packets.PacketEvent; import meteordevelopment.meteorclient.mixin.ClientPlayerEntityAccessor; import meteordevelopment.meteorclient.mixin.PlayerMoveC2SPacketAccessor; import meteordevelopment.meteorclient.settings.*; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.orbit.EventHandler; import net.minecraft.block.AbstractBlock; import net.minecraft.entity.Entity; import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket; import net.minecraft.util.math.Box; import net.minecraft.util.shape.VoxelShape; import java.util.stream.Stream;
3,746
// Copied from ServerPlayNetworkHandler#isEntityOnAir private boolean isEntityOnAir(Entity entity) { return entity.getWorld().getStatesInBox(entity.getBoundingBox().expand(0.0625).stretch(0.0, -0.55, 0.0)).allMatch(AbstractBlock.AbstractBlockState::isAir); } private int delayLeft = 20; private double lastPacketY = Double.MAX_VALUE; private boolean shouldFlyDown(double currentY, double lastY) { if (currentY >= lastY) { return true; } else return lastY - currentY < 0.03130D; } private void antiKickPacket(PlayerMoveC2SPacket packet, double currentY) { // maximum time we can be "floating" is 80 ticks, so 4 seconds max if (this.delayLeft <= 0 && this.lastPacketY != Double.MAX_VALUE && shouldFlyDown(currentY, this.lastPacketY) && isEntityOnAir(mc.player)) { // actual check is for >= -0.03125D, but we have to do a bit more than that // due to the fact that it's a bigger or *equal* to, and not just a bigger than ((PlayerMoveC2SPacketAccessor) packet).setY(lastPacketY - 0.03130D); lastPacketY -= 0.03130D; delayLeft = 20; } else { lastPacketY = currentY; if (!isEntityOnAir(mc.player)) delayLeft = 20; } if (delayLeft > 0) delayLeft--; } @EventHandler private void onSendPacket(PacketEvent.Send event) { if (mc.player.getVehicle() == null || !(event.packet instanceof PlayerMoveC2SPacket packet) || antiKickMode.get() != AntiKickMode.PaperNew) return; double currentY = packet.getY(Double.MAX_VALUE); if (currentY != Double.MAX_VALUE) { antiKickPacket(packet, currentY); } else { // if the packet is a LookAndOnGround packet or an OnGroundOnly packet then we need to // make it a Full packet or a PositionAndOnGround packet respectively, so it has a Y value PlayerMoveC2SPacket fullPacket; if (packet.changesLook()) { fullPacket = new PlayerMoveC2SPacket.Full( mc.player.getX(), mc.player.getY(), mc.player.getZ(), packet.getYaw(0), packet.getPitch(0), packet.isOnGround() ); } else { fullPacket = new PlayerMoveC2SPacket.PositionAndOnGround( mc.player.getX(), mc.player.getY(), mc.player.getZ(), packet.isOnGround() ); } event.cancel(); antiKickPacket(fullPacket, mc.player.getY()); mc.getNetworkHandler().sendPacket(fullPacket); } } private int floatingTicks = 0; @EventHandler private void onPlayerMove(PlayerMoveEvent event) { if (antiKickMode.get() == AntiKickMode.PaperNew) { // Resend movement packets ((ClientPlayerEntityAccessor) mc.player).setTicksSinceLastPositionPacketSent(20); } if (floatingTicks >= 20) { switch (antiKickMode.get()) { case New -> { Box box = mc.player.getBoundingBox(); Box adjustedBox = box.offset(0, -0.4, 0); Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox)); if (blockCollisions.findAny().isPresent()) break; mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY() - 0.4, mc.player.getZ(), mc.player.isOnGround())); mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround())); } case Old -> { Box box = mc.player.getBoundingBox(); Box adjustedBox = box.offset(0, -0.4, 0); Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox)); if (blockCollisions.findAny().isPresent()) break; double ground = calculateGround(); double groundExtra = ground + 0.1D; for (double posY = mc.player.getY(); posY > groundExtra; posY -= 4D) { mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), true)); if (posY - 4D < groundExtra) break; // Prevent next step } mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), groundExtra, mc.player.getZ(), true)); for (double posY = groundExtra; posY < mc.player.getY(); posY += 4D) { mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), mc.player.isOnGround())); if (posY + 4D > mc.player.getY()) break; // Prevent next step } mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround())); } } floatingTicks = 0; }
package anticope.rejects.modules; public class FullFlight extends Module { private final SettingGroup sgGeneral = settings.getDefaultGroup(); private final SettingGroup sgAntiKick = settings.createGroup("Anti Kick"); private final Setting<Double> speed = sgGeneral.add(new DoubleSetting.Builder() .name("speed") .description("Your speed when flying.") .defaultValue(0.3) .min(0.0) .sliderMax(10) .build() ); private final Setting<Boolean> verticalSpeedMatch = sgGeneral.add(new BoolSetting.Builder() .name("vertical-speed-match") .description("Matches your vertical speed to your horizontal speed, otherwise uses vanilla ratio.") .defaultValue(false) .build() ); private final Setting<AntiKickMode> antiKickMode = sgAntiKick.add(new EnumSetting.Builder<AntiKickMode>() .name("mode") .description("The mode for anti kick.") .defaultValue(AntiKickMode.PaperNew) .build() ); public FullFlight() { super(MeteorRejectsAddon.CATEGORY, "fullflight", "FullFlight."); } private double calculateGround() { for (double ground = mc.player.getY(); ground > 0D; ground -= 0.05) { Box box = mc.player.getBoundingBox(); Box adjustedBox = box.offset(0, ground - mc.player.getY(), 0); Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox)); if (blockCollisions.findAny().isPresent()) return ground + 0.05; } return 0F; } // Copied from ServerPlayNetworkHandler#isEntityOnAir private boolean isEntityOnAir(Entity entity) { return entity.getWorld().getStatesInBox(entity.getBoundingBox().expand(0.0625).stretch(0.0, -0.55, 0.0)).allMatch(AbstractBlock.AbstractBlockState::isAir); } private int delayLeft = 20; private double lastPacketY = Double.MAX_VALUE; private boolean shouldFlyDown(double currentY, double lastY) { if (currentY >= lastY) { return true; } else return lastY - currentY < 0.03130D; } private void antiKickPacket(PlayerMoveC2SPacket packet, double currentY) { // maximum time we can be "floating" is 80 ticks, so 4 seconds max if (this.delayLeft <= 0 && this.lastPacketY != Double.MAX_VALUE && shouldFlyDown(currentY, this.lastPacketY) && isEntityOnAir(mc.player)) { // actual check is for >= -0.03125D, but we have to do a bit more than that // due to the fact that it's a bigger or *equal* to, and not just a bigger than ((PlayerMoveC2SPacketAccessor) packet).setY(lastPacketY - 0.03130D); lastPacketY -= 0.03130D; delayLeft = 20; } else { lastPacketY = currentY; if (!isEntityOnAir(mc.player)) delayLeft = 20; } if (delayLeft > 0) delayLeft--; } @EventHandler private void onSendPacket(PacketEvent.Send event) { if (mc.player.getVehicle() == null || !(event.packet instanceof PlayerMoveC2SPacket packet) || antiKickMode.get() != AntiKickMode.PaperNew) return; double currentY = packet.getY(Double.MAX_VALUE); if (currentY != Double.MAX_VALUE) { antiKickPacket(packet, currentY); } else { // if the packet is a LookAndOnGround packet or an OnGroundOnly packet then we need to // make it a Full packet or a PositionAndOnGround packet respectively, so it has a Y value PlayerMoveC2SPacket fullPacket; if (packet.changesLook()) { fullPacket = new PlayerMoveC2SPacket.Full( mc.player.getX(), mc.player.getY(), mc.player.getZ(), packet.getYaw(0), packet.getPitch(0), packet.isOnGround() ); } else { fullPacket = new PlayerMoveC2SPacket.PositionAndOnGround( mc.player.getX(), mc.player.getY(), mc.player.getZ(), packet.isOnGround() ); } event.cancel(); antiKickPacket(fullPacket, mc.player.getY()); mc.getNetworkHandler().sendPacket(fullPacket); } } private int floatingTicks = 0; @EventHandler private void onPlayerMove(PlayerMoveEvent event) { if (antiKickMode.get() == AntiKickMode.PaperNew) { // Resend movement packets ((ClientPlayerEntityAccessor) mc.player).setTicksSinceLastPositionPacketSent(20); } if (floatingTicks >= 20) { switch (antiKickMode.get()) { case New -> { Box box = mc.player.getBoundingBox(); Box adjustedBox = box.offset(0, -0.4, 0); Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox)); if (blockCollisions.findAny().isPresent()) break; mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY() - 0.4, mc.player.getZ(), mc.player.isOnGround())); mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround())); } case Old -> { Box box = mc.player.getBoundingBox(); Box adjustedBox = box.offset(0, -0.4, 0); Stream<VoxelShape> blockCollisions = Streams.stream(mc.world.getBlockCollisions(mc.player, adjustedBox)); if (blockCollisions.findAny().isPresent()) break; double ground = calculateGround(); double groundExtra = ground + 0.1D; for (double posY = mc.player.getY(); posY > groundExtra; posY -= 4D) { mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), true)); if (posY - 4D < groundExtra) break; // Prevent next step } mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), groundExtra, mc.player.getZ(), true)); for (double posY = groundExtra; posY < mc.player.getY(); posY += 4D) { mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), posY, mc.player.getZ(), mc.player.isOnGround())); if (posY + 4D > mc.player.getY()) break; // Prevent next step } mc.getNetworkHandler().sendPacket(new PlayerMoveC2SPacket.PositionAndOnGround(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.isOnGround())); } } floatingTicks = 0; }
float ySpeed = RejectsUtils.fullFlightMove(event, speed.get(), verticalSpeedMatch.get());
1
2023-11-13 08:11:28+00:00
8k
stiemannkj1/java-utilities
src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java
[ { "identifier": "binarySearchArrayPrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(prefixes);\n}" }, { "identifier": "binarySearchArraySuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutableSuffixMapping<T> binarySearchArraySuffixMapping(\n final Map<String, T> suffixes) {\n return new BinarySearchArraySuffixMapping<>(suffixes);\n}" }, { "identifier": "limitedCharArrayTriePrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> limitedCharArrayTriePrefixMapping(\n final char min, final char max, final Map<String, T> prefixes) {\n return new LimitedCharArrayTriePrefixMapping<>(min, max, prefixes);\n}" }, { "identifier": "limitedCharArrayTrieSuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutableSuffixMapping<T> limitedCharArrayTrieSuffixMapping(\n final char min, final char max, final Map<String, T> suffixes) {\n return new LimitedCharArrayTrieSuffixMapping<>(min, max, suffixes);\n}" }, { "identifier": "ImmutablePrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public interface ImmutablePrefixMapping<T> extends ImmutablePrefixMatcher {\n\n @Override\n default boolean matchesAnyPrefix(final String string) {\n return keyAndValueForPrefix(string) != null;\n }\n\n default T valueForPrefix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForPrefix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForPrefix(final String string);\n}" }, { "identifier": "ImmutableSuffixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public interface ImmutableSuffixMapping<T> extends ImmutableSuffixMatcher {\n\n @Override\n default boolean matchesAnySuffix(final String string) {\n return keyAndValueForSuffix(string) != null;\n }\n\n default T valueForSuffix(final String string) {\n final Pair<String, T> keyAndValue = keyAndValueForSuffix(string);\n\n if (keyAndValue == null) {\n return null;\n }\n\n return keyAndValue.second;\n }\n\n Pair<String, T> keyAndValueForSuffix(final String string);\n}" }, { "identifier": "Pair", "path": "src/main/java/dev/stiemannkj1/util/Pair.java", "snippet": "public class Pair<T1, T2> implements Map.Entry<T1, T2> {\n public final T1 first;\n public final T2 second;\n\n private Pair(final T1 first, final T2 second) {\n this.first = first;\n this.second = second;\n }\n\n public T1 first() {\n return first;\n }\n\n public T2 second() {\n return second;\n }\n\n public T1 left() {\n return first;\n }\n\n public T2 right() {\n return second;\n }\n\n public T1 key() {\n return first;\n }\n\n public T2 value() {\n return second;\n }\n\n @Override\n public T1 getKey() {\n return first;\n }\n\n @Override\n public T2 getValue() {\n return second;\n }\n\n @Override\n public T2 setValue(final T2 value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean equals(final Object o) {\n\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n final Pair<?, ?> pair = (Pair<?, ?>) o;\n\n return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(first, second);\n }\n\n @Override\n public String toString() {\n return \"{\" + first + ',' + second + '}';\n }\n\n public static <T1, T2> Pair<T1, T2> of(final T1 first, final T2 second) {\n return new Pair<>(first, second);\n }\n\n public static <K, V> Pair<K, V> fromEntry(final Map.Entry<K, V> entry) {\n return new Pair<>(entry.getKey(), entry.getValue());\n }\n\n public static final class NameValue<V> extends Pair<String, V> {\n private NameValue(final String name, final V value) {\n super(name, value);\n }\n\n public String name() {\n return first;\n }\n }\n\n public static <V> NameValue<V> nameValuePair(final String name, final V value) {\n return new NameValue<>(name, value);\n }\n}" } ]
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; 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.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping; import dev.stiemannkj1.util.Pair; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource;
3,902
return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidSuffixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> suffixes) { final Class<? extends Exception> expectedExceptionType = suffixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes)); } ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes); } private static void assertFirstMatchSearchTakesLessSteps( String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) { final AtomicLong firstSearchSteps = new AtomicLong(0); final AtomicLong longestSearchSteps = new AtomicLong(0); final Pair<String, Integer> firstMatch = fixMapping.getKeyAndValue(false, string, firstSearchSteps); if (expectedValue != null) { assertNotNull(firstMatch); } else { assertNull(firstMatch); } final Pair<String, Integer> longestMatch = fixMapping.getKeyAndValue(true, string, longestSearchSteps); if (expectedValue != null) { assertNotNull(longestMatch); } else { assertNull(longestMatch); } assertTrue(firstSearchSteps.get() <= longestSearchSteps.get()); } static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests { @Override public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) { return binarySearchArrayPrefixMapping(prefixes); } @CsvSource( value = { "abdicate,abd,abdicate,3,11,8,8", "abdicated,abd,abdicate,3,14,8,11", }) @ParameterizedTest @Override public void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { PrefixMappersTests.super.detects_prefixes_with_minimal_steps( string, firstMatchEvenKeys, firstMatchOddKeys, firstMatchStepsEvenKeys, longestMatchStepsEvenKeys, firstMatchStepsOddKeys, longestMatchStepsOddKeys); } } static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests { @Override public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) { return binarySearchArraySuffixMapping(suffixes); } @CsvSource( value = { "abdicate,abdicate,ate,8,8,5,13", "i abdicate,abdicate,ate,8,10,5,13", }) @ParameterizedTest @Override public void detects_suffixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { SuffixMappersTests.super.detects_suffixes_with_minimal_steps( string, firstMatchEvenKeys, firstMatchOddKeys, firstMatchStepsEvenKeys, longestMatchStepsEvenKeys, firstMatchStepsOddKeys, longestMatchStepsOddKeys); } } static final class LimitedCharArrayTriePrefixMapTests implements PrefixMappersTests { @Override public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) {
/* Copyright 2023 Kyle J. Stiemann 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 dev.stiemannkj1.collection.fixmapping; final class FixMappingsTests { // TODO test unicode interface PrefixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "abe,true,1", "abd,true,2", "aba,false,null", "abd,true,2", "abdi,true,2", "abdic,true,2", "abdica,true,2", "abdicat,true,2", "abdicat,true,2", "abdicate,true,3", "abdicated,true,3", "x,false,null", "xy,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_prefixes( final String string, final boolean expectPrefixed, final Integer expectedValue) { // Test odd number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); // Test odd number of prefixes. prefixes.put("xyz", 4); prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); } @SuppressWarnings("unchecked") default void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get()); // Test odd number of prefixes. prefixes.put("aaa", 4); prefixMap = newPrefixMap(prefixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_prefixes_with_matching_suffixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newPrefixMap(suffixes)); } static Stream<Map<String, Integer>> invalidPrefixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidPrefixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> prefixes) { final Class<? extends Exception> expectedExceptionType = prefixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes)); } ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes); } interface SuffixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "1abc,true,0", "abe,true,1", "abed,false,null", "abd,false,null", "aba,false,null", "at,false,null", "ate,true,2", "cate,true,2", "icate,true,2", "dicate,true,2", "bdicate,true,2", "abdicate,true,3", "i abdicate,true,3", "abdicated,false,null", "z,false,null", "yz,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_suffixes( final String string, final boolean expectSuffixed, final Integer expectedValue) { // Test even number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map; ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes); assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string)); assertEquals(expectedValue, suffixMap.valueForSuffix(string)); assertEquals( getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap); // Test odd number of suffixes. suffixes.put("xyz", 4); suffixMap = newSuffixMap(suffixes); assertEquals(expectSuffixed, suffixMap.matchesAnySuffix(string)); assertEquals(expectedValue, suffixMap.valueForSuffix(string)); assertEquals( getKeyAndValueByValue(suffixes, expectedValue), suffixMap.keyAndValueForSuffix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) suffixMap); } @SuppressWarnings("unchecked") default void detects_suffixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map; ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchEvenKeys, suffixes.get(firstMatchEvenKeys)), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get()); // Test odd number of suffixes. suffixes.put("aaa", 4); suffixMap = newSuffixMap(suffixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, suffixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) suffixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_suffixes_with_matching_prefixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abdicat", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newSuffixMap(suffixes)); } static Stream<Map<String, Integer>> invalidSuffixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidSuffixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> suffixes) { final Class<? extends Exception> expectedExceptionType = suffixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newSuffixMap(suffixes)); } ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> prefixes); } private static void assertFirstMatchSearchTakesLessSteps( String string, Integer expectedValue, FixMappings.FixMapping<Integer> fixMapping) { final AtomicLong firstSearchSteps = new AtomicLong(0); final AtomicLong longestSearchSteps = new AtomicLong(0); final Pair<String, Integer> firstMatch = fixMapping.getKeyAndValue(false, string, firstSearchSteps); if (expectedValue != null) { assertNotNull(firstMatch); } else { assertNull(firstMatch); } final Pair<String, Integer> longestMatch = fixMapping.getKeyAndValue(true, string, longestSearchSteps); if (expectedValue != null) { assertNotNull(longestMatch); } else { assertNull(longestMatch); } assertTrue(firstSearchSteps.get() <= longestSearchSteps.get()); } static final class BinarySearchArrayPrefixMapTests implements PrefixMappersTests { @Override public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) { return binarySearchArrayPrefixMapping(prefixes); } @CsvSource( value = { "abdicate,abd,abdicate,3,11,8,8", "abdicated,abd,abdicate,3,14,8,11", }) @ParameterizedTest @Override public void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { PrefixMappersTests.super.detects_prefixes_with_minimal_steps( string, firstMatchEvenKeys, firstMatchOddKeys, firstMatchStepsEvenKeys, longestMatchStepsEvenKeys, firstMatchStepsOddKeys, longestMatchStepsOddKeys); } } static final class BinarySearchArraySuffixMapTests implements SuffixMappersTests { @Override public ImmutableSuffixMapping<Integer> newSuffixMap(final Map<String, Integer> suffixes) { return binarySearchArraySuffixMapping(suffixes); } @CsvSource( value = { "abdicate,abdicate,ate,8,8,5,13", "i abdicate,abdicate,ate,8,10,5,13", }) @ParameterizedTest @Override public void detects_suffixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { SuffixMappersTests.super.detects_suffixes_with_minimal_steps( string, firstMatchEvenKeys, firstMatchOddKeys, firstMatchStepsEvenKeys, longestMatchStepsEvenKeys, firstMatchStepsOddKeys, longestMatchStepsOddKeys); } } static final class LimitedCharArrayTriePrefixMapTests implements PrefixMappersTests { @Override public ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes) {
return limitedCharArrayTriePrefixMapping('a', 'z', prefixes);
2
2023-11-12 05:05:22+00:00
8k
slow3586/HypersomniaMapGen
src/main/java/com/slow3586/Main.java
[ { "identifier": "RoomStyle", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class RoomStyle {\n int height;\n Color floorColor;\n Color wallColor;\n int patternIdFloor;\n int patternIdWall;\n Color patternColorFloor;\n Color patternColorWall;\n}" }, { "identifier": "ExternalResource", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Builder\n@Value\npublic static class ExternalResource {\n public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";\n String path;\n @Builder.Default\n String file_hash = \"03364891a7e8a89057d550d2816c8756c98e951524c4a14fa7e00981e0a46a62\";\n String id;\n String domain;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n int[] color = WHITE.intArray();\n AsPhysical as_physical;\n AsNonPhysical as_nonphysical;\n boolean stretch_when_resized;\n\n static final String DOMAIN_PHYSICAL = \"PHYSICAL\";\n static final String DOMAIN_FOREGROUND = \"FOREGROUND\";\n static final String RESOURCE_ID_PREFIX = \"@\";\n static final String PNG_EXT = \".png\";\n static final String MAP_GFX_PATH = \"gfx/\";\n static final String RESOURCE_WALL_ID = \"style_wall\";\n static final String RESOURCE_FLOOR_ID = \"style_floor\";\n static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";\n static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";\n static final String CRATE_BLOCKING = \"crate_blocking\";\n static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";\n static final String SHADOW_WALL_LINE = \"shadow_wall_line\";\n static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";\n static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";\n static final String LINE_FLOOR = \"line_floor\";\n static final String LINE_WALL = \"line_wall\";\n static final String WANDERING_PIXELS = \"wandering_pixels\";\n static final String POINT_LIGHT = \"point_light\";\n}" }, { "identifier": "WHITE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static Color WHITE = new Color(255, 255, 255, 255);" }, { "identifier": "Layer", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class Layer {\n String id;\n List<String> nodes;\n}" }, { "identifier": "Node", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\n@Builder\npublic static class Node {\n @Builder.Default\n String id = String.valueOf(Map.nodeIndex.getAndIncrement());\n String type;\n float[] pos;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n Float rotation = 0.0f;\n String faction;\n String letter;\n Float positional_vibration;\n Float intensity_vibration;\n Falloff falloff;\n int[] color;\n int num_particles;\n\n static final String FACTION_RESISTANCE = \"RESISTANCE\";\n static final String TYPE_BOMBSITE = \"bombsite\";\n static final String LETTER_A = \"A\";\n static final String TYPE_BUY_ZONE = \"buy_zone\";\n static final String FACTION_METROPOLIS = \"METROPOLIS\";\n static final String TYPE_TEAM_SPAWN = \"team_spawn\";\n static final String LETTER_B = \"B\";\n\n @Value\n public static class Falloff {\n float radius;\n int strength;\n }\n\n @Builder\n @Value\n public static class ExternalResource {\n public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";\n String path;\n @Builder.Default\n String file_hash = \"03364891a7e8a89057d550d2816c8756c98e951524c4a14fa7e00981e0a46a62\";\n String id;\n String domain;\n @Builder.Default\n float[] size = TILE_SIZE.floatArray();\n @Builder.Default\n int[] color = WHITE.intArray();\n AsPhysical as_physical;\n AsNonPhysical as_nonphysical;\n boolean stretch_when_resized;\n\n static final String DOMAIN_PHYSICAL = \"PHYSICAL\";\n static final String DOMAIN_FOREGROUND = \"FOREGROUND\";\n static final String RESOURCE_ID_PREFIX = \"@\";\n static final String PNG_EXT = \".png\";\n static final String MAP_GFX_PATH = \"gfx/\";\n static final String RESOURCE_WALL_ID = \"style_wall\";\n static final String RESOURCE_FLOOR_ID = \"style_floor\";\n static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";\n static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";\n static final String CRATE_BLOCKING = \"crate_blocking\";\n static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";\n static final String SHADOW_WALL_LINE = \"shadow_wall_line\";\n static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";\n static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";\n static final String LINE_FLOOR = \"line_floor\";\n static final String LINE_WALL = \"line_wall\";\n static final String WANDERING_PIXELS = \"wandering_pixels\";\n static final String POINT_LIGHT = \"point_light\";\n }\n\n @Value\n @Builder\n public static class AsPhysical {\n // lombok \"'is' getter\" fix\n @JsonProperty(\"is_static\")\n @Getter(AccessLevel.NONE)\n boolean is_static;\n @JsonProperty(\"is_see_through\")\n @Getter(AccessLevel.NONE)\n boolean is_see_through;\n @JsonProperty(\"is_throw_through\")\n @Getter(AccessLevel.NONE)\n boolean is_throw_through;\n @JsonProperty(\"is_melee_throw_through\")\n @Getter(AccessLevel.NONE)\n boolean is_melee_throw_through;\n @JsonProperty(\"is_shoot_through\")\n @Getter(AccessLevel.NONE)\n boolean is_shoot_through;\n Float density; // 0.7\n Float friction; // 0.0\n Float bounciness; // 0.2\n Float penetrability; // 1\n Float collision_sound_sensitivity; // 1\n Float linear_damping; // 6.5\n Float angular_damping; // 6.5\n CustomShape custom_shape;\n\n static final AsPhysical AS_PHYSICAL_DEFAULT = AsPhysical.builder()\n .is_static(true)\n .build();\n\n @Value\n public static class CustomShape {\n float[][] source_polygon;\n\n public CustomShape mul(float mul) {\n float[][] result = new float[4][2];\n for (int y = 0; y < 4; y++) {\n for (int x = 0; x < 2; x++) {\n result[y][x] = CRATE_SHAPE.source_polygon[y][x] * mul;\n }\n }\n return new CustomShape(result);\n }\n\n static final CustomShape CRATE_SHAPE = new CustomShape(\n new float[][]{\n new float[]{-32.0f, -32.0f},\n new float[]{32.0f, -32.0f},\n new float[]{32.0f, 32.0f},\n new float[]{-32.0f, 32.0f},\n });\n }\n }\n\n @Value\n public static class AsNonPhysical {\n boolean full_illumination;\n\n static final AsNonPhysical AS_NON_PHYSICAL_DEFAULT = new AsNonPhysical(true);\n }\n}" }, { "identifier": "AS_NON_PHYSICAL_DEFAULT", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final AsNonPhysical AS_NON_PHYSICAL_DEFAULT = new AsNonPhysical(true);" }, { "identifier": "AS_PHYSICAL_DEFAULT", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final AsPhysical AS_PHYSICAL_DEFAULT = AsPhysical.builder()\n .is_static(true)\n .build();" }, { "identifier": "BASE_PNG_TEXTURE_FILENAME", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static final String BASE_PNG_TEXTURE_FILENAME = \"base\";" }, { "identifier": "CRATE_BLOCKING", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String CRATE_BLOCKING = \"crate_blocking\";" }, { "identifier": "CRATE_NON_BLOCKING", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String CRATE_NON_BLOCKING = \"crate_non_blocking\";" }, { "identifier": "DOMAIN_FOREGROUND", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String DOMAIN_FOREGROUND = \"FOREGROUND\";" }, { "identifier": "DOMAIN_PHYSICAL", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String DOMAIN_PHYSICAL = \"PHYSICAL\";" }, { "identifier": "LINE_FLOOR", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String LINE_FLOOR = \"line_floor\";" }, { "identifier": "LINE_WALL", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String LINE_WALL = \"line_wall\";" }, { "identifier": "MAP_GFX_PATH", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String MAP_GFX_PATH = \"gfx/\";" }, { "identifier": "PNG_EXT", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String PNG_EXT = \".png\";" }, { "identifier": "RESOURCE_FLOOR_ID", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String RESOURCE_FLOOR_ID = \"style_floor\";" }, { "identifier": "RESOURCE_ID_PREFIX", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String RESOURCE_ID_PREFIX = \"@\";" }, { "identifier": "RESOURCE_WALL_ID", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String RESOURCE_WALL_ID = \"style_wall\";" }, { "identifier": "ROOM_NOISE_CIRCLE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String ROOM_NOISE_CIRCLE = \"room_noise_circle\";" }, { "identifier": "SHADOW_FLOOR_CORNER", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_FLOOR_CORNER = \"shadow_floor_corner\";" }, { "identifier": "SHADOW_FLOOR_LINE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_FLOOR_LINE = \"shadow_floor_line\";" }, { "identifier": "SHADOW_WALL_CORNER", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_WALL_CORNER = \"shadow_wall_corner\";" }, { "identifier": "SHADOW_WALL_LINE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "static final String SHADOW_WALL_LINE = \"shadow_wall_line\";" }, { "identifier": "Playtesting", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class Playtesting {\n static final String QUICK_TEST = \"quick_test\";\n String mode;\n}" }, { "identifier": "CRATE_SIZE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static Size CRATE_SIZE = new Size(104, 104);" }, { "identifier": "TILE_SIZE", "path": "src/main/java/com/slow3586/Main.java", "snippet": "public static Size TILE_SIZE = new Size(128, 128);" } ]
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.slow3586.Main.Room.RoomStyle; import com.slow3586.Main.Settings.Node.ExternalResource; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.ToString; import lombok.Value; import org.jooq.lambda.Sneaky; import org.jooq.lambda.function.Consumer1; import org.jooq.lambda.function.Consumer2; import org.jooq.lambda.function.Consumer4; import org.jooq.lambda.function.Function1; import org.jooq.lambda.function.Function3; import java.awt.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.StringJoiner; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; import static com.slow3586.Main.Color.WHITE; import static com.slow3586.Main.MapTile.TileType.DOOR; import static com.slow3586.Main.MapTile.TileType.WALL; import static com.slow3586.Main.Settings.Layer; import static com.slow3586.Main.Settings.Node; import static com.slow3586.Main.Settings.Node.AsNonPhysical.AS_NON_PHYSICAL_DEFAULT; import static com.slow3586.Main.Settings.Node.AsPhysical.AS_PHYSICAL_DEFAULT; import static com.slow3586.Main.Settings.Node.ExternalResource.BASE_PNG_TEXTURE_FILENAME; import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_BLOCKING; import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_NON_BLOCKING; import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_FOREGROUND; import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_PHYSICAL; import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_FLOOR; import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_WALL; import static com.slow3586.Main.Settings.Node.ExternalResource.MAP_GFX_PATH; import static com.slow3586.Main.Settings.Node.ExternalResource.PNG_EXT; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_FLOOR_ID; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_ID_PREFIX; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_WALL_ID; import static com.slow3586.Main.Settings.Node.ExternalResource.ROOM_NOISE_CIRCLE; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_CORNER; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_LINE; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_CORNER; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_LINE; import static com.slow3586.Main.Settings.Playtesting; import static com.slow3586.Main.Size.CRATE_SIZE; import static com.slow3586.Main.Size.TILE_SIZE;
5,989
+ (isBlocking ? "" : "non") + "blocking"; //endregion //region RESOURCES: ROOMS mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT) .id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE) .stretch_when_resized(true) .domain(DOMAIN_FOREGROUND) .color(new Color(255, 255, 255, 150).intArray()) .build()); createTextureSameName.accept(ROOM_NOISE_CIRCLE); //endregion //region RESOURCES: STYLES IntStream.range(0, styles.length) .boxed() .forEach((final Integer roomStyleIndex) -> { final RoomStyle style = styles[roomStyleIndex]; final String floorId = RESOURCE_FLOOR_ID + roomStyleIndex; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + floorId + PNG_EXT) .id(RESOURCE_ID_PREFIX + floorId) .color(style.floorColor.intArray()) .build()); createTexture.accept(BASE_PNG_TEXTURE_FILENAME, floorId); final String wallId = RESOURCE_WALL_ID + roomStyleIndex; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + wallId + PNG_EXT) .id(RESOURCE_ID_PREFIX + wallId) .domain(DOMAIN_PHYSICAL) .color(style.wallColor.intArray()) .as_physical(AS_PHYSICAL_DEFAULT) .build()); createTexture.accept(BASE_PNG_TEXTURE_FILENAME, wallId); final String patternWallTarget = "style" + roomStyleIndex + "_pattern_wall"; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + patternWallTarget + PNG_EXT) .id(RESOURCE_ID_PREFIX + patternWallTarget) .domain(DOMAIN_FOREGROUND) .color(style.patternColorWall.intArray()) .build()); createTexture.accept("pattern" + style.patternIdWall, patternWallTarget); final String patternFloorTarget = "style" + roomStyleIndex + "_pattern_floor"; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + patternFloorTarget + PNG_EXT) .id(RESOURCE_ID_PREFIX + patternFloorTarget) .color(style.patternColorFloor.intArray()) .build()); createTexture.accept("pattern" + style.patternIdFloor, patternFloorTarget); final BiConsumer<Integer, Boolean> createCrate = ( final Integer crateStyleIndex, final Boolean isBlocking ) -> { final String crateName = getCrateName.apply( roomStyleIndex, crateStyleIndex, isBlocking); final float sizeMultiplier = config.crateMinMaxSizeMultiplier.randomize(); mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + crateName + PNG_EXT) .id(RESOURCE_ID_PREFIX + crateName) .domain(DOMAIN_PHYSICAL) .stretch_when_resized(true) .size(CRATE_SIZE .mul(sizeMultiplier) .floatArray()) .color((isBlocking ? config.crateBlockingMinMaxTint : config.crateNonBlockingMinMaxTint) .randomize() .intArray() ).as_physical(Node.AsPhysical.builder() .custom_shape(Node.AsPhysical.CustomShape .CRATE_SHAPE .mul(sizeMultiplier)) .is_see_through(!isBlocking) .is_shoot_through(!isBlocking) .is_melee_throw_through(!isBlocking) .is_throw_through(!isBlocking) .density(nextFloat(0.6f, 1.3f)) .friction(nextFloat(0.0f, 0.5f)) .bounciness(nextFloat(0.1f, 0.6f)) .penetrability(nextFloat(0.0f, 1.0f)) .angular_damping(nextFloat(10f, 100f)) .build()) .build()); createTexture.accept(isBlocking ? CRATE_BLOCKING : CRATE_NON_BLOCKING, crateName); }; IntStream.range(0, config.cratesBlockingPerStyle) .forEach(crateIndex -> createCrate.accept(crateIndex, true)); IntStream.range(0, config.cratesNonBlockingPerStyle) .forEach(crateIndex -> createCrate.accept(crateIndex, false)); }); //endregion //region RESOURCES: SHADOWS mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + SHADOW_WALL_CORNER + PNG_EXT) .id(RESOURCE_ID_PREFIX + SHADOW_WALL_CORNER) .domain(DOMAIN_FOREGROUND) .color(config.shadowTintWall.intArray()) .as_nonphysical(AS_NON_PHYSICAL_DEFAULT) .build()); createTextureSameName.accept(SHADOW_WALL_CORNER); mapJson.external_resources.add( ExternalResource.builder()
package com.slow3586; public class Main { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static Random baseRandom; static Configuration config; static { OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); } public static void main(String[] args) throws IOException { //region CONFIGURATION final String configStr = Files.readString(Path.of("config.json")); config = OBJECT_MAPPER.readValue(configStr, Configuration.class); baseRandom = new Random(config.randomSeed); final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName); //endregion //region GENERATION: ROOMS //region RANDOMIZE DIAGONAL ROOM SIZES final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize()) .limit(Math.max(config.roomsCount.x, config.roomsCount.y)) .toArray(Size[]::new); //endregion //region RANDOMIZE ROOM STYLES final RoomStyle[] styles = IntStream.range(0, config.styleCount) .boxed() .map(styleIndex -> new RoomStyle( config.styleHeightOverride.length > styleIndex ? config.styleHeightOverride[styleIndex] : styleIndex, config.floorMinMaxTintBase .randomize() .add(config.floorTintPerHeight.mul(styleIndex)), config.wallMinMaxTintBase .randomize() .add(config.wallTintPerHeight.mul(styleIndex)), nextInt(1, config.patternResourceCount), nextInt(1, config.patternResourceCount), config.patternMinMaxTintFloor.randomize(), config.patternMinMaxTintWall.randomize()) ).toArray(RoomStyle[]::new); //endregion final Room[][] rooms = new Room[config.roomsCount.y][config.roomsCount.x]; pointsRect(0, 0, config.roomsCount.x, config.roomsCount.y) .forEach(roomIndex -> { final boolean disableRoom = Arrays.asList(config.roomsDisabled).contains(roomIndex); final boolean disableDoorRight = Arrays.asList(config.roomsDoorRightDisabled).contains(roomIndex) || (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.RIGHT))); final boolean disableDoorDown = Arrays.asList(config.roomsDoorDownDisabled).contains(roomIndex) || (disableRoom && Arrays.asList(config.roomsDisabled).contains(roomIndex.add(Point.DOWN))); //region CALCULATE ABSOLUTE ROOM POSITION final Point roomPosAbs = new Point( Arrays.stream(diagonalRoomSizes) .limit(roomIndex.x) .map(Size::getW) .reduce(0, Integer::sum), Arrays.stream(diagonalRoomSizes) .limit(roomIndex.y) .map(Size::getH) .reduce(0, Integer::sum)); //endregion //region RANDOMIZE WALL final Size wallSize = config.wallMinMaxSize.randomize(); final Point wallOffset = new Point( -nextInt(0, Math.min(wallSize.w, config.wallMaxOffset.x)), -nextInt(0, Math.min(wallSize.h, config.wallMaxOffset.y))); //endregion //region RANDOMIZE DOOR final Size roomFloorSpace = new Size( diagonalRoomSizes[roomIndex.x].w + wallOffset.y, diagonalRoomSizes[roomIndex.y].h + wallOffset.x); final boolean needVerticalDoor = !disableDoorRight && roomIndex.x > 0 && roomIndex.x < rooms[0].length - 1; final boolean needHorizontalDoor = !disableDoorDown && roomIndex.y > 0 && roomIndex.y < rooms.length - 1; final Size doorSize = new Size( needHorizontalDoor ? Math.min(config.doorMinMaxWidth.randomizeWidth(), roomFloorSpace.w - 1) : 0, needVerticalDoor ? Math.min(config.doorMinMaxWidth.randomizeHeight(), roomFloorSpace.h - 1) : 0); final Point doorOffset = new Point( needHorizontalDoor ? nextInt(1, roomFloorSpace.w - doorSize.w + 1) : 0, needVerticalDoor ? nextInt(1, roomFloorSpace.h - doorSize.h + 1) : 0); //endregion //region RANDOMIZE STYLE final int styleIndex = nextInt(0, config.styleCount); final Size styleSize = new Size( roomIndex.x == config.roomsCount.x - 1 ? 1 : config.styleSizeMinMaxSize.randomizeWidth(), roomIndex.y == config.roomsCount.y - 1 ? 1 : config.styleSizeMinMaxSize.randomizeHeight()); //endregion //region PUT ROOM INTO ROOMS ARRAY rooms[roomIndex.y][roomIndex.x] = new Room( roomPosAbs, new Size( diagonalRoomSizes[roomIndex.x].w, diagonalRoomSizes[roomIndex.y].h), new Room.Rect( wallOffset.x, wallSize.w), new Room.Rect( wallOffset.y, wallSize.h), new Room.Rect( doorOffset.x, doorSize.w), new Room.Rect( doorOffset.y, doorSize.h), styleIndex, styleSize, disableRoom); //endregion }); //endregion //region GENERATION: BASE MAP TILE ARRAY final MapTile[][] mapTilesUncropped = pointsRectRows( Arrays.stream(diagonalRoomSizes) .mapToInt(r -> r.w + Math.max(config.styleSizeMinMaxSize.max.w, config.wallMaxOffset.x)) .sum() + 1, Arrays.stream(diagonalRoomSizes) .mapToInt(r -> r.h + Math.max(config.styleSizeMinMaxSize.max.h, config.wallMaxOffset.y)) .sum() + 1) .stream() .map(row -> row.stream() .map(point -> new MapTile( MapTile.TileType.FLOOR, null, false, false, null)) .toArray(MapTile[]::new) ).toArray(MapTile[][]::new); //endregion //region GENERATION: RENDER BASE ROOMS ONTO BASE MAP TILE ARRAY pointsRectArray(rooms) .forEach(roomIndex -> { final Room room = rooms[roomIndex.y][roomIndex.x]; //region FILL MAP TILES //region WALL HORIZONTAL pointsRect( room.roomPosAbs.x, room.roomPosAbs.y + room.roomSize.h + room.wallHoriz.offset, room.roomSize.w, room.wallHoriz.width ).forEach(pointAbs -> { final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR) || (pointAbs.x >= room.roomPosAbs.x + room.doorHoriz.offset && pointAbs.x < room.roomPosAbs.x + room.doorHoriz.offset + room.doorHoriz.width); mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile; mapTilesUncropped[pointAbs.y][pointAbs.x].tileType = isDoorTile ? MapTile.TileType.DOOR : WALL; }); //endregion //region WALL VERTICAL pointsRect( room.roomPosAbs.x + room.roomSize.w + room.wallVert.offset, room.roomPosAbs.y, room.wallVert.width, room.roomSize.h ).forEach(pointAbs -> { final boolean isDoorTile = (mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == MapTile.TileType.DOOR) || (pointAbs.y >= room.roomPosAbs.y + room.doorVert.offset && pointAbs.y < room.roomPosAbs.y + room.doorVert.offset + room.doorVert.width); mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile; mapTilesUncropped[pointAbs.y][pointAbs.x].tileType = isDoorTile ? MapTile.TileType.DOOR : WALL; }); //endregion //region DISABLE FLOOR if (room.isDisabled()) { pointsRect( room.roomPosAbs.x, room.roomPosAbs.y, room.roomSize.w + room.wallVert.offset, room.roomSize.h + room.wallHoriz.offset ).forEach(pointAbs -> { final boolean isDoorTile = mapTilesUncropped[pointAbs.y][pointAbs.x].tileType == DOOR; mapTilesUncropped[pointAbs.y][pointAbs.x].disabled = !isDoorTile; mapTilesUncropped[pointAbs.y][pointAbs.x].tileType = isDoorTile ? MapTile.TileType.DOOR : WALL; }); } //endregion //region CARCASS HORIZONTAL pointsRect( room.roomPosAbs.x, room.roomPosAbs.y + room.roomSize.h, room.roomSize.w, 1 ).forEach(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true); //endregion //region CARCASS VERTICAL pointsRect( room.roomPosAbs.x + room.roomSize.w, room.roomPosAbs.y, 1, room.roomSize.h ).forEach(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x].carcass = true); //endregion //region TILE ROOM TYPE pointsRect( room.roomPosAbs.x, room.roomPosAbs.y, room.roomSize.w + room.styleSize.w, room.roomSize.h + room.styleSize.h ).stream() .map(pointAbs -> mapTilesUncropped[pointAbs.y][pointAbs.x]) .forEach(tile -> { if (tile.styleIndex == null) { tile.styleIndex = room.styleIndex; } tile.height = styles[room.styleIndex].height + (tile.tileType == WALL ? config.wallHeight : 0); }); //endregion //endregion }); //endregion //region GENERATION: CROP MAP final MapTile[][] mapTilesCrop; if (config.cropMap) { final Size croppedMapSize = new Size( Arrays.stream(diagonalRoomSizes) .limit(rooms[0].length) .map(s -> s.w) .reduce(0, Integer::sum) - diagonalRoomSizes[0].w + 1, Arrays.stream(diagonalRoomSizes) .limit(rooms.length) .map(s -> s.h) .reduce(0, Integer::sum) - diagonalRoomSizes[0].h + 1); final MapTile[][] temp = new MapTile[croppedMapSize.h][croppedMapSize.w]; for (int y = 0; y < croppedMapSize.h; y++) { temp[y] = Arrays.copyOfRange( mapTilesUncropped[y + diagonalRoomSizes[0].h], diagonalRoomSizes[0].w, diagonalRoomSizes[0].w + croppedMapSize.w); } mapTilesCrop = temp; } else { mapTilesCrop = mapTilesUncropped; } //endregion //region GENERATION: FIX MOST DOWN RIGHT TILE mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 1] = mapTilesCrop[mapTilesCrop.length - 1][mapTilesCrop[0].length - 2]; //endregion //region GENERATION: FIX DIAGONAL WALLS TOUCH WITH EMPTY SIDES // #_ _# // _# OR #_ final Function1<MapTile, Boolean> isWall = (s) -> s.tileType == MapTile.TileType.WALL; for (int iter = 0; iter < 2; iter++) { for (int y = 1; y < mapTilesCrop.length - 1; y++) { for (int x = 1; x < mapTilesCrop[y].length - 1; x++) { final boolean wall = isWall.apply(mapTilesCrop[y][x]); final boolean wallR = isWall.apply(mapTilesCrop[y][x + 1]); final boolean wallD = isWall.apply(mapTilesCrop[y + 1][x]); final boolean wallRD = isWall.apply(mapTilesCrop[y + 1][x + 1]); if ((wall && wallRD && !wallR && !wallD) || (!wall && !wallRD && wallR && wallD) ) { if (wall) mapTilesCrop[y][x].height -= config.wallHeight; mapTilesCrop[y][x].tileType = MapTile.TileType.FLOOR; if (wallR) mapTilesCrop[y][x + 1].height -= config.wallHeight; mapTilesCrop[y][x + 1].tileType = MapTile.TileType.FLOOR; if (wallD) mapTilesCrop[y + 1][x].height -= config.wallHeight; mapTilesCrop[y + 1][x].tileType = MapTile.TileType.FLOOR; if (wallRD) mapTilesCrop[y + 1][x + 1].height -= config.wallHeight; mapTilesCrop[y + 1][x + 1].tileType = MapTile.TileType.FLOOR; } } } } //endregion //region OUTPUT: PRINT MAP TO TEXT FILE final StringJoiner wallJoiner = new StringJoiner("\n"); wallJoiner.add("Walls:"); final StringJoiner heightJoiner = new StringJoiner("\n"); heightJoiner.add("Heights:"); final StringJoiner styleIndexJoiner = new StringJoiner("\n"); styleIndexJoiner.add("Styles:"); final StringJoiner carcassJoiner = new StringJoiner("\n"); carcassJoiner.add("Carcass:"); pointsRectArrayByRow(mapTilesCrop) .forEach(row -> { final StringBuilder wallJoinerRow = new StringBuilder(); final StringBuilder heightJoinerRow = new StringBuilder(); final StringBuilder styleIndexJoinerRow = new StringBuilder(); final StringBuilder carcassJoinerRow = new StringBuilder(); row.forEach(point -> { final MapTile mapTile = mapTilesCrop[point.y][point.x]; wallJoinerRow.append( mapTile.tileType == WALL ? "#" : mapTile.tileType == MapTile.TileType.DOOR ? "." : "_"); heightJoinerRow.append(mapTile.height); styleIndexJoinerRow.append(mapTile.styleIndex); carcassJoinerRow.append( mapTile.disabled && !mapTile.carcass ? "X" : mapTile.carcass || point.x == 0 || point.y == 0 ? "#" : "_"); }); wallJoiner.add(wallJoinerRow.toString()); heightJoiner.add(heightJoinerRow.toString()); styleIndexJoiner.add(styleIndexJoinerRow.toString()); carcassJoiner.add(carcassJoinerRow.toString()); }); final StringJoiner textJoiner = new StringJoiner("\n\n"); textJoiner.add(carcassJoiner.toString()); textJoiner.add(wallJoiner.toString()); textJoiner.add(heightJoiner.toString()); textJoiner.add(styleIndexJoiner.toString()); Files.write(Path.of(config.outputTextFilePath), textJoiner.toString().getBytes()); //endregion //region OUTPUT: CREATE MAP JSON FILE //region BASE MAP JSON OBJECT final Map mapJson = new Map( new Meta( config.gameVersion, config.mapName, "2023-11-14 17:28:36.619839 UTC"), new About("Generated map"), new Settings( "bomb_defusal", config.ambientLightColor.intArray()), new Playtesting(Playtesting.QUICK_TEST), new ArrayList<>(), List.of(new Layer( "default", new ArrayList<>())), new ArrayList<>()); //endregion //region RESOURCES: FUNCTIONS final File texturesDir = new File("textures"); final Path mapGfxPath = mapDirectory.resolve("gfx"); if (!Files.exists(mapGfxPath)) { Files.createDirectories(mapGfxPath); } final BiConsumer<String, String> createTexture = Sneaky.biConsumer( (sourceFilename, targetFilename) -> { final Path sourcePath = texturesDir.toPath().resolve(sourceFilename + PNG_EXT); final Path targetPath = mapGfxPath.resolve(targetFilename + PNG_EXT); if (Files.exists(targetPath)) Files.delete(targetPath); Files.copy(sourcePath, targetPath); }); final Consumer<String> createTextureSameName = Sneaky.consumer( (filename) -> createTexture.accept(filename, filename)); final Function3<Integer, Integer, Boolean, String> getCrateName = ( final Integer roomStyleIndex, final Integer crateStyleIndex, final Boolean isBlocking ) -> "style" + roomStyleIndex + "_crate" + crateStyleIndex + "_" + (isBlocking ? "" : "non") + "blocking"; //endregion //region RESOURCES: ROOMS mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + ROOM_NOISE_CIRCLE + PNG_EXT) .id(RESOURCE_ID_PREFIX + ROOM_NOISE_CIRCLE) .stretch_when_resized(true) .domain(DOMAIN_FOREGROUND) .color(new Color(255, 255, 255, 150).intArray()) .build()); createTextureSameName.accept(ROOM_NOISE_CIRCLE); //endregion //region RESOURCES: STYLES IntStream.range(0, styles.length) .boxed() .forEach((final Integer roomStyleIndex) -> { final RoomStyle style = styles[roomStyleIndex]; final String floorId = RESOURCE_FLOOR_ID + roomStyleIndex; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + floorId + PNG_EXT) .id(RESOURCE_ID_PREFIX + floorId) .color(style.floorColor.intArray()) .build()); createTexture.accept(BASE_PNG_TEXTURE_FILENAME, floorId); final String wallId = RESOURCE_WALL_ID + roomStyleIndex; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + wallId + PNG_EXT) .id(RESOURCE_ID_PREFIX + wallId) .domain(DOMAIN_PHYSICAL) .color(style.wallColor.intArray()) .as_physical(AS_PHYSICAL_DEFAULT) .build()); createTexture.accept(BASE_PNG_TEXTURE_FILENAME, wallId); final String patternWallTarget = "style" + roomStyleIndex + "_pattern_wall"; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + patternWallTarget + PNG_EXT) .id(RESOURCE_ID_PREFIX + patternWallTarget) .domain(DOMAIN_FOREGROUND) .color(style.patternColorWall.intArray()) .build()); createTexture.accept("pattern" + style.patternIdWall, patternWallTarget); final String patternFloorTarget = "style" + roomStyleIndex + "_pattern_floor"; mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + patternFloorTarget + PNG_EXT) .id(RESOURCE_ID_PREFIX + patternFloorTarget) .color(style.patternColorFloor.intArray()) .build()); createTexture.accept("pattern" + style.patternIdFloor, patternFloorTarget); final BiConsumer<Integer, Boolean> createCrate = ( final Integer crateStyleIndex, final Boolean isBlocking ) -> { final String crateName = getCrateName.apply( roomStyleIndex, crateStyleIndex, isBlocking); final float sizeMultiplier = config.crateMinMaxSizeMultiplier.randomize(); mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + crateName + PNG_EXT) .id(RESOURCE_ID_PREFIX + crateName) .domain(DOMAIN_PHYSICAL) .stretch_when_resized(true) .size(CRATE_SIZE .mul(sizeMultiplier) .floatArray()) .color((isBlocking ? config.crateBlockingMinMaxTint : config.crateNonBlockingMinMaxTint) .randomize() .intArray() ).as_physical(Node.AsPhysical.builder() .custom_shape(Node.AsPhysical.CustomShape .CRATE_SHAPE .mul(sizeMultiplier)) .is_see_through(!isBlocking) .is_shoot_through(!isBlocking) .is_melee_throw_through(!isBlocking) .is_throw_through(!isBlocking) .density(nextFloat(0.6f, 1.3f)) .friction(nextFloat(0.0f, 0.5f)) .bounciness(nextFloat(0.1f, 0.6f)) .penetrability(nextFloat(0.0f, 1.0f)) .angular_damping(nextFloat(10f, 100f)) .build()) .build()); createTexture.accept(isBlocking ? CRATE_BLOCKING : CRATE_NON_BLOCKING, crateName); }; IntStream.range(0, config.cratesBlockingPerStyle) .forEach(crateIndex -> createCrate.accept(crateIndex, true)); IntStream.range(0, config.cratesNonBlockingPerStyle) .forEach(crateIndex -> createCrate.accept(crateIndex, false)); }); //endregion //region RESOURCES: SHADOWS mapJson.external_resources.add( ExternalResource.builder() .path(MAP_GFX_PATH + SHADOW_WALL_CORNER + PNG_EXT) .id(RESOURCE_ID_PREFIX + SHADOW_WALL_CORNER) .domain(DOMAIN_FOREGROUND) .color(config.shadowTintWall.intArray()) .as_nonphysical(AS_NON_PHYSICAL_DEFAULT) .build()); createTextureSameName.accept(SHADOW_WALL_CORNER); mapJson.external_resources.add( ExternalResource.builder()
.path(MAP_GFX_PATH + SHADOW_WALL_LINE + PNG_EXT)
23
2023-11-18 14:36:04+00:00
8k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/StatusActivity.java
[ { "identifier": "StatusAction", "path": "app/src/main/java/com/buaa/food/action/StatusAction.java", "snippet": "public interface StatusAction {\n\n /**\n * 获取状态布局\n */\n StatusLayout getStatusLayout();\n\n /**\n * 显示加载中\n */\n default void showLoading() {\n showLoading(R.raw.loading);\n }\n\n default void showLoading(@RawRes int id) {\n StatusLayout layout = getStatusLayout();\n layout.show();\n layout.setAnimResource(id);\n layout.setHint(\"\");\n layout.setOnRetryListener(null);\n }\n\n /**\n * 显示加载完成\n */\n default void showComplete() {\n StatusLayout layout = getStatusLayout();\n if (layout == null || !layout.isShow()) {\n return;\n }\n layout.hide();\n }\n\n /**\n * 显示空提示\n */\n default void showEmpty() {\n showLayout(R.drawable.status_empty_ic, R.string.status_layout_no_data, null);\n }\n\n /**\n * 显示错误提示\n */\n default void showError(StatusLayout.OnRetryListener listener) {\n StatusLayout layout = getStatusLayout();\n Context context = layout.getContext();\n ConnectivityManager manager = ContextCompat.getSystemService(context, ConnectivityManager.class);\n if (manager != null) {\n NetworkInfo info = manager.getActiveNetworkInfo();\n // 判断网络是否连接\n if (info == null || !info.isConnected()) {\n showLayout(R.drawable.status_network_ic, R.string.status_layout_error_network, listener);\n return;\n }\n }\n showLayout(R.drawable.status_error_ic, R.string.status_layout_error_request, listener);\n }\n\n /**\n * 显示自定义提示\n */\n default void showLayout(@DrawableRes int drawableId, @StringRes int stringId, StatusLayout.OnRetryListener listener) {\n StatusLayout layout = getStatusLayout();\n Context context = layout.getContext();\n showLayout(ContextCompat.getDrawable(context, drawableId), context.getString(stringId), listener);\n }\n\n default void showLayout(Drawable drawable, CharSequence hint, StatusLayout.OnRetryListener listener) {\n StatusLayout layout = getStatusLayout();\n layout.show();\n layout.setIcon(drawable);\n layout.setHint(hint);\n layout.setOnRetryListener(listener);\n }\n}" }, { "identifier": "AppActivity", "path": "app/src/main/java/com/buaa/food/app/AppActivity.java", "snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n /** 加载对话框 */\n private BaseDialog mDialog;\n /** 对话框数量 */\n private int mDialogCount;\n\n /**\n * 当前加载对话框是否在显示中\n */\n public boolean isShowDialog() {\n return mDialog != null && mDialog.isShowing();\n }\n\n /**\n * 显示加载对话框\n */\n public void showDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n mDialogCount++;\n postDelayed(() -> {\n if (mDialogCount <= 0 || isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialog == null) {\n mDialog = new WaitDialog.Builder(this)\n .setCancelable(false)\n .create();\n }\n if (!mDialog.isShowing()) {\n mDialog.show();\n }\n }, 300);\n }\n\n /**\n * 隐藏加载对话框\n */\n public void hideDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialogCount > 0) {\n mDialogCount--;\n }\n\n if (mDialogCount != 0 || mDialog == null || !mDialog.isShowing()) {\n return;\n }\n\n mDialog.dismiss();\n }\n\n @Override\n protected void initLayout() {\n super.initLayout();\n\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n // 初始化沉浸式状态栏\n if (isStatusBarEnabled()) {\n getStatusBarConfig().init();\n\n // 设置标题栏沉浸\n if (getTitleBar() != null) {\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n /**\n * 是否使用沉浸式状态栏\n */\n protected boolean isStatusBarEnabled() {\n return true;\n }\n\n /**\n * 状态栏字体深色模式\n */\n protected boolean isStatusBarDarkFont() {\n return true;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n public ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式状态栏\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(@StringRes int id) {\n setTitle(getString(id));\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(CharSequence title) {\n super.setTitle(title);\n if (getTitleBar() != null) {\n getTitleBar().setTitle(title);\n }\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null) {\n mTitleBar = obtainTitleBar(getContentView());\n }\n return mTitleBar;\n }\n\n @Override\n public void onLeftClick(View view) {\n onBackPressed();\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n super.startActivityForResult(intent, requestCode, options);\n overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);\n }\n\n @Override\n public void finish() {\n super.finish();\n overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);\n }\n\n /**\n * {@link OnHttpListener}\n */\n\n @Override\n public void onStart(Call call) {\n showDialog();\n }\n\n @Override\n public void onSucceed(Object result) {\n if (result instanceof HttpData) {\n toast(((HttpData<?>) result).getMessage());\n }\n }\n\n @Override\n public void onFail(Exception e) {\n toast(e.getMessage());\n }\n\n @Override\n public void onEnd(Call call) {\n hideDialog();\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n if (isShowDialog()) {\n hideDialog();\n }\n mDialog = null;\n }\n}" }, { "identifier": "MenuDialog", "path": "app/src/main/java/com/buaa/food/ui/dialog/MenuDialog.java", "snippet": "public final class MenuDialog {\n\n public static final class Builder\n extends BaseDialog.Builder<Builder>\n implements BaseAdapter.OnItemClickListener,\n View.OnLayoutChangeListener, Runnable {\n\n @SuppressWarnings(\"rawtypes\")\n @Nullable\n private OnListener mListener;\n private boolean mAutoDismiss = true;\n\n private final RecyclerView mRecyclerView;\n private final TextView mCancelView;\n\n private final MenuAdapter mAdapter;\n\n public Builder(Context context) {\n super(context);\n setContentView(R.layout.menu_dialog);\n setAnimStyle(BaseDialog.ANIM_BOTTOM);\n\n mRecyclerView = findViewById(R.id.rv_menu_list);\n mCancelView = findViewById(R.id.tv_menu_cancel);\n setOnClickListener(mCancelView);\n\n mAdapter = new MenuAdapter(getContext());\n mAdapter.setOnItemClickListener(this);\n mRecyclerView.setAdapter(mAdapter);\n }\n\n @Override\n public Builder setGravity(int gravity) {\n switch (gravity) {\n // 如果这个是在中间显示的\n case Gravity.CENTER:\n case Gravity.CENTER_VERTICAL:\n // 不显示取消按钮\n setCancel(null);\n // 重新设置动画\n setAnimStyle(BaseDialog.ANIM_SCALE);\n break;\n default:\n break;\n }\n return super.setGravity(gravity);\n }\n\n public Builder setList(int... ids) {\n List<String> data = new ArrayList<>(ids.length);\n for (int id : ids) {\n data.add(getString(id));\n }\n return setList(data);\n }\n\n public Builder setList(String... data) {\n return setList(Arrays.asList(data));\n }\n\n @SuppressWarnings(\"all\")\n public Builder setList(List data) {\n mAdapter.setData(data);\n mRecyclerView.addOnLayoutChangeListener(this);\n return this;\n }\n\n public Builder setCancel(@StringRes int id) {\n return setCancel(getString(id));\n }\n\n public Builder setCancel(CharSequence text) {\n mCancelView.setText(text);\n return this;\n }\n\n public Builder setAutoDismiss(boolean dismiss) {\n mAutoDismiss = dismiss;\n return this;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public Builder setListener(OnListener listener) {\n mListener = listener;\n return this;\n }\n\n @SingleClick\n @Override\n public void onClick(View view) {\n if (mAutoDismiss) {\n dismiss();\n }\n\n if (view == mCancelView) {\n if (mListener == null) {\n return;\n }\n mListener.onCancel(getDialog());\n }\n }\n\n /**\n * {@link BaseAdapter.OnItemClickListener}\n */\n @SuppressWarnings(\"all\")\n @Override\n public void onItemClick(RecyclerView recyclerView, View itemView, int position) {\n if (mAutoDismiss) {\n dismiss();\n }\n\n if (mListener == null) {\n return;\n }\n mListener.onSelected(getDialog(), position, mAdapter.getItem(position));\n }\n\n /**\n * {@link View.OnLayoutChangeListener}\n */\n @Override\n public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {\n mRecyclerView.removeOnLayoutChangeListener(this);\n // 这里一定要加延迟,如果不加在 Android 9.0 上面会导致 setLayoutParams 无效\n post(this);\n }\n\n @Override\n public void run() {\n final ViewGroup.LayoutParams params = mRecyclerView.getLayoutParams();\n final int maxHeight = getScreenHeight() / 4 * 3;\n if (mRecyclerView.getHeight() > maxHeight) {\n if (params.height != maxHeight) {\n params.height = maxHeight;\n mRecyclerView.setLayoutParams(params);\n }\n return;\n }\n\n if (params.height != ViewGroup.LayoutParams.WRAP_CONTENT) {\n params.height = ViewGroup.LayoutParams.WRAP_CONTENT;\n mRecyclerView.setLayoutParams(params);\n }\n }\n\n /**\n * 获取屏幕的高度\n */\n private int getScreenHeight() {\n Resources resources = getResources();\n DisplayMetrics outMetrics = resources.getDisplayMetrics();\n return outMetrics.heightPixels;\n }\n }\n\n private static final class MenuAdapter extends AppAdapter<Object> {\n\n private MenuAdapter(Context context) {\n super(context);\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n return new ViewHolder();\n }\n\n private final class ViewHolder extends AppAdapter<?>.ViewHolder {\n\n private final TextView mTextView;\n private final View mLineView;\n\n ViewHolder() {\n super(R.layout.menu_item);\n mTextView = findViewById(R.id.tv_menu_text);\n mLineView = findViewById(R.id.v_menu_line);\n }\n\n @Override\n public void onBindView(int position) {\n mTextView.setText(getItem(position).toString());\n\n if (position == 0) {\n // 当前是否只有一个条目\n if (getCount() == 1) {\n mLineView.setVisibility(View.GONE);\n } else {\n mLineView.setVisibility(View.VISIBLE);\n }\n } else if (position == getCount() - 1) {\n mLineView.setVisibility(View.GONE);\n } else {\n mLineView.setVisibility(View.VISIBLE);\n }\n }\n }\n }\n\n public interface OnListener<T> {\n\n /**\n * 选择条目时回调\n */\n void onSelected(BaseDialog dialog, int position, T t);\n\n /**\n * 点击取消时回调\n */\n default void onCancel(BaseDialog dialog) {}\n }\n}" }, { "identifier": "StatusLayout", "path": "app/src/main/java/com/buaa/food/widget/StatusLayout.java", "snippet": "public final class StatusLayout extends FrameLayout {\n\n /** 主布局 */\n private ViewGroup mMainLayout;\n /** 提示图标 */\n private LottieAnimationView mLottieView;\n /** 提示文本 */\n private TextView mTextView;\n /** 重试按钮 */\n private TextView mRetryView;\n /** 重试监听 */\n private OnRetryListener mListener;\n\n public StatusLayout(@NonNull Context context) {\n this(context, null);\n }\n\n public StatusLayout(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public StatusLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n /**\n * 显示\n */\n public void show() {\n\n if (mMainLayout == null) {\n //初始化布局\n initLayout();\n }\n\n if (isShow()) {\n return;\n }\n mRetryView.setVisibility(mListener == null ? View.INVISIBLE : View.VISIBLE);\n // 显示布局\n mMainLayout.setVisibility(VISIBLE);\n }\n\n /**\n * 隐藏\n */\n public void hide() {\n if (mMainLayout == null || !isShow()) {\n return;\n }\n //隐藏布局\n mMainLayout.setVisibility(INVISIBLE);\n }\n\n /**\n * 是否显示了\n */\n public boolean isShow() {\n return mMainLayout != null && mMainLayout.getVisibility() == VISIBLE;\n }\n\n /**\n * 设置提示图标,请在show方法之后调用\n */\n public void setIcon(@DrawableRes int id) {\n setIcon(ContextCompat.getDrawable(getContext(), id));\n }\n\n public void setIcon(Drawable drawable) {\n if (mLottieView == null) {\n return;\n }\n if (mLottieView.isAnimating()) {\n mLottieView.cancelAnimation();\n }\n mLottieView.setImageDrawable(drawable);\n }\n\n /**\n * 设置提示动画\n */\n public void setAnimResource(@RawRes int id) {\n if (mLottieView == null) {\n return;\n }\n\n mLottieView.setAnimation(id);\n if (!mLottieView.isAnimating()) {\n mLottieView.playAnimation();\n }\n }\n\n /**\n * 设置提示文本,请在show方法之后调用\n */\n public void setHint(@StringRes int id) {\n setHint(getResources().getString(id));\n }\n\n public void setHint(CharSequence text) {\n if (mTextView == null) {\n return;\n }\n if (text == null) {\n text = \"\";\n }\n mTextView.setText(text);\n }\n\n /**\n * 初始化提示的布局\n */\n private void initLayout() {\n\n mMainLayout = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.widget_status_layout, this, false);\n\n mLottieView = mMainLayout.findViewById(R.id.iv_status_icon);\n mTextView = mMainLayout.findViewById(R.id.iv_status_text);\n mRetryView = mMainLayout.findViewById(R.id.iv_status_retry);\n\n if (mMainLayout.getBackground() == null) {\n // 默认使用 windowBackground 作为背景\n TypedArray typedArray = getContext().obtainStyledAttributes(new int[]{android.R.attr.windowBackground});\n mMainLayout.setBackground(typedArray.getDrawable(0));\n mMainLayout.setClickable(true);\n typedArray.recycle();\n }\n\n mRetryView.setOnClickListener(mClickWrapper);\n\n addView(mMainLayout);\n }\n\n /**\n * 设置重试监听器\n */\n public void setOnRetryListener(OnRetryListener listener) {\n mListener = listener;\n if (isShow()) {\n mRetryView.setVisibility(mListener == null ? View.INVISIBLE : View.VISIBLE);\n }\n }\n\n /**\n * 点击事件包装类\n */\n private final OnClickListener mClickWrapper = new OnClickListener() {\n\n @Override\n public void onClick(View v) {\n if (mListener == null) {\n return;\n }\n mListener.onRetry(StatusLayout.this);\n }\n };\n\n /**\n * 重试监听器\n */\n public interface OnRetryListener {\n\n /**\n * 点击了重试\n */\n void onRetry(StatusLayout layout);\n }\n}" } ]
import androidx.core.content.ContextCompat; import com.buaa.food.R; import com.buaa.food.action.StatusAction; import com.buaa.food.app.AppActivity; import com.buaa.food.ui.dialog.MenuDialog; import com.buaa.food.widget.StatusLayout;
4,565
package com.buaa.food.ui.activity; public final class StatusActivity extends AppActivity implements StatusAction {
package com.buaa.food.ui.activity; public final class StatusActivity extends AppActivity implements StatusAction {
private StatusLayout mStatusLayout;
3
2023-11-14 10:04:26+00:00
8k
WallasAR/GUITest
src/main/java/com/session/employee/employeeClientController.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.createStatement();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n public static Connection conexao(){\n Connection conn = null;\n String url = \"jdbc:mysql://localhost:3306/farmacia?serverTimezone=America/Sao_Paulo\";\n String user = \"adm\";\n String password = \"1234\";\n try {\n conn = DriverManager.getConnection(url, user, password);\n\n } catch (SQLException erro) {\n JOptionPane.showMessageDialog(null, erro.getMessage());\n }\n return conn;\n }\n public void criartabela(){\n try {\n if(!tabelaExiste(\"medicamentos\")) {\n executar.execute(\"CREATE TABLE medicamentos(id INT NOT NULL AUTO_INCREMENT ,nome VARCHAR(25), quantidade INT, tipo VARCHAR(25), valor FLOAT, PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public static void deletarcliente(String idcli) throws SQLException{\n Connection connection = conexao();\n String deletecli = (\"DELETE FROM cliente WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(deletecli);\n preparedStatement.setString(1, idcli);\n preparedStatement.executeUpdate();\n }\n private boolean tabelaExiste(String nomeTabela) throws SQLException {\n // Verificar se a tabela já existe no banco de dados\n try (Connection connection = conexao();\n ResultSet resultSet = connection.getMetaData().getTables(null, null, nomeTabela, null)) {\n return resultSet.next();\n }\n }\n public void autenticar(){\n try {\n if(!tabelaExiste(\"autenticar\")) {\n executar.execute(\"CREATE TABLE autenticar(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), password VARCHAR(25), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n public void inseriradm(String user, String pass){\n try{\n String adm = (\"INSERT INTO autenticar (usuario, password) VALUES (?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(adm);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, pass);\n\n preparedStatement.executeUpdate();\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public void tablecliete(){\n try{\n if(!tabelaExiste(\"cliente\")){\n executar.execute(\"CREATE TABLE cliente(id INT NOT NULL AUTO_INCREMENT, nome VARCHAR(25), sobrenome VARCHAR(25), usuario VARCHAR(25), telefone VARCHAR(30), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public static boolean verificarusuario(String user){\n boolean existe = false;\n Connection connection = conexao();\n try{\n String verificar = \"SELECT * FROM cliente WHERE usuario = ?\";\n try(PreparedStatement verificarexis = connection.prepareStatement(verificar)){\n verificarexis.setString(1, user);\n try(ResultSet verificarresultado = verificarexis.executeQuery()){\n existe = verificarresultado.next();\n }\n }\n }catch(SQLException e){\n System.out.println(e);\n }\n return existe;\n }\n public void inserircliente(String nomecli, String sobrenomecli, String user, String fone){\n try{\n if(verificarusuario(user)) {\n AlertMsg alert = new AlertMsg();\n alert.msgInformation(\"Erro ao registrar\" , \"Nome de usuário ja está sendo utilizado, tente novamente.\");\n }else{\n String cliente = (\"INSERT INTO cliente (nome, sobrenome, usuario, telefone) VALUES(?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(cliente);\n preparedStatement.setString(1, nomecli);\n preparedStatement.setString(2, sobrenomecli);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, fone);\n\n preparedStatement.executeUpdate();\n }\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n\n public void updateClient(String nome, String sobrenome, String usuario, String fone, String idcli) throws SQLException {\n String updateQuaryCli = \"UPDATE cliente SET nome = ?, sobrenome = ?, usuario = ?, telefone = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, usuario);\n preparedStatement.setString(4, fone);\n preparedStatement.setString(5, idcli);\n preparedStatement.executeUpdate();\n }\n\n public void inserirmedicamento(String nomMedi, int quantiMedi,String tipoMedi, float valorMedi ){\n try{\n String medi = (\"INSERT INTO medicamentos (nome, quantidade, tipo , valor) VALUES(?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(medi);\n preparedStatement.setString(1, nomMedi);\n preparedStatement.setInt(2, quantiMedi);\n preparedStatement.setString(3, tipoMedi);\n preparedStatement.setFloat(4, valorMedi);\n\n preparedStatement.executeUpdate();\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n\n public static int somarentidadeseliente() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM cliente\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSoma = statement.executeQuery()) {\n\n if (consultaSoma.next()) {\n int soma = consultaSoma.getInt(\"soma_total\");\n return soma;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n public static int somarentidadesefuncionarios() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM funcionarios\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSomafu = statement.executeQuery()) {\n\n if (consultaSomafu.next()) {\n int somafu = consultaSomafu.getInt(\"soma_total\");\n return somafu;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n public static int somarentidadesmedicamentos() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM medicamentos\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSomamedi = statement.executeQuery()) {\n\n if (consultaSomamedi.next()) {\n int somamedi = consultaSomamedi.getInt(\"soma_total\");\n return somamedi;\n //System.out.println(\"Soma total de Medicamentos registrados: \" + somamedi);\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n\n public void tabelafuncionario(){\n try {\n if(!tabelaExiste(\"funcionarios\")) {\n executar.execute(\"CREATE TABLE funcionarios(id INT NOT NULL AUTO_INCREMENT, nome VARCHAR(25), sobrenome VARCHAR(25), usuario VARCHAR(25), cargo VARCHAR(25), cpf VARCHAR(25), salario FLOAT, senha VARCHAR(25), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserirfuncinario(String nome, String sobrenome, String user, String cargo, String Cpf, float salario, String senha){\n try{\n if(verificarusuario(user)) {\n System.out.println(\"O nome de usuario não pode ser utilizado, tente outro.\");\n }else{\n String cliente = (\"INSERT INTO funcionarios (nome, sobrenome, usuario, cargo, cpf, salario, senha) VALUES(?,?,?,?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(cliente);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, cargo);\n preparedStatement.setString(5, Cpf);\n preparedStatement.setFloat(6, salario);\n preparedStatement.setString(7, senha);\n\n preparedStatement.executeUpdate();\n }\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public void updateFuncionario(String nome, String sobrenome, String user, String cargo, String cpf, float salario, String senha, int idfunc) throws SQLException {\n String updateQuaryCli = \"UPDATE funcionarios SET nome = ?, sobrenome = ?, usuario = ?, cargo = ?, cpf = ?, salario = ?, senha = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, cargo);\n preparedStatement.setString(5, cpf);\n preparedStatement.setFloat(6, salario);\n preparedStatement.setString(7, senha);\n preparedStatement.setInt(8,idfunc);\n preparedStatement.executeUpdate();\n }\n public static void deletarfuncionario(int num) throws SQLException{\n Connection connection = conexao();\n String delete = (\"DELETE FROM funcionarios WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(delete);\n preparedStatement.setInt(1, num);\n\n preparedStatement.executeUpdate();\n }\n public static void deletarmedicamento(int num) throws SQLException{\n Connection connection = conexao();\n String delete = (\"DELETE FROM medicamentos WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(delete);\n preparedStatement.setInt(1, num);\n\n preparedStatement.executeUpdate();\n }\n public void updateMedicamento(String nome, int quantidade, String tipo, float valor, int idfunc) throws SQLException {\n String updateQuaryCli = \"UPDATE medicamentos SET nome = ?, quantidade = ?, tipo = ?, valor = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setInt(2, quantidade);\n preparedStatement.setString(3, tipo);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setInt(5,idfunc);\n preparedStatement.executeUpdate();\n }\n public void registro(){\n try {\n if(!tabelaExiste(\"registros\")) {\n executar.execute(\"CREATE TABLE registros(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor FLOAT, data VARCHAR(50), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n\n public void inseriregistro(String user, String medicamento, int quantidade, float valor, String date) throws SQLException {\n String dados = (\"INSERT INTO registros (usuario, medicamento, quantidade, valor, data) VALUES (?, ?, ?,?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setString(5, date);\n\n preparedStatement.executeUpdate();\n }\n public void carrinho(){\n try {\n if(!tabelaExiste(\"carrinho\")) {\n executar.execute(\"CREATE TABLE carrinho(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor FLOAT, PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserircarrinho(String user, String medicamento, int quantidade, float valor) throws SQLException {\n String dados = (\"INSERT INTO carrinho (usuario, medicamento, quantidade, valor) VALUES (?, ?, ?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n\n preparedStatement.executeUpdate();\n }\n public void encomendas(){\n try {\n if(!tabelaExiste(\"encomendas\")) {\n executar.execute(\"CREATE TABLE encomendas(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor INT, data VARCHAR(50), telefone VARCHAR(50), status VARCHAR(50), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserirencomendas(String user, String medicamento, int quantidade, float valor, String data,String fone, String status) throws SQLException {\n String dados = (\"INSERT INTO encomendas (usuario, medicamento, quantidade, valor, telefone, data, status) VALUES (?, ?, ?, ?, ?, ?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setString(5, fone);\n preparedStatement.setString(6, data);\n preparedStatement.setString(7, status);\n\n preparedStatement.executeUpdate();\n }\n}" }, { "identifier": "Main", "path": "src/main/java/com/example/guitest/Main.java", "snippet": "public class Main extends Application {\n\n private static Stage stage; // Variavel estaticas para fazer a mudança de tela\n\n private static Scene mainScene, homeScene, funcScene, medScene, clientScene, recordScene, funcServiceScene, medOrderScene, funcClientScene; // variavel do tipo Scene\n\n @Override\n public void start(Stage primaryStage) throws Exception { // Metodo padrão do JavaFX\n stage = primaryStage; // inicializando a variavel stage\n\n primaryStage.setTitle(\"UmbrellaCorp. System\");\n stage.getIcons().add(new Image(\"icon.png\"));\n primaryStage.initStyle(StageStyle.UNDECORATED);\n\n Parent fxmlLogin = FXMLLoader.load(getClass().getResource(\"TelaLogin.fxml\"));\n mainScene = new Scene(fxmlLogin, 700, 500); // Cache tela 1\n\n Parent fxmlHome = FXMLLoader.load(getClass().getResource(\"homePage.fxml\"));\n homeScene = new Scene(fxmlHome, 1920, 1080); // Cache tela 2\n\n Parent fxmlFunc = FXMLLoader.load(getClass().getResource(\"funcPage.fxml\"));\n funcScene = new Scene(fxmlFunc, 1920, 1080); // Cache tela 3\n\n Parent fxmlMed = FXMLLoader.load(getClass().getResource(\"medPage.fxml\"));\n medScene = new Scene(fxmlMed, 1920, 1080); // Cache tela 4\n\n Parent fxmlClient = FXMLLoader.load(getClass().getResource(\"clientPage.fxml\"));\n clientScene = new Scene(fxmlClient, 1920, 1080); // Cache tela\n\n Parent fxmlRecord = FXMLLoader.load(getClass().getResource(\"RecordPage.fxml\"));\n recordScene = new Scene(fxmlRecord, 1920, 1080); // Cache tela\n\n Parent fxmlfuncService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/PurchasePage.fxml\"));\n funcServiceScene = new Scene(fxmlfuncService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncMedOrderService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/medicineOrderPage.fxml\"));\n medOrderScene = new Scene(fxmlfuncMedOrderService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncClientService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/employeeClientPage.fxml\"));\n funcClientScene = new Scene(fxmlfuncClientService, 1920, 1080);\n\n primaryStage.setScene(mainScene); // Definindo tela principal/inicial\n primaryStage.show(); // mostrando a cena\n Banco banco = new Banco();\n banco.registro();\n banco.carrinho();\n banco.tablecliete();\n banco.encomendas();\n }\n\n public static void changedScene(String scr){ // metodo que muda a tela\n switch (scr){\n case \"main\":\n stage.setScene(mainScene);\n stage.centerOnScreen();\n break;\n case \"home\":\n stage.setScene(homeScene);\n stage.centerOnScreen();\n break;\n case \"func\":\n stage.setScene(funcScene);\n stage.centerOnScreen();\n break;\n case \"med\":\n stage.setScene(medScene);\n stage.centerOnScreen();\n break;\n case \"client\":\n stage.setScene(clientScene);\n stage.centerOnScreen();\n break;\n case \"sale\":\n stage.setScene(funcServiceScene);\n stage.centerOnScreen();\n break;\n case \"medOrder\":\n stage.setScene(medOrderScene);\n stage.centerOnScreen();\n break;\n case \"ClientAdmFunc\":\n stage.setScene(funcClientScene);\n stage.centerOnScreen();\n break;\n case \"record\":\n stage.setScene(recordScene);\n stage.centerOnScreen();\n break;\n }\n }\n\n public static void main(String[] args) {\n launch();\n }\n}" }, { "identifier": "ClienteTable", "path": "src/main/java/com/table/view/ClienteTable.java", "snippet": "public class ClienteTable {\n public int idcli;\n public String nomecli;\n public String sobrenome;\n public String usuario;\n public String fone;\n\n public ClienteTable(int idcli, String nomecli, String sobrenome, String usuario, String fone) {\n this.idcli = idcli;\n this.nomecli = nomecli;\n this.sobrenome = sobrenome;\n this.usuario = usuario;\n this.fone = fone;\n }\n\n public int getIdcli() {\n return idcli;\n }\n\n public void setIdcli(int idcli) {\n this.idcli = idcli;\n }\n\n public String getNomecli() {\n return nomecli;\n }\n\n public void setNomecli(String nomecli) {\n this.nomecli = nomecli;\n }\n\n public String getSobrenome() {\n return sobrenome;\n }\n\n public void setSobrenome(String sobrenome) {\n this.sobrenome = sobrenome;\n }\n\n public String getUsuario() {\n return usuario;\n }\n\n public void setUsuario(String usuario) {\n this.usuario = usuario;\n }\n\n public String getFone() {\n return fone;\n }\n\n public void setFone(String Fone) {\n this.fone = fone;\n }\n}" }, { "identifier": "AlertMsg", "path": "src/main/java/com/warning/alert/AlertMsg.java", "snippet": "public class AlertMsg {\n static ButtonType btnConfirm = new ButtonType(\"Confirmar\");\n static ButtonType btnCancel = new ButtonType(\"Cancelar\");\n static boolean answer;\n\n public static boolean msgConfirm(String headermsg, String msg){\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Alerta\");\n alert.setHeaderText(headermsg);\n alert.setContentText(msg);\n alert.getButtonTypes().setAll(btnConfirm, btnCancel);\n alert.showAndWait().ifPresent(b -> {\n if (b == btnConfirm){\n answer = true;\n } else {\n answer = false;\n }\n });\n return answer;\n }\n\n public void msgInformation(String header , String msg){\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Aviso\");\n alert.setHeaderText(header);\n alert.setContentText(msg);\n alert.showAndWait();\n }\n}" }, { "identifier": "connection", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public static Connection connection = conexao();" } ]
import com.db.bank.Banco; import com.example.guitest.Main; import com.table.view.ClienteTable; 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.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.net.URL; 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 static com.db.bank.Banco.connection;
5,223
package com.session.employee; public class employeeClientController implements Initializable { // Ações para troca de cena @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 SaleAction(MouseEvent e) { Main.changedScene("sale"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("ClientAdmFunc"); } // Predefinição da instância banco Banco banco = new Banco(); // GUI IDs @FXML private TableView tbCliente; @FXML private TableColumn clIdcli; @FXML private TableColumn clNomecli; @FXML private TableColumn clSobrenomeli; @FXML private TableColumn clUsuario; @FXML private TableColumn clFoneCli; @FXML private TextField tfNome; @FXML private TextField tfSobrenome; @FXML private TextField tfUser; @FXML private TextField tfFone; @FXML private TextField tfId; @FXML private TextField tfSearch; // Show The Client Table public void tabelacliente()throws SQLException { List<ClienteTable> clientes = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM cliente";
package com.session.employee; public class employeeClientController implements Initializable { // Ações para troca de cena @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 SaleAction(MouseEvent e) { Main.changedScene("sale"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("ClientAdmFunc"); } // Predefinição da instância banco Banco banco = new Banco(); // GUI IDs @FXML private TableView tbCliente; @FXML private TableColumn clIdcli; @FXML private TableColumn clNomecli; @FXML private TableColumn clSobrenomeli; @FXML private TableColumn clUsuario; @FXML private TableColumn clFoneCli; @FXML private TextField tfNome; @FXML private TextField tfSobrenome; @FXML private TextField tfUser; @FXML private TextField tfFone; @FXML private TextField tfId; @FXML private TextField tfSearch; // Show The Client Table public void tabelacliente()throws SQLException { List<ClienteTable> clientes = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM cliente";
Statement statement = connection.createStatement();
4
2023-11-16 14:55:08+00:00
8k
wzh933/Buffer-Manager
src/main/java/cs/adb/wzh/dataStorageManager/DSMgr.java
[ { "identifier": "Buffer", "path": "src/main/java/cs/adb/wzh/Storage/Buffer.java", "snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n }\n\n\n public Buffer() {\n final int DEF_BUF_SIZE = 1024;\n this.bufSize = DEF_BUF_SIZE;\n this.buf = new Frame[DEF_BUF_SIZE];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n /**\n * @param bufSize:用户自定义的缓存区大小\n */\n public Buffer(int bufSize) throws Exception {\n if (bufSize <= 0) {\n throw new Exception(\"缓存区大小不可以为非正数!\");\n }\n this.bufSize = bufSize;\n this.buf = new Frame[bufSize];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n public Frame readFrame(int frameId) {\n return buf[frameId];\n }\n\n public void writeFrame(Page page, int frameId) {\n //先不进行任何操作\n }\n\n}" }, { "identifier": "Disk", "path": "src/main/java/cs/adb/wzh/Storage/Disk.java", "snippet": "public class Disk {\n private final int diskSize;\n private final Page[] disk;\n\n public int getDiskSize() {\n return diskSize;\n }\n\n public Page[] getDisk() {\n return disk;\n }\n\n\n public Disk() {\n final int DEF_BUF_SIZE = 65536;//256MB的磁盘\n this.diskSize = DEF_BUF_SIZE;\n this.disk = new Page[DEF_BUF_SIZE];\n //初始化磁盘空间\n for (int pageId = 0; pageId < this.diskSize; pageId++) {\n this.disk[pageId] = new Page();\n }\n }\n\n\n}" }, { "identifier": "File", "path": "src/main/java/cs/adb/wzh/Storage/File.java", "snippet": "public class File {\n private final int fileSize;\n private final Page[] records;\n\n public int getFileSize() {\n return fileSize;\n }\n\n public Page getFileRecord(int recordId) {\n return records[recordId];\n }\n\n\n public File(String filename) {\n final int DEF_FILE_SIZE = 50000;//50000个页面的文件\n this.fileSize = DEF_FILE_SIZE;\n this.records = new Page[DEF_FILE_SIZE];\n //假设可以读取这个文件,实际上只是初始化文件空间\n for (int recordId = 0; recordId < this.fileSize; recordId++) {\n this.records[recordId] = new Page();\n }\n }\n\n\n}" }, { "identifier": "Frame", "path": "src/main/java/cs/adb/wzh/StorageForm/Frame.java", "snippet": "public class Frame {\n private final int FRAME_SIZE = 4096;\n private char[] field;\n\n public int getFrameSize() {\n return FRAME_SIZE;\n }\n\n public void setField(char[] field) {\n this.field = field;\n }\n\n public char[] getField() {\n return field;\n }\n\n public Frame() {\n this.field = new char[this.FRAME_SIZE];\n }\n}" }, { "identifier": "Page", "path": "src/main/java/cs/adb/wzh/StorageForm/Page.java", "snippet": "public class Page {\n private final int PAGE_SIZE = 4096;\n private char[] field;\n\n public int getFrameSize() {\n return PAGE_SIZE;\n }\n\n public void setField(char[] field) {\n this.field = field;\n }\n\n public char[] getField() {\n return field;\n }\n\n public Page() {\n this.field = new char[this.PAGE_SIZE];\n }\n}" }, { "identifier": "BMgr", "path": "src/main/java/cs/adb/wzh/bufferManager/BMgr.java", "snippet": "public class BMgr {\n private final DSMgr dsMgr;\n private final Bucket[] p2f;\n /*\n 有了BCB表之后就不需要f2p索引表了\n 其中bcbTable[frameId] = BCB(frameId)\n */\n private final BCB[] bcbTable;\n private BCB head;\n private BCB tail;\n private final int bufSize;\n private int freePageNum;\n private final Buffer bf;\n private final Disk disk;\n\n private double hitNum = 0;\n private int operation;//0-读 1-写\n// private BCB freePageTail;\n\n //对页面的读写操作(operation, pageId)\n// private final pageRecordReader pageRecords;\n\n private BCB clockSentinel;//维护一个时钟哨兵\n // private boolean useLRU = false;\n// private boolean useCLOCK = false;\n private SwapMethod swapMethod;\n\n public BMgr(Buffer bf, Disk disk) throws IOException {\n this.bf = bf;\n this.disk = disk;\n this.bufSize = bf.getBufSize();\n this.freePageNum = bufSize;\n\n this.dsMgr = new DSMgr(bf, disk);\n this.dsMgr.openFile(\"data.dbf\");\n\n// this.pageRecords = new pageRecordReader(pageRequestsFilePath);\n\n this.bcbTable = new BCB[bufSize];\n this.p2f = new Bucket[bufSize];\n\n this.head = new BCB(-1);//增加一个frameId为-1的无效节点并在之后作为环形链表的尾结点\n BCB p = this.head, q;\n //初始化帧缓存区BCB的双向循环链表\n for (int i = 0; i < this.bufSize; i++) {\n q = new BCB(i);\n p.setNext(q);//设置后继节点\n q.setPre(p);//设置前驱节点\n p = q;\n if (i == this.bufSize - 1) {\n this.tail = q;//设置缓存区尾指针\n }\n this.bcbTable[i] = p;//bcbTable中: bcbId = bcb.getFrameId()\n }\n //循环链表\n this.head.setPre(tail);\n this.tail.setNext(head);\n //让无效结点作为尾部结点\n this.head = this.head.getNext();\n this.tail = this.tail.getNext();\n }\n\n public BCB getHead() {\n return head;\n }\n\n public BCB getTail() {\n return tail;\n }\n\n public BCB[] getBcbTable() {\n return bcbTable;\n }\n\n\n public void move2Head(BCB bcb) {\n if (bcb == this.head || bcb == this.tail) {\n /*\n 本就是首尾部结点则不做任何操作\n 因为首部结点不用动\n 尾部结点无效也不需要任何操作\n */\n return;\n }\n //这样写代码舒服多了\n bcb.getPre().setNext(bcb.getNext());\n bcb.getNext().setPre(bcb.getPre());\n bcb.setPre(this.tail);\n bcb.setNext(this.head);\n this.head.setPre(bcb);\n this.tail.setNext(bcb);\n this.head = bcb;\n }\n\n\n/*\n /**\n * 文件和访问管理器将使用记录的record_id中的page_id调用这个页面\n * 该函数查看页面是否已经在缓冲区中\n * 如果是,则返回相应的frame_id\n * 如果页面尚未驻留在缓冲区中,则它会选择牺牲页面(如果需要),并加载所请求的页面。\n *\n * @param pageId:需要被固定于缓存区的页号\n * @return frameId:页面pageId被固定于缓存区的帧号\n * /\n public int fixPage(int pageId) throws Exception {\n int frameId = this.fixPageLRU(pageId);//可以切换不同的策略进行页面的置换\n this.bcbTable[frameId].setDirty(operation);//如果是写操作则将脏位设置为1(0-读 1-写)\n\n return frameId;\n/*\n Page page = this.dsMgr.readPage(pageId);\n if (this.p2f[this.hash(pageId)] == null) {//如果pageId对应的hash桶是空的则新建桶\n this.p2f[this.hash(pageId)] = new Bucket();\n }\n Bucket hashBucket = this.p2f[this.hash(pageId)];//找到pageId可能存放的hash桶\n BCB targetBCB = hashBucket.searchPage(pageId);//寻找hash桶中的页面\n if (targetBCB != null) {\n /*\n 如果该页面存放在缓存区中\n 那么命中次数加一\n 同时将该页面置于循环链表的首部\n * /\n this.hitNum++;\n this.move2Head(targetBCB);\n return targetBCB.getFrameId();\n }\n\n /*\n 如果该页面不在缓存区中,则从磁盘读取该页并且执行如下的内存操作:\n a)该缓存区未满,则将该页面存放于缓存区的尾部并将其移动至首部\n b)该缓存区已满,则执行淘汰规则:\n 1、得到需要将要被置换(牺牲)的尾部页面victimBCB和其帧号frameId\n 2、将victimBCB从其原来的pageId对应的hash桶中删除\n 3、修改victimBCB原来的pageId为当前pageId\n 4、将victimBCB放入当前pageId对应的hash桶中\n 5、将victimBCB移到首部\n 6、如果该帧脏位为1,则将帧frameId中的内容写入页面pageId中\n * /\n this.dsMgr.readPage(pageId);\n int frameId;\n if (this.freePageNum > 0) {\n frameId = this.bufSize - this.freePageNum;\n BCB freeBCB = this.bcbTable[frameId];\n freeBCB.setPageId(pageId);\n this.move2Head(freeBCB);\n this.freePageNum--;\n this.p2f[this.hash(freeBCB.getPageId())].appendBCB(freeBCB);\n } else {\n frameId = this.selectVictim();\n if (this.bcbTable[frameId].getDirty() == 1) {\n this.dsMgr.writePage(frameId, this.bcbTable[frameId].getPageId());\n }\n BCB victimBCB = this.bcbTable[frameId];\n victimBCB.setPageId(pageId);\n// System.out.printf(\"frameId: %d, pageId: %d\\n\", victimBCB.getFrameId(), victimBCB.getPageId());\n hashBucket.appendBCB(victimBCB);\n// this.move2Head(victimBCB);\n\n// this.bf.getBuf()[frameId].setField(page.getField());\n }\n return frameId;\n* /\n\n }\n*/\n\n\n /**\n * 当插入、索引拆分或创建对象时需要一个新页面时,使用这个函数\n * 此函数将找到一个空页面,文件和访问管理器可以使用它来存储一些数据\n *\n * @return 该page被分配到缓存区中的frameId\n */\n public int fixNewPage() throws Exception {\n /*\n 先在被固定的页面中搜索可用位为0的页面\n 如果找到被固定页面中的可用页面pageId\n 那么该页面pageId将被重用\n 同时置该页面的使用位为1\n */\n for (int pageId = 0; pageId < dsMgr.getNumPages(); pageId++) {\n if (dsMgr.getUse(pageId) == 0) {\n dsMgr.setUse(pageId, 1);\n return pageId;\n }\n }\n /*\n 否则被固定的页面计数器+=1\n 并且从非固定页面中重新分配页面\n 并且置该页面的使用位为1\n 其中被分配的页面allocPageId为pageNum(pageId从0开始)\n */\n int allocPageId = dsMgr.getNumPages();\n if (allocPageId >= dsMgr.getMaxPageNum()) {\n throw new Exception(\"当前磁盘已满,无法分配新页面!\");\n }\n dsMgr.setUse(allocPageId, 1);\n dsMgr.incNumPages();\n return allocPageId;\n }\n\n /**\n * 文件和访问管理器将使用记录的record_id中的page_id调用这个页面\n * 该函数查看页面是否已经在缓冲区中\n * 如果是,则返回相应的frame_id\n * 如果页面尚未驻留在缓冲区中,则它会选择牺牲页面(如果需要),并加载所请求的页面。\n *\n * @param pageId:需要被固定于缓存区的页号\n * @return frameId:页面pageId被固定于缓存区的帧号\n */\n public int fixPage(int pageId) throws Exception {\n if (this.p2f[this.hash(pageId)] == null) {//如果pageId对应的hash桶是空的则新建桶\n this.p2f[this.hash(pageId)] = new Bucket();\n }\n Bucket hashBucket = this.p2f[this.hash(pageId)];//找到pageId可能存放的hash桶\n BCB targetBCB = hashBucket.searchPage(pageId);//寻找hash桶中的页面\n if (targetBCB != null) {\n /*\n 如果该页面存放在缓存区中\n 那么命中次数加一\n 如果采用LRU策略则将该页面置于循环链表的首部\n */\n this.hitNum++;\n targetBCB.setDirty(this.operation);//如果是写操作则将脏位设置为1(0-读 1-写)\n if (this.swapMethod == SwapMethod.LRU) {//如果使用LRU置换算法则将命中页面移动至首部\n this.move2Head(targetBCB);\n }\n targetBCB.setReferenced(1);\n return targetBCB.getFrameId();\n }\n\n /*\n 如果该页面不在缓存区中,则从磁盘读取该页并且执行如下的内存操作:\n a)该缓存区未满,则将该页面存放于缓存区的尾部并将其移动至首部\n b)该缓存区已满,则执行淘汰规则:\n 1、得到需要将要被置换(牺牲)的尾部页面victimBCB和其帧号frameId\n 2、将victimBCB从其原来的pageId对应的hash桶中删除\n 3、修改victimBCB原来的pageId为当前pageId\n 4、将victimBCB放入当前pageId对应的hash桶中\n 5、将victimBCB移到首部\n 6、如果该帧脏位为1,则将帧frameId中的内容写入页面pageId中\n */\n if (this.operation == 0) {\n this.dsMgr.readPage(pageId);\n }\n int frameId;\n if (this.freePageNum > 0) {\n frameId = this.bufSize - this.freePageNum;\n BCB freeBCB = this.bcbTable[frameId];\n freeBCB.setPageId(pageId);\n this.move2Head(freeBCB);\n //让时钟哨兵指向循环双向链表中的最后一个结点\n this.clockSentinel = this.tail.getPre();\n// this.clockSentinel = this.head;\n this.freePageNum--;\n this.p2f[this.hash(freeBCB.getPageId())].appendBCB(freeBCB);\n } else {\n frameId = this.selectVictim();\n if (this.bcbTable[frameId].getDirty() == 1) {\n this.dsMgr.writePage(frameId, this.bcbTable[frameId].getPageId());\n }\n BCB victimBCB = this.bcbTable[frameId];\n victimBCB.setPageId(pageId);\n// System.out.printf(\"frameId: %d, pageId: %d\\n\", victimBCB.getFrameId(), victimBCB.getPageId());\n hashBucket.appendBCB(victimBCB);\n// this.move2Head(victimBCB);\n\n// this.bf.getBuf()[frameId].setField(page.getField());\n }\n this.bcbTable[frameId].setDirty(operation);//如果是写操作则将脏位设置为1(0-读 1-写)\n return frameId;\n }\n\n /**\n * NumFreeFrames函数查看缓冲区,并返回可用的缓冲区页数\n *\n * @return int\n */\n public int numFreeFrames() {\n return freePageNum;\n }\n\n /**\n * @return 被淘汰的页面存放的帧号frameId\n */\n private int selectVictim() throws Exception {\n int victimFrame;\n switch (swapMethod) {\n case LRU -> victimFrame = removeLRUEle();\n case CLOCK -> victimFrame = removeCLOCKEle();\n default -> victimFrame = this.tail.getPre().getFrameId();\n }\n return victimFrame;\n }\n\n private int hash(int pageId) {\n return pageId % bufSize;\n }\n\n private void removeBCB(int pageId) throws Exception {\n Bucket hashBucket = this.p2f[this.hash(pageId)];\n if (hashBucket == null) {\n throw new Exception(\"哈希桶不存在,代码出错啦!\");\n }\n if (this.p2f[this.hash(pageId)].searchPage(pageId) == null) {\n throw new Exception(\"找不到要删除的页,代码出错啦!\");\n }\n\n for (Bucket curBucket = hashBucket; curBucket != null; curBucket = curBucket.getNext()) {\n for (int i = 0; i < curBucket.getBcbNum(); i++) {\n if (curBucket.getBcbList().get(i).getPageId() == pageId) {\n curBucket.getBcbList().remove(i);\n// System.out.println(curBucket);\n for (Bucket curBucket1 = curBucket; curBucket1 != null; curBucket1 = curBucket1.getNext()) {\n if (curBucket1.getNext() != null) {\n //将下个桶中的首元素加入当前桶\n curBucket1.getBcbList().add(curBucket1.getNext().getBcbList().get(0));\n //删除下个桶的首元素\n curBucket1.getNext().getBcbList().remove(0);\n //如果下个桶空则删除桶\n if (curBucket1.getNext().getBcbNum() == 0) {\n curBucket1.setNext(null);\n }\n }\n }\n break;\n }\n }\n }\n }\n\n private int removeLRUEle() throws Exception {\n //LRU策略选择尾部结点作为victimBCB\n BCB victimBCB = this.tail.getPre();\n //从hash表中删除BCB并在之后建立新的索引\n this.removeBCB(victimBCB.getPageId());\n //将被淘汰结点放至首部并在之后重新设置其页号\n this.move2Head(victimBCB);\n return victimBCB.getFrameId();\n }\n\n private int removeCLOCKEle() {\n for (; this.clockSentinel.getReferenced() != 0; this.clockSentinel = this.clockSentinel.getNext()) {\n if (this.clockSentinel.getFrameId() == -1) {//遇到无效节点则不进行任何操作\n continue;\n }\n this.clockSentinel.setReferenced(0);\n }\n this.clockSentinel.setReferenced(1);\n int resFrameId = this.clockSentinel.getFrameId();\n this.clockSentinel = this.clockSentinel.getNext();\n if (this.clockSentinel.getFrameId() == -1) {\n this.clockSentinel = this.clockSentinel.getNext();\n }\n return resFrameId;\n }\n\n\n public void writeDirtys() {\n /*\n 这键盘突然好了\n 我真是蚌埠住了\n */\n for (int frameId = 0; frameId < this.bufSize; frameId++) {\n if (this.bcbTable[frameId].getDirty() == 1) {\n this.dsMgr.writePage(frameId, this.bcbTable[frameId].getPageId());\n }\n }\n\n }\n\n public void printBuffer() {\n for (BCB p = this.head; p.getFrameId() != -1; p = p.getNext()) {\n System.out.printf(\"%d, \", p.getPageId());\n }\n System.out.println();\n }\n\n// public void setUseLRU(boolean useLRU) {\n// this.useLRU = useLRU;\n// }\n//\n// public void setUseCLOCK(boolean useCLOCK) {\n// this.useCLOCK = useCLOCK;\n// }\n\n public void setSwapMethod(SwapMethod swapMethod) {\n this.swapMethod = swapMethod;\n }\n\n public double getHitNum() {\n return hitNum;\n }\n\n public void setOperation(int operation) {//0-读 1-写\n this.operation = operation;\n }\n\n public int getReadDiskNum() {\n return this.dsMgr.getReadDiskNum();\n }\n\n public int getWriteDiskNum() {\n return this.dsMgr.getWriteDiskNum();\n }\n\n\n}" } ]
import cs.adb.wzh.Storage.Buffer; import cs.adb.wzh.Storage.Disk; import cs.adb.wzh.Storage.File; import cs.adb.wzh.StorageForm.Frame; import cs.adb.wzh.StorageForm.Page; import cs.adb.wzh.bufferManager.BMgr; import java.io.IOException; import java.util.Arrays;
5,826
package cs.adb.wzh.dataStorageManager; /** * @author Wang Zihui * @date 2023/11/12 **/ public class DSMgr { private final int maxPageNum; private int pageNum = 0;//开始时被固定的页面数位0 private final int[] pages; private int curRecordId; private File curFile;
package cs.adb.wzh.dataStorageManager; /** * @author Wang Zihui * @date 2023/11/12 **/ public class DSMgr { private final int maxPageNum; private int pageNum = 0;//开始时被固定的页面数位0 private final int[] pages; private int curRecordId; private File curFile;
private final Buffer bf;
0
2023-11-15 16:30:06+00:00
8k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/BlockModelDragonFly.java
[ { "identifier": "DragonFly", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static final Gson GSON = new GsonBuilder().registerTypeAdapter(Animation.class, new AnimationDeserializer()).create();\n\tpublic static final Side[] sides = new Side[]{Side.BOTTOM, Side.TOP, Side.NORTH, Side.SOUTH, Side.WEST, Side.EAST};\n\tpublic static double terrainAtlasWidth = TextureFX.tileWidthTerrain * Global.TEXTURE_ATLAS_WIDTH_TILES;\n\tpublic static String version;\n\tpublic static boolean isDev;\n\tpublic static String renderState = \"gui\";\n\tstatic {\n\t\tversion = FabricLoader.getInstance().getModContainer(MOD_ID).get().getMetadata().getVersion().getFriendlyString();\n\t\tisDev = version.equals(\"${version}\") || version.contains(\"dev\");\n\t}\n\t@Override\n\tpublic void beforeGameStart() {\n\t\tif (isDev){\n\t\t\tLOGGER.info(\"DragonFly \" + version + \" loading debug assets\");\n\t\t\tDebugMain.init();\n\t\t}\n\t\tLOGGER.info(\"DragonFly initialized.\");\n\t}\n\n\t@Override\n\tpublic void afterGameStart() {\n\n\t}\n}" }, { "identifier": "ModelHelper", "path": "src/main/java/useless/dragonfly/helper/ModelHelper.java", "snippet": "public class ModelHelper {\n\tpublic static final Map<NamespaceId, ModelData> modelDataFiles = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockModel> registeredModels = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockstateData> registeredBlockStates = new HashMap<>();\n\tpublic static HashMap<NamespaceId, BenchEntityModel> benchEntityModelMap = new HashMap<>();\n\n\t/**\n\t * Place mod models in the <i>assets/modid/model/block/</i> directory for them to be seen.\n\t */\n\tpublic static BlockModel getOrCreateBlockModel(String modId, String modelSource) {\n\t\tNamespaceId namespaceId = new NamespaceId(modId, modelSource);\n\t\tif (registeredModels.containsKey(namespaceId)){\n\t\t\treturn registeredModels.get(namespaceId);\n\t\t}\n\t\tBlockModel model = new BlockModel(namespaceId);\n\t\tregisteredModels.put(namespaceId, model);\n\t\treturn model;\n\t}\n\t/**\n\t * Place mod models in the <i>assets/modid/blockstates/</i> directory for them to be seen.\n\t */\n\tpublic static BlockstateData getOrCreateBlockState(String modId, String blockStateSource) {\n\t\tNamespaceId namespaceId = new NamespaceId(modId, blockStateSource);\n\t\tif (registeredBlockStates.containsKey(namespaceId)){\n\t\t\treturn registeredBlockStates.get(namespaceId);\n\t\t}\n\t\treturn createBlockState(namespaceId);\n\t}\n\tprivate static BlockstateData createBlockState(NamespaceId namespaceId){\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(getBlockStateLocation(namespaceId)))));\n\t\tBlockstateData blockstateData = DragonFly.GSON.fromJson(reader, BlockstateData.class);\n\t\tregisteredBlockStates.put(namespaceId, blockstateData);\n\t\tif (blockstateData.variants != null){\n\t\t\tfor (VariantData variant : blockstateData.variants.values()) {\n\t\t\t\tNamespaceId variantNamespaceId = NamespaceId.idFromString(variant.model);\n\t\t\t\tgetOrCreateBlockModel(variantNamespaceId.getNamespace(), variantNamespaceId.getId());\n\t\t\t}\n\t\t}\n\t\tif (blockstateData.multipart != null){\n\t\t\tfor (ModelPart part : blockstateData.multipart){\n\t\t\t\tNamespaceId variantNamespaceId = NamespaceId.idFromString(part.apply.model);\n\t\t\t\tgetOrCreateBlockModel(variantNamespaceId.getNamespace(), variantNamespaceId.getId());\n\t\t\t}\n\t\t}\n\t\treturn blockstateData;\n\t}\n\tpublic static ModelData loadBlockModel(NamespaceId namespaceId){\n\t\tif (modelDataFiles.containsKey(namespaceId)){\n\t\t\treturn modelDataFiles.get(namespaceId);\n\t\t}\n\t\treturn createBlockModel(namespaceId);\n\t}\n\tprivate static ModelData createBlockModel(NamespaceId namespaceId){\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(getModelLocation(namespaceId)))));\n\t\tModelData modelData = DragonFly.GSON.fromJson(reader, ModelData.class);\n\t\tmodelDataFiles.put(namespaceId, modelData);\n\t\treturn modelData;\n\t}\n\n\t/**\n\t * Place mod models in the <i>assets/modid/model/</i> directory for them to be seen.\n\t */\n\tpublic static BenchEntityModel getOrCreateEntityModel(String modID, String modelSource, Class<? extends BenchEntityModel> baseModel) {\n\t\tNamespaceId namespaceId = new NamespaceId(modID, modelSource);\n\t\tif (benchEntityModelMap.containsKey(namespaceId)){\n\t\t\treturn benchEntityModelMap.get(namespaceId);\n\t\t}\n\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(getModelLocation(namespaceId)))));\n\t\tBenchEntityModel model = DragonFly.GSON.fromJson(reader, baseModel);\n\t\tbenchEntityModelMap.put(namespaceId, model);\n\t\treturn model;\n\t}\n\tpublic static String getModelLocation(NamespaceId namespaceId){\n\t\tString modelSource = namespaceId.getId();\n\t\tif (!modelSource.contains(\".json\")){\n\t\t\tmodelSource += \".json\";\n\t\t}\n\t\treturn \"/assets/\" + namespaceId.getNamespace() + \"/model/\" + modelSource;\n\t}\n\tpublic static String getBlockStateLocation(NamespaceId namespaceId){\n\t\tString modelSource = namespaceId.getId();\n\t\tif (!modelSource.contains(\".json\")){\n\t\t\tmodelSource += \".json\";\n\t\t}\n\t\treturn \"/assets/\" + namespaceId.getNamespace() + \"/blockstates/\" + modelSource;\n\t}\n\tpublic static void refreshModels(){\n\t\tSet<NamespaceId> blockModelDataKeys = new HashSet<>(modelDataFiles.keySet());\n\t\tSet<NamespaceId> blockStateKeys = new HashSet<>(registeredBlockStates.keySet());\n//\t\tSet<String> entityModelKeys = new HashSet<>(benchEntityModelMap.keySet());\n\n\t\tfor (NamespaceId modelDataKey : blockModelDataKeys){\n\t\t\tcreateBlockModel(modelDataKey);\n\t\t}\n\t\tfor (BlockModel model : registeredModels.values()){\n\t\t\tmodel.refreshModel();\n\t\t}\n\t\tfor (NamespaceId stateKey : blockStateKeys){\n\t\t\tcreateBlockState(stateKey);\n\t\t}\n\n\t}\n}" }, { "identifier": "RenderBlocksAccessor", "path": "src/main/java/useless/dragonfly/mixins/mixin/accessor/RenderBlocksAccessor.java", "snippet": "@Mixin(value = RenderBlocks.class, remap = false)\npublic interface RenderBlocksAccessor {\n\t@Accessor\n\tWorldSource getBlockAccess();\n\t@Accessor\n\tRenderBlockCache getCache();\n\t@Accessor\n\tfloat[] getSIDE_LIGHT_MULTIPLIER();\n\t@Accessor\n\tboolean getOverbright();\n\t@Invoker(\"getBlockBrightness\")\n\tfloat invokeGetBlockBrightness(WorldSource blockAccess, int x, int y, int z);\n}" }, { "identifier": "BlockModel", "path": "src/main/java/useless/dragonfly/model/block/processed/BlockModel.java", "snippet": "public class BlockModel {\n\tprivate static final HashMap<String, PositionData> defaultDisplays = new HashMap<>();\n\tstatic {\n\t\tPositionData gui = new PositionData();\n\t\tgui.rotation = new double[]{30, 225, 0};\n\t\tgui.translation = new double[] {0, 0, 0};\n\t\tgui.scale = new double[]{0.625, 0.625, 0.625};\n\n\t\tPositionData ground = new PositionData();\n\t\tground.rotation = new double[]{0, 0, 0};\n\t\tground.translation = new double[] {0, 3, 0};\n\t\tground.scale = new double[]{0.25, 0.25, 0.25};\n\n\t\tPositionData right_3rd = new PositionData();\n\t\tright_3rd.rotation = new double[]{75, 45, 0};\n\t\tright_3rd.translation = new double[] {0, 2.5, 0};\n\t\tright_3rd.scale = new double[]{0.375, 0.375, 0.375};\n\n\t\tPositionData right_first = new PositionData();\n\t\tright_first.rotation = new double[]{0, 45, 0};\n\t\tright_first.translation = new double[] {0, 0, 0};\n\t\tright_first.scale = new double[]{0.4, 0.4, 0.4};\n\n\t\tdefaultDisplays.put(\"gui\", gui);\n\t\tdefaultDisplays.put(\"ground\", ground);\n\t\tdefaultDisplays.put(\"thirdperson_righthand\", right_3rd);\n\t\tdefaultDisplays.put(\"firstperson_righthand\", right_first);\n\t}\n\tpublic BlockCube[] blockCubes = new BlockCube[0];\n\tprotected ModelData modelData;\n\tprotected BlockModel parentModel;\n\tpublic HashMap<String, String> textureMap;\n\tpublic HashMap<String, PositionData> display;\n\tpublic final NamespaceId namespaceId;\n\tpublic BlockModel(NamespaceId namespaceId){\n\t\tthis.namespaceId = namespaceId;\n\t\trefreshModel();\n\t}\n\tpublic void refreshModel(){\n\t\tthis.modelData = ModelHelper.loadBlockModel(namespaceId);\n\t\ttextureMap = new HashMap<>();\n\t\tdisplay = new HashMap<>();\n\n\t\tif (modelData.parent != null){ // Has parent Model\n\t\t\tString namespace;\n\t\t\tString modelName;\n\t\t\tif (modelData.parent.contains(\":\")){\n\t\t\t\tnamespace = modelData.parent.split(\":\")[0];\n\t\t\t\tmodelName = modelData.parent.split(\":\")[1];\n\t\t\t} else {\n\t\t\t\tnamespace = NamespaceId.coreNamespaceId;\n\t\t\t\tmodelName = modelData.parent;\n\t\t\t}\n\t\t\tparentModel = ModelHelper.getOrCreateBlockModel(namespace, modelName );\n\n\t\t\ttextureMap.putAll(parentModel.textureMap);\n\t\t\tdisplay.putAll(parentModel.display);\n\t\t}\n\t\ttextureMap.putAll(modelData.textures);\n\t\tdisplay.putAll(modelData.display);\n\n\n\t\t// Initialize textures\n\t\tfor (String texture: textureMap.values()) {\n\t\t\tif (texture == null) continue;\n\t\t\tTextureRegistry.softRegisterTexture(texture);\n\t\t}\n\n\t\t// Use parent elements if model does not specify its own\n\t\tif (parentModel != null && modelData.elements == null){\n\t\t\tthis.blockCubes = new BlockCube[parentModel.blockCubes.length];\n\t\t\tfor (int i = 0; i < blockCubes.length; i++) {\n\t\t\t\tblockCubes[i] = new BlockCube(this, parentModel.blockCubes[i].cubeData);\n\t\t\t}\n\t\t} else if (modelData.elements != null) {\n\t\t\tthis.blockCubes = new BlockCube[modelData.elements.length];\n\t\t\tfor (int i = 0; i < blockCubes.length; i++) {\n\t\t\t\tblockCubes[i] = new BlockCube(this, modelData.elements[i]);\n\t\t\t}\n\t\t}\n\t}\n\tpublic NamespaceId getTexture(String textureKey){\n\t\tString result;\n\t\tif (textureKey.contains(\"#\")){\n\t\t\tresult = textureMap.get(textureKey.substring(1));\n\t\t} else {\n\t\t\tresult =textureMap.get(textureKey);\n\t\t}\n\n\t\tif (result == null || result.equals(textureKey)) return TextureRegistry.getNamespaceId(0,0);\n\t\tif (result.contains(\"#\")){\n\t\t\treturn getTexture(result);\n\t\t} else if (!result.contains(\":\")) {\n\t\t\tresult = NamespaceId.coreNamespaceId + \":\" + result;\n\t\t}\n\t\treturn NamespaceId.idFromString(result);\n\t}\n\tpublic boolean getAO(){\n\t\treturn modelData.ambientocclusion;\n\t}\n\t@Nonnull\n\tpublic PositionData getDisplayPosition(String key){\n\t\tif (display.containsKey(key)){\n\t\t\treturn display.get(key);\n\t\t}\n\t\tdisplay.put(key, defaultDisplays.getOrDefault(key, new PositionData()));\n\t\treturn display.get(key);\n\t}\n}" }, { "identifier": "BlockstateData", "path": "src/main/java/useless/dragonfly/model/blockstates/data/BlockstateData.java", "snippet": "public class BlockstateData {\n\t@SerializedName(\"variants\")\n\tpublic HashMap<String, VariantData> variants;\n\t@SerializedName(\"multipart\")\n\tpublic ModelPart[] multipart;\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tif (variants == null){\n\t\t\tbuilder.append(\"null\\n\");\n\t\t} else {\n\t\t\tfor (String key: variants.keySet()) {\n\t\t\t\tbuilder.append(key).append(\"\\n\");\n\t\t\t\tbuilder.append(Utilities.tabBlock(variants.get(key).toString(),1));\n\t\t\t}\n\t\t}\n\t\treturn builder.toString();\n\t}\n}" }, { "identifier": "ModelPart", "path": "src/main/java/useless/dragonfly/model/blockstates/data/ModelPart.java", "snippet": "public class ModelPart {\n\t@SerializedName(\"apply\")\n\tpublic VariantData apply;\n\t@SerializedName(\"when\")\n\tpublic HashMap<String, Object> when = new HashMap<>();\n}" }, { "identifier": "VariantData", "path": "src/main/java/useless/dragonfly/model/blockstates/data/VariantData.java", "snippet": "public class VariantData {\n\t@SerializedName(\"\")\n\tpublic VariantData[] variants;\n\n\t@SerializedName(\"model\")\n\tpublic String model;\n\t@SerializedName(\"x\")\n\tpublic int x;\n\t@SerializedName(\"y\")\n\tpublic int y;\n\t@SerializedName(\"uvlock\")\n\tpublic boolean uvlock = false;\n\t@SerializedName(\"weight\")\n\tpublic int weight = 1;\n\t@Override\n\tpublic String toString() {\n\t\tString builder =\n\t\t\t\"model: \" + model + \"\\n\" +\n\t\t\t\"x: \" + x + \"\\n\" +\n\t\t\t\"y: \" + y + \"\\n\" +\n\t\t\t\"uvlock: \" + uvlock + \"\\n\";\n\t\treturn builder;\n\t}\n}" }, { "identifier": "MetaStateInterpreter", "path": "src/main/java/useless/dragonfly/model/blockstates/processed/MetaStateInterpreter.java", "snippet": "public abstract class MetaStateInterpreter {\n\tpublic abstract HashMap<String, String> getStateMap(WorldSource worldSource, int x, int y, int z, Block block, int meta);\n}" }, { "identifier": "NamespaceId", "path": "src/main/java/useless/dragonfly/utilities/NamespaceId.java", "snippet": "public class NamespaceId {\n\tpublic static final String coreNamespaceId = \"minecraft\"; // This is also used as the default namespace if one is not provided\n\tprivate final String namespace;\n\tprivate final String id;\n\tpublic NamespaceId(String namespace, String id){\n\t\tthis.namespace = namespace.toLowerCase();\n\t\tthis.id = id.toLowerCase();\n\t}\n\tpublic String getNamespace(){\n\t\treturn namespace;\n\t}\n\tpublic String getId(){\n\t\treturn id;\n\t}\n\tpublic String toString(){\n\t\treturn (namespace + \":\" + id).toLowerCase();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (obj instanceof String){\n\t\t\treturn this.toString().equals(((String) obj).toLowerCase());\n\t\t}\n\t\tif (obj instanceof NamespaceId){\n\t\t\treturn this.namespace.equals(((NamespaceId) obj).namespace) && this.id.equals(((NamespaceId) obj).id);\n\t\t}\n\t\treturn super.equals(obj);\n\t}\n\t@Override\n\tpublic int hashCode()\n\t{\n\t\treturn toString().hashCode();\n\t}\n\n\tpublic static NamespaceId idFromString(String formattedString){\n\t\tformattedString = formattedString.toLowerCase();\n\t\tString namespace = coreNamespaceId;\n\t\tString id;\n\t\tif (formattedString.contains(\":\")){\n\t\t\tnamespace = formattedString.split(\":\")[0];\n\t\t\tid = formattedString.split(\":\")[1];\n\t\t} else {\n\t\t\tid = formattedString;\n\t\t}\n\n\t\tif (namespace.contains(\":\") || namespace.isEmpty()) throw new IllegalArgumentException(\"Namespace '\" + namespace + \"' is not formatted correctly!\");\n\t\tif (id.contains(\":\") || id.isEmpty()) throw new IllegalArgumentException(\"Id '\" + id + \"' is not formatted correctly!\");\n\n\t\treturn new NamespaceId(namespace, id);\n\t}\n}" } ]
import net.minecraft.client.Minecraft; import net.minecraft.client.render.block.model.BlockModelRenderBlocks; import net.minecraft.core.block.Block; import net.minecraft.core.world.WorldSource; import useless.dragonfly.DragonFly; import useless.dragonfly.helper.ModelHelper; import useless.dragonfly.mixins.mixin.accessor.RenderBlocksAccessor; import useless.dragonfly.model.block.processed.BlockModel; import useless.dragonfly.model.blockstates.data.BlockstateData; import useless.dragonfly.model.blockstates.data.ModelPart; import useless.dragonfly.model.blockstates.data.VariantData; import useless.dragonfly.model.blockstates.processed.MetaStateInterpreter; import useless.dragonfly.utilities.NamespaceId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
4,444
package useless.dragonfly.model.block; public class BlockModelDragonFly extends BlockModelRenderBlocks { public BlockModel baseModel; public boolean render3d; public float renderScale; public BlockstateData blockstateData; public MetaStateInterpreter metaStateInterpreter; public BlockModelDragonFly(BlockModel model) { this(model, null, null,true, 0.25f); } public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d) { this(model, blockstateData, metaStateInterpreter, render3d, 0.25f); } public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d, float renderScale) { super(0); this.baseModel = model; this.render3d = render3d; this.renderScale = renderScale; this.blockstateData = blockstateData; this.metaStateInterpreter = metaStateInterpreter; } @Override public boolean render(Block block, int x, int y, int z) { InternalModel[] models = getModelsFromState(block, x, y, z, false); boolean didRender = false; for (InternalModel model : models) { didRender |= BlockModelRenderer.renderModelNormal(model.model, block, x, y, z, model.rotationX, -model.rotationY); } return didRender; } @Override public boolean renderNoCulling(Block block, int x, int y, int z) { InternalModel[] models = getModelsFromState(block, x, y, z, false); boolean didRender = false; for (InternalModel model : models) { didRender |= BlockModelRenderer.renderModelNoCulling(model.model, block, x, y, z, model.rotationX, -model.rotationY); } return didRender; } @Override public boolean renderWithOverrideTexture(Block block, int x, int y, int z, int textureIndex) { InternalModel[] models = getModelsFromState(block, x, y, z, false); boolean didRender = false; for (InternalModel model : models) { didRender |= BlockModelRenderer.renderModelBlockUsingTexture(model.model, block, x, y, z, textureIndex, model.rotationX, -model.rotationY); } return didRender; } @Override public boolean shouldItemRender3d() { return render3d; } @Override public float getItemRenderScale() { return renderScale; } public InternalModel[] getModelsFromState(Block block, int x, int y, int z, boolean sourceFromWorld){ if (blockstateData == null || metaStateInterpreter == null){ return new InternalModel[]{new InternalModel(baseModel, 0, 0)}; }
package useless.dragonfly.model.block; public class BlockModelDragonFly extends BlockModelRenderBlocks { public BlockModel baseModel; public boolean render3d; public float renderScale; public BlockstateData blockstateData; public MetaStateInterpreter metaStateInterpreter; public BlockModelDragonFly(BlockModel model) { this(model, null, null,true, 0.25f); } public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d) { this(model, blockstateData, metaStateInterpreter, render3d, 0.25f); } public BlockModelDragonFly(BlockModel model, BlockstateData blockstateData, MetaStateInterpreter metaStateInterpreter, boolean render3d, float renderScale) { super(0); this.baseModel = model; this.render3d = render3d; this.renderScale = renderScale; this.blockstateData = blockstateData; this.metaStateInterpreter = metaStateInterpreter; } @Override public boolean render(Block block, int x, int y, int z) { InternalModel[] models = getModelsFromState(block, x, y, z, false); boolean didRender = false; for (InternalModel model : models) { didRender |= BlockModelRenderer.renderModelNormal(model.model, block, x, y, z, model.rotationX, -model.rotationY); } return didRender; } @Override public boolean renderNoCulling(Block block, int x, int y, int z) { InternalModel[] models = getModelsFromState(block, x, y, z, false); boolean didRender = false; for (InternalModel model : models) { didRender |= BlockModelRenderer.renderModelNoCulling(model.model, block, x, y, z, model.rotationX, -model.rotationY); } return didRender; } @Override public boolean renderWithOverrideTexture(Block block, int x, int y, int z, int textureIndex) { InternalModel[] models = getModelsFromState(block, x, y, z, false); boolean didRender = false; for (InternalModel model : models) { didRender |= BlockModelRenderer.renderModelBlockUsingTexture(model.model, block, x, y, z, textureIndex, model.rotationX, -model.rotationY); } return didRender; } @Override public boolean shouldItemRender3d() { return render3d; } @Override public float getItemRenderScale() { return renderScale; } public InternalModel[] getModelsFromState(Block block, int x, int y, int z, boolean sourceFromWorld){ if (blockstateData == null || metaStateInterpreter == null){ return new InternalModel[]{new InternalModel(baseModel, 0, 0)}; }
RenderBlocksAccessor blocksAccessor = (RenderBlocksAccessor) BlockModelRenderer.getRenderBlocks();
2
2023-11-16 01:10:52+00:00
8k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/utils/redisson/lock/LockUtils.java
[ { "identifier": "ReturnCode", "path": "src/main/java/top/sharehome/springbootinittemplate/common/base/ReturnCode.java", "snippet": "@Getter\npublic enum ReturnCode {\n\n /**\n * 操作成功 200\n */\n SUCCESS(HttpStatus.SUCCESS, \"操作成功\"),\n\n /**\n * 操作失败 500\n */\n FAIL(HttpStatus.ERROR, \"操作失败\"),\n\n /**\n * 系统警告 600\n */\n WARN(HttpStatus.WARN, \"系统警告\"),\n\n /**\n * 账户名称校验失败 11000\n */\n USERNAME_VALIDATION_FAILED(11000, \"账户名称校验失败\"),\n\n /**\n * 账户名称已经存在 11001\n */\n USERNAME_ALREADY_EXISTS(11001, \"账户名称已经存在\"),\n\n /**\n * 账户名称包含特殊字符 11002\n */\n PASSWORD_AND_SECONDARY_PASSWORD_NOT_SAME(11002, \"密码和二次密码不相同\"),\n\n /**\n * 密码校验失败 11003\n */\n PASSWORD_VERIFICATION_FAILED(11003, \"密码校验失败\"),\n\n /**\n * 用户基本信息校验失败 11004\n */\n USER_BASIC_INFORMATION_VERIFICATION_FAILED(11004, \"用户基本信息校验失败\"),\n\n /**\n * 用户账户不存在 11005\n */\n USER_ACCOUNT_DOES_NOT_EXIST(11005, \"用户账户不存在\"),\n\n /**\n * 用户账户被封禁 11006\n */\n USER_ACCOUNT_BANNED(11006, \"用户账户被封禁\"),\n\n /**\n * 用户账号或密码错误 11007\n */\n WRONG_USER_ACCOUNT_OR_PASSWORD(11007, \"用户账号或密码错误\"),\n\n /**\n * 用户登录已过期 11008\n */\n USER_LOGIN_HAS_EXPIRED(11008, \"用户登录已过期\"),\n\n /**\n * 用户操作异常 11009\n */\n ABNORMAL_USER_OPERATION(11009, \"用户操作异常\"),\n\n /**\n * 用户设备异常 11010\n */\n ABNORMAL_USER_EQUIPMENT(11010, \"用户设备异常\"),\n\n /**\n * 用户登录验证码为空 11011\n */\n CAPTCHA_IS_EMPTY(11011, \"验证码为空\"),\n\n /**\n * 用户登录验证码已过期 11012\n */\n CAPTCHA_HAS_EXPIRED(11012, \"验证码已过期\"),\n\n /**\n * 用户登录验证码无效 11013\n */\n CAPTCHA_IS_INVALID(11013, \"验证码无效\"),\n\n /**\n * 用户登录验证码无效 11014\n */\n CAPTCHA_IS_INCORRECT(11014, \"验证码错误\"),\n\n /**\n * 用户发出无效请求 11015\n */\n USER_SENT_INVALID_REQUEST(11015, \"用户发出无效请求\"),\n\n /**\n * 手机格式校验失败 12000\n */\n PHONE_FORMAT_VERIFICATION_FAILED(12000, \"手机格式校验失败\"),\n\n /**\n * 邮箱格式校验失败 12001\n */\n EMAIL_FORMAT_VERIFICATION_FAILED(12001, \"邮箱格式校验失败\"),\n\n /**\n * 访问未授权 13000\n */\n ACCESS_UNAUTHORIZED(13000, \"访问未授权\"),\n\n /**\n * 请求必填参数为空 13001\n */\n REQUEST_REQUIRED_PARAMETER_IS_EMPTY(13001, \"请求必填参数为空\"),\n\n /**\n * 参数格式不匹配 13002\n */\n PARAMETER_FORMAT_MISMATCH(13002, \"参数格式不匹配\"),\n\n /**\n * 用户请求次数太多 13003\n */\n TOO_MANY_REQUESTS(13003, \"用户请求次数太多\"),\n\n /**\n * 用户上传文件异常 14000\n */\n FILE_UPLOAD_EXCEPTION(14000, \"用户上传文件异常\"),\n\n /**\n * 用户没有上传文件 14001\n */\n USER_DO_NOT_UPLOAD_FILE(14001, \"用户没有上传文件\"),\n\n /**\n * 用户上传文件类型不匹配 14002\n */\n USER_UPLOADED_FILE_TYPE_MISMATCH(14002, \"用户上传文件类型不匹配\"),\n\n /**\n * 用户上传文件太大 14003\n */\n USER_UPLOADED_FILE_IS_TOO_LARGE(14003, \"用户上传文件太大\"),\n\n /**\n * 用户上传图片太大 14004\n */\n USER_UPLOADED_IMAGE_IS_TOO_LARGE(14004, \"用户上传图片太大\"),\n\n /**\n * 用户上传视频太大 14005\n */\n USER_UPLOADED_VIDEO_IS_TOO_LARGE(14005, \"用户上传视频太大\"),\n\n /**\n * 用户上传压缩文件太大 14006\n */\n USER_UPLOADED_ZIP_IS_TOO_LARGE(14006, \"用户上传压缩文件太大\"),\n\n /**\n * 用户文件地址异常 14007\n */\n USER_FILE_ADDRESS_IS_ABNORMAL(14007, \"用户文件地址异常\"),\n\n /**\n * 用户文件删除异常 14008\n */\n USER_FILE_DELETION_IS_ABNORMAL(14008, \"用户文件删除异常\"),\n\n /**\n * 系统文件地址异常 14009\n */\n SYSTEM_FILE_ADDRESS_IS_ABNORMAL(14007, \"系统文件地址异常\"),\n\n /**\n * 邮件发送异常 15000\n */\n EMAIL_WAS_SENT_ABNORMALLY(15000, \"邮件发送异常\"),\n\n /**\n * 数据库服务出错 20000\n */\n ERRORS_OCCURRED_IN_THE_DATABASE_SERVICE(20000, \"数据库服务出错\"),\n\n /**\n * 消息中间件服务出错 30000\n */\n MQ_SERVICE_ERROR(30000, \"消息中间件服务出错\"),\n\n /**\n * 内存数据库服务出错 30001\n */\n MAIN_MEMORY_DATABASE_SERVICE_ERROR(30001, \"内存数据库服务出错\"),\n\n /**\n * 搜索引擎服务出错 30002\n */\n SEARCH_ENGINE_SERVICE_ERROR(30002, \"搜索引擎服务出错\"),\n\n /**\n * 网关服务出错 30003\n */\n GATEWAY_SERVICE_ERROR(30003, \"网关服务出错\"),\n\n /**\n * 分布式锁服务出错 30004\n */\n LOCK_SERVICE_ERROR(30004, \"分布式锁服务出错\"),\n\n /**\n * 分布式锁设计出错 30005\n */\n LOCK_DESIGN_ERROR(30005, \"分布式锁设计出错\");\n\n final private int code;\n\n final private String msg;\n\n ReturnCode(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n}" }, { "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,可在任意代码中取出ApplicaitonContext.\n */\n private static ApplicationContext context;\n\n /**\n * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.\n */\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n SpringContextHolder.context = applicationContext;\n }\n\n /**\n * 获取applicationContext\n *\n * @return 返回结果\n */\n public ApplicationContext getApplicationContext() {\n return context;\n }\n\n /**\n * 通过name获取 Bean.\n *\n * @param name Bean名称\n * @return 返回结果\n */\n public static Object getBean(String name) {\n return context.getBean(name);\n }\n\n /**\n * 通过class获取Bean.\n *\n * @param clazz Bean类\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> Map<String, T> getBeans(Class<T> clazz) {\n return context.getBeansOfType(clazz);\n }\n\n /**\n * 通过class获取Bean.\n *\n * @param clazz Bean类\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> T getBean(Class<T> clazz) {\n return context.getBean(clazz);\n }\n\n /**\n * 通过name,以及Clazz返回指定的Bean\n *\n * @param name Bean名称\n * @param clazz Bean类\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> T getBean(String name, Class<T> clazz) {\n return context.getBean(name, clazz);\n }\n\n /**\n * 依赖注入日志输出\n */\n @PostConstruct\n private void initDi() {\n log.info(\"############ {} Configuration DI.\", this.getClass().getSimpleName());\n }\n\n}" }, { "identifier": "CustomizeLockException", "path": "src/main/java/top/sharehome/springbootinittemplate/exception/customize/CustomizeLockException.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class CustomizeLockException extends RuntimeException {\n\n private ReturnCode returnCode;\n\n private String msg;\n\n public <T> CustomizeLockException() {\n this.returnCode = ReturnCode.FAIL;\n this.msg = ReturnCode.FAIL.getMsg();\n }\n\n public <T> CustomizeLockException(ReturnCode returnCode) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg();\n }\n\n public <T> CustomizeLockException(ReturnCode returnCode, String msg) {\n this.returnCode = returnCode;\n this.msg = returnCode.getMsg() + \" ==> [\" + msg + \"]\";\n }\n\n @Override\n public String getMessage() {\n return this.msg;\n }\n\n}" }, { "identifier": "KeyPrefixConstants", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/redisson/KeyPrefixConstants.java", "snippet": "public interface KeyPrefixConstants {\n\n /**\n * 不带有类型的缓存Key前缀\n */\n String CACHE_KEY_PREFIX = \"CACHE_\";\n\n /**\n * String类型的缓存Key前准\n */\n String STRING_PREFIX = CACHE_KEY_PREFIX + \"STRING_\";\n\n /**\n * Number类型的缓存Key前准\n */\n String NUMBER_PREFIX = CACHE_KEY_PREFIX + \"NUMBER_\";\n\n /**\n * List类型的缓存Key前缀\n */\n String LIST_PREFIX = CACHE_KEY_PREFIX + \"LIST_\";\n\n /**\n * Set类型的缓存Key前缀\n */\n String SET_PREFIX = CACHE_KEY_PREFIX + \"SET_\";\n\n /**\n * Map类型的缓存Key前缀\n */\n String MAP_PREFIX = CACHE_KEY_PREFIX + \"MAP_\";\n\n /**\n * 系统限流Key前缀\n */\n String SYSTEM_RATE_LIMIT_PREFIX = \"SYSTEM_RATE_\";\n\n /**\n * 自定义限流Key前缀\n */\n String CUSTOMIZE_RATE_LIMIT_PREFIX = \"CUSTOMIZE_RATE_\";\n\n /**\n * 分布式锁Key前缀\n */\n String LOCK_PREFIX = \"LOCK_\";\n\n /**\n * 验证码Key前缀\n */\n String CAPTCHA_PREFIX = \"CAPTCHA_\";\n\n}" }, { "identifier": "SuccessFunction", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/redisson/lock/function/SuccessFunction.java", "snippet": "@FunctionalInterface\npublic interface SuccessFunction {\n\n void method();\n\n}" }, { "identifier": "VoidFunction", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/redisson/lock/function/VoidFunction.java", "snippet": "@FunctionalInterface\npublic interface VoidFunction {\n\n void method();\n\n}" } ]
import lombok.extern.slf4j.Slf4j; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeLockException; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import top.sharehome.springbootinittemplate.utils.redisson.lock.function.SuccessFunction; import top.sharehome.springbootinittemplate.utils.redisson.lock.function.VoidFunction; import java.util.concurrent.TimeUnit; import java.util.function.Supplier;
4,838
package top.sharehome.springbootinittemplate.utils.redisson.lock; /** * 分布式锁工具类 * 工具类中包含三种情况,在使用时针对同一业务逻辑或线程建议采纳相同的情况: * 1、无论获取锁成功与否均无返回值 * 2、无论获取锁成功与否均带有boolean类型返回值 * 3、无论获取锁成功与否均带有自定义类型返回值 * 使用该工具类之前需要了解工具类中所设计和涉及的一些概念: * 1、看门狗释放:看门狗是Redisson分布式锁中设计的一个防宕机死锁机制,宕机死锁指获取锁之后程序没有释放锁就停止运行而导致其他程序拿不到锁的情况, * 看门狗机制就起到一个监听程序健康状态的作用,默认宕机30秒后自动释放锁。 * 2、自动释放:自动释放需要靠开发者自定义自动释放时间,只要没有设定该时间,那么这个锁就采用看门狗释放,自动释放的存在可提高代码可自定义性,但是 * 容易产生异常,比如A、B线程均需要运行10s,A线程先运行,B线程等待锁,在5s时A线程自动释放了锁,B线程立即拿到锁开始运行,在10s时A结束运行,工 * 具类代码逻辑要求A线程释放锁,但是锁在B线程上,所以就会报出异常,或许一些业务需要以上所描述的逻辑,但是这里为了保持以锁为中心的工具类,强制要 * 求获取锁和释放锁必须在同一线程中操作,即A线程不能释放B线程的锁,如果开发者诚心想实现上述逻辑,请自己编写相关代码,建议使用Redisson缓存或者 * 延迟队列。 * 3、同步等待:同步等待主要针对于“无论获取锁成功与否均无返回值”的情况,因为通过传参没有判断处理该线程是否获取得到锁,所以使用此类方法,多个线程 * 是同步执行的,执行次序取决于线程抢占锁的能力,越强越先执行。 * 4、不可等待:不可等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中不含有waitTime形参的情况,其实它是同步等待的一种,只不 * 过此类方法能够处理或者忽略没获取到锁的情况,即拿不到锁就不拿,所以不用等待锁也能执行业务逻辑。 * 5、自定义等待:自定义等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中含有waitTime形参的情况,主要是考虑到网络原因和其他 * 外部因素,如果比较偏向于获取锁成功所要执行的操作,可以在此类方法中设置合理的等待时间,总之自定义等待完全依赖业务逻辑的需求。 * * @author AntonyCheng */ @Slf4j public class LockUtils { /** * 被封装的redisson客户端对象 */ private static final RedissonClient REDISSON_CLIENT = SpringContextHolder.getBean(RedissonClient.class); /** * 无论获取锁成功与否均无返回值,看门狗释放型,同步等待分布式锁 * * @param key 锁键值 * @param eventFunc 获取锁之后的操作 */ public static void lockEvent(String key, VoidFunction eventFunc) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); try { lock.lock(); eventFunc.method(); } finally { if (lock.isLocked()) { lock.unlock(); } } } /** * 无论获取锁成功与否均无返回值,自动释放型,同步等待分布式锁 * * @param key 锁键值 * @param leaseTime 自动释放时间/ms * @param eventFunc 执行的操作 */ public static void lockEvent(String key, long leaseTime, VoidFunction eventFunc) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); try { lock.lock(leaseTime, TimeUnit.MILLISECONDS); eventFunc.method(); } finally { if (lock.isLocked()) { lock.unlock(); } } } /** * 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,不可等待分布式锁 * * @param key 锁键值 * @param success 获取锁成功的操作 * @return 返回结果 */ public static boolean lockEvent(String key, SuccessFunction success) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); boolean lockResult = false; try { lockResult = lock.tryLock(); if (lockResult) { success.method(); } } finally { if (lockResult) { if (lock.isLocked()) { lock.unlock(); } } } return lockResult; } /** * 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,自定义等待分布式锁 * * @param key 锁键值 * @param waitTime 最大等待时间/ms * @param success 获取锁成功的操作 * @return 返回结果 */ public static boolean lockEvent(String key, long waitTime, SuccessFunction success) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); boolean lockResult = false; try { lockResult = lock.tryLock(waitTime, TimeUnit.MILLISECONDS); if (lockResult) { success.method(); } } catch (InterruptedException e) {
package top.sharehome.springbootinittemplate.utils.redisson.lock; /** * 分布式锁工具类 * 工具类中包含三种情况,在使用时针对同一业务逻辑或线程建议采纳相同的情况: * 1、无论获取锁成功与否均无返回值 * 2、无论获取锁成功与否均带有boolean类型返回值 * 3、无论获取锁成功与否均带有自定义类型返回值 * 使用该工具类之前需要了解工具类中所设计和涉及的一些概念: * 1、看门狗释放:看门狗是Redisson分布式锁中设计的一个防宕机死锁机制,宕机死锁指获取锁之后程序没有释放锁就停止运行而导致其他程序拿不到锁的情况, * 看门狗机制就起到一个监听程序健康状态的作用,默认宕机30秒后自动释放锁。 * 2、自动释放:自动释放需要靠开发者自定义自动释放时间,只要没有设定该时间,那么这个锁就采用看门狗释放,自动释放的存在可提高代码可自定义性,但是 * 容易产生异常,比如A、B线程均需要运行10s,A线程先运行,B线程等待锁,在5s时A线程自动释放了锁,B线程立即拿到锁开始运行,在10s时A结束运行,工 * 具类代码逻辑要求A线程释放锁,但是锁在B线程上,所以就会报出异常,或许一些业务需要以上所描述的逻辑,但是这里为了保持以锁为中心的工具类,强制要 * 求获取锁和释放锁必须在同一线程中操作,即A线程不能释放B线程的锁,如果开发者诚心想实现上述逻辑,请自己编写相关代码,建议使用Redisson缓存或者 * 延迟队列。 * 3、同步等待:同步等待主要针对于“无论获取锁成功与否均无返回值”的情况,因为通过传参没有判断处理该线程是否获取得到锁,所以使用此类方法,多个线程 * 是同步执行的,执行次序取决于线程抢占锁的能力,越强越先执行。 * 4、不可等待:不可等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中不含有waitTime形参的情况,其实它是同步等待的一种,只不 * 过此类方法能够处理或者忽略没获取到锁的情况,即拿不到锁就不拿,所以不用等待锁也能执行业务逻辑。 * 5、自定义等待:自定义等待主要针对于“无论获取锁成功与否均带有自定义/boolean类型返回值”中含有waitTime形参的情况,主要是考虑到网络原因和其他 * 外部因素,如果比较偏向于获取锁成功所要执行的操作,可以在此类方法中设置合理的等待时间,总之自定义等待完全依赖业务逻辑的需求。 * * @author AntonyCheng */ @Slf4j public class LockUtils { /** * 被封装的redisson客户端对象 */ private static final RedissonClient REDISSON_CLIENT = SpringContextHolder.getBean(RedissonClient.class); /** * 无论获取锁成功与否均无返回值,看门狗释放型,同步等待分布式锁 * * @param key 锁键值 * @param eventFunc 获取锁之后的操作 */ public static void lockEvent(String key, VoidFunction eventFunc) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); try { lock.lock(); eventFunc.method(); } finally { if (lock.isLocked()) { lock.unlock(); } } } /** * 无论获取锁成功与否均无返回值,自动释放型,同步等待分布式锁 * * @param key 锁键值 * @param leaseTime 自动释放时间/ms * @param eventFunc 执行的操作 */ public static void lockEvent(String key, long leaseTime, VoidFunction eventFunc) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); try { lock.lock(leaseTime, TimeUnit.MILLISECONDS); eventFunc.method(); } finally { if (lock.isLocked()) { lock.unlock(); } } } /** * 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,不可等待分布式锁 * * @param key 锁键值 * @param success 获取锁成功的操作 * @return 返回结果 */ public static boolean lockEvent(String key, SuccessFunction success) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); boolean lockResult = false; try { lockResult = lock.tryLock(); if (lockResult) { success.method(); } } finally { if (lockResult) { if (lock.isLocked()) { lock.unlock(); } } } return lockResult; } /** * 无论获取锁成功与否均带有boolean类型返回值,看门狗释放型,自定义等待分布式锁 * * @param key 锁键值 * @param waitTime 最大等待时间/ms * @param success 获取锁成功的操作 * @return 返回结果 */ public static boolean lockEvent(String key, long waitTime, SuccessFunction success) { RLock lock = REDISSON_CLIENT.getLock(KeyPrefixConstants.LOCK_PREFIX + key); boolean lockResult = false; try { lockResult = lock.tryLock(waitTime, TimeUnit.MILLISECONDS); if (lockResult) { success.method(); } } catch (InterruptedException e) {
throw new CustomizeLockException(ReturnCode.LOCK_SERVICE_ERROR);
2
2023-11-12 07:49:59+00:00
8k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/VertexBatch.java
[ { "identifier": "AttribType", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/AttribType.java", "snippet": "public enum AttribType {\n /** GLSL {@code float} */\n FLOAT(1),\n /** GLSL {@code vec2} */\n VEC2(2),\n /** GLSL {@code vec3} */\n VEC3(3),\n /** GLSL {@code vec4} */\n VEC4(4);\n\n private final int elemCount;\n\n AttribType(int elemCount) {\n this.elemCount = elemCount;\n }\n\n /**\n * Gets the number of values within this type.\n *\n * @return element count\n */\n public int getElemCount() {\n return elemCount;\n }\n\n /**\n * Gets the size of this type in bytes.\n *\n * @return size in bytes\n */\n public int sizeOf() {\n return elemCount * SizeOf.FLOAT;\n }\n}" }, { "identifier": "MeshData", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/MeshData.java", "snippet": "public final class MeshData implements SafeCloseable {\n private static final int INITIAL_CAPACITY = 16;\n\n private final PrimitiveType primType;\n private final VertexLayout layout;\n private int layoutElemIdx;\n\n private ByteBuffer vertexBuf;\n private final List<Integer> indices;\n private int mark;\n private boolean finished;\n private int finalVertexCount;\n\n /**\n * Creates a new data buffer with the specified layout.\n *\n * @param primType type of primitive to render\n * @param layout layout of the vertex data\n */\n public MeshData(PrimitiveType primType, AttribType... layout) {\n this(primType, new VertexLayout(layout));\n }\n\n /**\n * Creates a new data buffer with the specified layout.\n *\n * @param primType type of primitive to render\n * @param layout layout of the vertex data\n */\n public MeshData(PrimitiveType primType, VertexLayout layout) {\n this.primType = primType;\n this.layout = layout;\n layoutElemIdx = 0;\n\n indices = new ArrayList<>();\n mark = 0;\n finished = false;\n\n vertexBuf = MemoryUtil.memAlloc(INITIAL_CAPACITY * layout.sizeOf());\n }\n\n private void ensureSpace(int spaceBytes) {\n if (vertexBuf.remaining() < spaceBytes) {\n int cap = vertexBuf.capacity();\n vertexBuf = MemoryUtil.memRealloc(vertexBuf, Math.max(cap + spaceBytes, cap * 2));\n }\n }\n\n private void prepare(AttribType type) {\n AttribType[] types = layout.getTypes();\n\n ensureSpace(type.sizeOf());\n AttribType layoutType = types[layoutElemIdx++];\n if (layoutType != type)\n throw new IllegalStateException(\"Incorrect attribute added for format (added \" + type + \", layout specifies \" + layoutType + \")\");\n if (layoutElemIdx >= types.length)\n layoutElemIdx = 0;\n }\n\n /**\n * Marks the current position. The mark position is added to\n * indices added after this is called.\n *\n * @return this\n */\n public MeshData mark() {\n mark = getVertexCount();\n return this;\n }\n\n /**\n * Adds a {@code float} value.\n *\n * @param f value to add\n * @return this\n */\n public MeshData putFloat(float f) {\n prepare(AttribType.FLOAT);\n vertexBuf.putFloat(f);\n return this;\n }\n\n /**\n * Adds a {@code vec2} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec2(Vector2f vec) {\n return putVec2(vec.x, vec.y);\n }\n\n /**\n * Adds a {@code vec2} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @return this\n */\n public MeshData putVec2(float x, float y) {\n prepare(AttribType.VEC2);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n return this;\n }\n\n /**\n * Adds a {@code vec3} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec3(Vector3f vec) {\n return putVec3(vec.x, vec.y, vec.z);\n }\n\n /**\n * Adds a {@code vec3} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @param z z coordinate of the value\n * @return this\n */\n public MeshData putVec3(float x, float y, float z) {\n prepare(AttribType.VEC3);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n vertexBuf.putFloat(z);\n return this;\n }\n\n /**\n * Adds a {@code vec4} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec4(Vector4f vec) { return putVec4(vec.x, vec.y, vec.z, vec.w); }\n\n /**\n * Adds a {@code vec4} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @param z z coordinate of the value\n * @param w w coordinate of the value\n * @return this\n */\n public MeshData putVec4(float x, float y, float z, float w) {\n prepare(AttribType.VEC4);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n vertexBuf.putFloat(z);\n vertexBuf.putFloat(w);\n return this;\n }\n\n /**\n * Adds an index to the index array. The index is added to the mark\n * position before adding it.\n *\n * @param i the index to add\n * @return this\n */\n public MeshData index(int i) {\n indices.add(mark + i);\n return this;\n }\n\n /**\n * Adds several indices to the index array. This is equivalent to calling\n * {@link #index(int)} for each index.\n * @param indices indices to add\n * @return this\n */\n public MeshData indices(int... indices) {\n for (int i : indices) {\n this.indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Adds several indices to the index array. This is equivalent to calling\n * {@link #index(int)} for each index.\n * @param indices indices to add\n * @return this\n */\n public MeshData indices(List<Integer> indices) {\n for (int i : indices) {\n this.indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Appends another mesh data buffer to this. This will not modify the\n * source buffer.\n *\n * @param other mesh data to append\n * @return this\n */\n public MeshData append(MeshData other) {\n if (primType != other.primType)\n throw new IllegalArgumentException(\"Can only append data with same primitive type\");\n if (!layout.equals(other.layout))\n throw new IllegalArgumentException(\"Can only append data with same layout\");\n\n // Make sure our buffer is big enough\n ensureSpace(other.vertexBuf.position());\n\n mark();\n\n // Back up other buffer's bounds\n int posTmp = other.vertexBuf.position();\n int limitTmp = other.vertexBuf.limit();\n\n // Copy in the data\n other.vertexBuf.flip();\n vertexBuf.put(other.vertexBuf);\n\n // Restore backed up bounds\n other.vertexBuf.position(posTmp);\n other.vertexBuf.limit(limitTmp);\n\n // Copy indices with mark applied\n for (int i : other.indices) {\n indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Marks this data as finished, so no other data can be added.\n *\n * @return this\n */\n public MeshData finish() {\n if (finished) throw new IllegalStateException(\"Already finished\");\n finalVertexCount = getVertexCount();\n finished = true;\n vertexBuf.flip();\n return this;\n }\n\n /**\n * Gets the native data buffer. Do not free the returned buffer.\n *\n * @return vertex buffer\n */\n public ByteBuffer getVertexBuf() {\n if (!finished)\n finish();\n return vertexBuf;\n }\n\n /**\n * Gets the vertex layout this mesh data uses.\n *\n * @return layout\n */\n public VertexLayout getVertexLayout() {\n return layout;\n }\n\n /**\n * Gets the number of vertices in this data.\n *\n * @return vertex count\n */\n public int getVertexCount() {\n if (finished) return finalVertexCount;\n return vertexBuf.position() / layout.sizeOf();\n }\n\n /**\n * Gets the index array in this data.\n *\n * @return indices\n */\n public List<Integer> getIndices() {\n return indices;\n }\n\n /**\n * Gets the primitive type the vertices should be rendered as.\n *\n * @return primitive type\n */\n public PrimitiveType getPrimitiveType() {\n return primType;\n }\n\n /**\n * Gets the current mark position.\n *\n * @return mark\n */\n public int getMark() {\n return mark;\n }\n\n @Override\n public void close() {\n MemoryUtil.memFree(vertexBuf);\n }\n}" }, { "identifier": "PrimitiveType", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/PrimitiveType.java", "snippet": "public enum PrimitiveType {\n /** Each vertex is its own individual point. */\n POINTS,\n\n /** The points are connected with lines. */\n LINE_STRIP,\n\n /**\n * The points are connected with lines, and the last is connected to the\n * first.\n */\n LINE_LOOP,\n\n /** Each set of two vertices form the endpoints of a line. */\n LINES,\n\n /**\n * Each vertex forms a triangle with itself and the previous two vertices.\n */\n TRIANGLE_STRIP,\n\n /**\n * Each vertex forms a triangle with itself, the previous vertex, and the\n * first vertex.\n */\n TRIANGLE_FAN,\n\n /** Each set of three vertices form an individual triangle. */\n TRIANGLES\n}" }, { "identifier": "VertexLayout", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/VertexLayout.java", "snippet": "public final class VertexLayout {\n private final AttribType[] types;\n private final int sizeOf;\n\n /**\n * Creates a new layout of the specified attribute types.\n *\n * @param types vertex attribute types\n */\n public VertexLayout(AttribType... types) {\n this.types = types;\n\n int sz = 0;\n for (AttribType type : types)\n sz += type.sizeOf();\n sizeOf = sz;\n }\n\n /**\n * Gets the attribute types in this layout.\n *\n * @return types\n */\n public AttribType[] getTypes() {\n return types;\n }\n\n /**\n * Gets the total size of one vertex in bytes.\n *\n * @return size of vertex in bytes\n */\n public int sizeOf() {\n return sizeOf;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n VertexLayout that = (VertexLayout) o;\n return sizeOf == that.sizeOf &&\n Arrays.equals(types, that.types);\n }\n\n @Override\n public int hashCode() {\n int result = Objects.hash(sizeOf);\n result = 31 * result + Arrays.hashCode(types);\n return result;\n }\n}" }, { "identifier": "Texture2D", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/texture/Texture2D.java", "snippet": "public interface Texture2D extends Texture, Texture2DRegion {\n /**\n * Uploads a set of bitmap data to the GPU.\n *\n * @param data data to upload\n */\n void setData(BitmapRegion data);\n\n /**\n * Sets a section of the texture data on GPU, leaving the rest the same.\n *\n * @param data data to upload\n * @param x x coordinate to upload into\n * @param y y coordinate to upload into\n */\n void setSubData(BitmapRegion data, int x, int y);\n\n @Override\n default Texture2D getSourceTexture() {\n return this;\n }\n\n @Override\n default Vector2f getRegionTopLeftUV() {\n return new Vector2f(0, 0);\n }\n\n @Override\n default Vector2f getRegionBottomRightUV() {\n return new Vector2f(1, 1);\n }\n}" }, { "identifier": "Texture2DRegion", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/texture/Texture2DRegion.java", "snippet": "public interface Texture2DRegion {\n /**\n * Gets the texture this region is a part of.\n *\n * @return the source texture\n */\n Texture2D getSourceTexture();\n\n /**\n * Gets the top-left UV coordinates of the region in the source texture.\n *\n * @return top-left UV\n */\n Vector2f getRegionTopLeftUV();\n\n /**\n * Gets the bottom-right UV coordinates of the region in the source texture.\n *\n * @return bottom-right UV\n */\n Vector2f getRegionBottomRightUV();\n\n /**\n * Gets a sub-region of this texture. The positions specified here are\n * fractions from 0 to 1 of this region.\n *\n * @param leftX left x position fraction\n * @param topY top y position fraction\n * @param rightX right x position fraction\n * @param bottomY bottom y position fraction\n * @return the sub-region\n */\n default Texture2DRegion getSubRegion(float leftX, float topY, float rightX, float bottomY) {\n Vector2f min = getRegionTopLeftUV();\n Vector2f max = getRegionBottomRightUV();\n\n return new SubTexture2D(\n getSourceTexture(),\n new Vector2f(MathUtil.lerp(min.x, max.x, leftX), MathUtil.lerp(min.y, max.y, topY)),\n new Vector2f(MathUtil.lerp(min.x, max.x, rightX), MathUtil.lerp(min.y, max.y, bottomY))\n );\n }\n\n /**\n * Gets a view of the region reflected over the X axis\n * @return flipped region\n */\n default Texture2DRegion getFlippedX() {\n Vector2f min = getRegionTopLeftUV();\n Vector2f max = getRegionBottomRightUV();\n return new SubTexture2D(\n getSourceTexture(),\n new Vector2f(min.x, max.y),\n new Vector2f(max.x, min.y)\n );\n }\n\n /**\n * Gets a view of the region reflected over the Y axis\n * @return flipped region\n */\n default Texture2DRegion getFlippedY() {\n Vector2f min = getRegionTopLeftUV();\n Vector2f max = getRegionBottomRightUV();\n return new SubTexture2D(\n getSourceTexture(),\n new Vector2f(max.x, min.y),\n new Vector2f(min.x, max.y)\n );\n }\n}" } ]
import com.github.rmheuer.azalea.render.mesh.AttribType; import com.github.rmheuer.azalea.render.mesh.MeshData; import com.github.rmheuer.azalea.render.mesh.PrimitiveType; import com.github.rmheuer.azalea.render.mesh.VertexLayout; import com.github.rmheuer.azalea.render.texture.Texture2D; import com.github.rmheuer.azalea.render.texture.Texture2DRegion; import java.util.List;
4,141
package com.github.rmheuer.azalea.render2d; /** * A batch of vertices to draw. */ final class VertexBatch { /** * The layout of the generated vertex data. */ public static final VertexLayout LAYOUT = new VertexLayout(
package com.github.rmheuer.azalea.render2d; /** * A batch of vertices to draw. */ final class VertexBatch { /** * The layout of the generated vertex data. */ public static final VertexLayout LAYOUT = new VertexLayout(
AttribType.VEC3, // Position
0
2023-11-16 04:46:53+00:00
8k
Shushandr/offroad
src/net/osmand/map/WorldRegion.java
[ { "identifier": "LatLon", "path": "src/net/osmand/data/LatLon.java", "snippet": "@XmlRootElement\npublic class LatLon implements Serializable {\n\tpublic void setLongitude(double pLongitude) {\n\t\tlongitude = pLongitude;\n\t}\n\n\tpublic void setLatitude(double pLatitude) {\n\t\tlatitude = pLatitude;\n\t}\n\tprivate double longitude;\n\tprivate double latitude;\n\n\tpublic LatLon() {\n\t}\n\t\n\tpublic LatLon(double latitude, double longitude) {\n\t\tthis.latitude = latitude;\n\t\tthis.longitude = longitude;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tint temp;\n\t\ttemp = (int)Math.floor(latitude * 10000);\n\t\tresult = prime * result + temp;\n\t\ttemp = (int)Math.floor(longitude * 10000);\n\t\tresult = prime * result + temp;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\n\t\tLatLon other = (LatLon) obj;\n\t\treturn Math.abs(latitude - other.latitude) < 0.00001\n\t\t\t\t&& Math.abs(longitude - other.longitude) < 0.00001;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Lat \" + ((float)latitude) + \" Lon \" + ((float)longitude); //$NON-NLS-1$ //$NON-NLS-2$\n\t}\n\n\tpublic double getLatitude() {\n\t\treturn latitude;\n\t}\n\n\tpublic double getLongitude() {\n\t\treturn longitude;\n\t}\n\n\tpublic int get31TileNumberX() {\n\t\treturn MapUtils.get31TileNumberX(longitude);\n\t}\n\tpublic int get31TileNumberY() {\n\t\treturn MapUtils.get31TileNumberY(latitude);\n\t}\n\n}" }, { "identifier": "Algorithms", "path": "src/net/osmand/util/Algorithms.java", "snippet": "public class Algorithms {\n\tprivate static final int BUFFER_SIZE = 1024;\n\tprivate static final Log log = PlatformUtil.getLog(Algorithms.class);\n\t\n\tpublic static boolean isEmpty(String s){\n\t\treturn s == null || s.length() == 0;\n\t}\n\n\tpublic static boolean stringsEqual(String s1, String s2) {\n\t\tif (s1 == null && s2 == null) {\n\t\t\treturn true;\n\t\t} else if (s1 == null) {\n\t\t\treturn false;\n\t\t} else if (s2 == null) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn s2.equals(s1);\n\t\t}\n\t}\n\n\tpublic static long parseLongSilently(String input, long def) {\n\t\tif(input != null && input.length() > 0) {\n\t\t\ttry {\n\t\t\t\treturn Long.parseLong(input);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\treturn def;\n\t\t\t}\n\t\t}\n\t\treturn def;\n\t}\n\t\n\t\n\tpublic static String getFileNameWithoutExtension(File f) {\n\t\tString name = f.getName();\n\t\tint i = name.indexOf('.');\n\t\tif(i >= 0) {\n\t\t\tname = name.substring(0, i);\n\t\t}\n\t\treturn name;\n\t}\n\t\n\t\n\t\n\tpublic static File[] getSortedFilesVersions(File dir){\n\t\tFile[] listFiles = dir.listFiles();\n\t\tif (listFiles != null) {\n\t\t\tArrays.sort(listFiles, getFileVersionComparator());\n\t\t}\n\t\treturn listFiles;\n\t}\n\n\tpublic static Comparator<File> getFileVersionComparator() {\n\t\treturn new Comparator<File>() {\n\t\t\t@Override\n\t\t\tpublic int compare(File o1, File o2) {\n\t\t\t\treturn -simplifyFileName(o1.getName()).compareTo(simplifyFileName(o2.getName()));\n\t\t\t}\n\t\t\t\n\t\t\tpublic String simplifyFileName(String fn) {\n\t\t\t\tString lc = fn.toLowerCase();\n\t\t\t\tif (lc.indexOf(\".\") != -1) {\n\t\t\t\t\tlc = lc.substring(0, lc.indexOf(\".\"));\n\t\t\t\t}\n\t\t\t\tif (lc.endsWith(\"_2\")) {\n\t\t\t\t\tlc = lc.substring(0, lc.length() - \"_2\".length());\n\t\t\t\t}\n\t\t\t\tboolean hasTimestampEnd = false;\n\t\t\t\tfor(int i = 0; i < lc.length(); i++) {\n\t\t\t\t\tif(lc.charAt(i) >= '0' && lc.charAt(i) <= '9') {\n\t\t\t\t\t\thasTimestampEnd = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(!hasTimestampEnd) {\n\t\t\t\t\tlc += \"_00_00_00\";\n\t\t\t\t}\n\t\t\t\treturn lc;\n\t\t\t}\n\t\t};\n\t}\n\t\n\tprivate static final char CHAR_TOSPLIT = 0x01;\n\n\tpublic static Map<String, String> decodeMap(String s) {\n\t\tif (isEmpty(s)) {\n\t\t\treturn Collections.emptyMap();\n\t\t}\n\t\tMap<String, String> names = new HashMap<String, String>();\n\t\tString[] split = s.split(CHAR_TOSPLIT + \"\");\n\t\t// last split is an empty string\n\t\tfor (int i = 1; i < split.length; i += 2) {\n\t\t\tnames.put(split[i - 1], split[i]);\n\t\t}\n\t\treturn names;\n\t}\n\t\n\tpublic static String encodeMap(Map<String, String> names) {\n\t\tif (names != null) {\n\t\t\tIterator<Entry<String, String>> it = names.entrySet().iterator();\n\t\t\tStringBuilder bld = new StringBuilder();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tEntry<String, String> e = it.next();\n\t\t\t\tbld.append(e.getKey()).append(CHAR_TOSPLIT)\n\t\t\t\t\t\t.append(e.getValue().replace(CHAR_TOSPLIT, (char)(CHAR_TOSPLIT + 1)));\n\t\t\t\tbld.append(CHAR_TOSPLIT);\n\t\t\t}\n\t\t\treturn bld.toString();\n\t\t}\n\t\treturn \"\";\n\t}\n\t\n\tpublic static int findFirstNumberEndIndex(String value) {\n\t\tint i = 0;\n\t\tboolean valid = false;\n\t\tif (value.length() > 0 && value.charAt(0) == '-') {\n\t\t\ti++;\n\t\t}\n\t\twhile (i < value.length() && (isDigit(value.charAt(i)) || value.charAt(i) == '.')) {\n\t\t\ti++;\n\t\t\tvalid = true;\n\t\t}\n\t\tif (valid) {\n\t\t\treturn i;\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t}\n\t\n\tpublic static boolean isDigit(char charAt) {\n\t\treturn charAt >= '0' && charAt <= '9';\n\t}\n\n\t/**\n\t * Determine whether a file is a ZIP File.\n\t */\n\tpublic static boolean isZipFile(File file) throws IOException {\n\t\tif (file.isDirectory()) {\n\t\t\treturn false;\n\t\t}\n\t\tif (!file.canRead()) {\n\t\t\tthrow new IOException(\"Cannot read file \" + file.getAbsolutePath());\n\t\t}\n\t\tif (file.length() < 4) {\n\t\t\treturn false;\n\t\t}\n\t\tFileInputStream in = new FileInputStream(file);\n\t\tint test = readInt(in);\n\t\tin.close();\n\t\treturn test == 0x504b0304;\n\t}\n\t\n\tprivate static final int readInt(InputStream in) throws IOException {\n int ch1 = in.read();\n int ch2 = in.read();\n int ch3 = in.read();\n int ch4 = in.read();\n if ((ch1 | ch2 | ch3 | ch4) < 0)\n throw new EOFException();\n return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + ch4);\n }\n\t\n\tpublic static String capitalizeFirstLetterAndLowercase(String s) {\n\t\tif (s != null && s.length() > 1) {\n\t\t\t// not very efficient algorithm\n\t\t\treturn Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase();\n\t\t} else {\n\t\t\treturn s;\n\t\t}\n\t}\n\t\n\t\n\tpublic static boolean objectEquals(Object a, Object b){\n\t\tif(a == null){\n\t\t\treturn b == null;\n\t\t} else {\n\t\t\treturn a.equals(b);\n\t\t}\n\t}\n\t\n\t\n\t/**\n \t* Parse the color string, and return the corresponding color-int.\n \t* If the string cannot be parsed, throws an IllegalArgumentException\n \t* exception. Supported formats are:\n \t* #RRGGBB\n \t* #AARRGGBB\n \t* 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta',\n \t* 'yellow', 'lightgray', 'darkgray'\n \t*/\n \tpublic static int parseColor(String colorString) {\n \tif (colorString.charAt(0) == '#') {\n \t// Use a long to avoid rollovers on #ffXXXXXX\n \t\tif (colorString.length() == 4) {\n \t\tcolorString = \"#\" + \n \t\t\t\tcolorString.charAt(1) + colorString.charAt(1) +\n \t\t\t\tcolorString.charAt(2) + colorString.charAt(2) +\n \t\t\t\tcolorString.charAt(3) + colorString.charAt(3);\n \t\t\t\t\n \t}\n \tlong color = Long.parseLong(colorString.substring(1), 16);\n \tif (colorString.length() == 7) {\n\t // Set the alpha value\n \t color |= 0x00000000ff000000;\n \t} else if (colorString.length() != 9) {\n \tthrow new IllegalArgumentException(\"Unknown color \" + colorString); //$NON-NLS-1$\n \t}\n \treturn (int)color;\n \t}\n \tthrow new IllegalArgumentException(\"Unknown color \" + colorString); //$NON-NLS-1$\n \t}\n\t\n \t\n\tpublic static int extractFirstIntegerNumber(String s) {\n\t\tint i = 0;\n\t\tfor (int k = 0; k < s.length(); k++) {\n\t\t\tif (isDigit(s.charAt(k))) {\n\t\t\t\ti = i * 10 + (s.charAt(k) - '0');\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn i;\n\t}\n\t\n\tpublic static int extractIntegerNumber(String s) {\n\t\tint i = 0;\n\t\tint k = 0;\n\t\tfor (k = 0; k < s.length(); k++) {\n\t\t\tif (isDigit(s.charAt(k))) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfor (; k < s.length(); k++) {\n\t\t\tif (isDigit(s.charAt(k))) {\n\t\t\t\ti = i * 10 + (s.charAt(k) - '0');\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn i;\n\t}\n\t\n\tpublic static String extractIntegerPrefix(String s) {\n\t\tint k = 0;\n\t\tfor (; k < s.length(); k++) {\n\t\t\tif (Character.isDigit(s.charAt(k))) {\n\t\t\t\treturn s.substring(0, k);\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}\n\t\n\tpublic static String extractOnlyIntegerSuffix(String s) {\n\t\tint k = 0;\n\t\tfor (; k < s.length(); k++) {\n\t\t\tif (Character.isDigit(s.charAt(k))) {\n\t\t\t\treturn s.substring(k);\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}\n\t\n\tpublic static String extractIntegerSuffix(String s) {\n\t\tint k = 0;\n\t\tfor (; k < s.length(); k++) {\n\t\t\tif (!Character.isDigit(s.charAt(k))) {\n\t\t\t\treturn s.substring(k);\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}\n\t\n\t\n\tpublic static void fileCopy(File src, File dst) throws IOException {\n\t\tFileOutputStream fout = new FileOutputStream(dst);\n\t\ttry {\n\t\t\tFileInputStream fin = new FileInputStream(src);\n\t\t\ttry {\n\t\t\t\tAlgorithms.streamCopy(fin, fout);\n\t\t\t} finally {\n\t\t\t\tfin.close();\n\t\t\t}\n\t\t} finally {\n\t\t\tfout.close();\n\t\t}\n\t}\n\tpublic static void streamCopy(InputStream in, OutputStream out) throws IOException{\n\t\tbyte[] b = new byte[BUFFER_SIZE];\n\t\tint read;\n\t\twhile ((read = in.read(b)) != -1) {\n\t\t\tout.write(b, 0, read);\n\t\t}\n\t}\n\t\n\t\n\tpublic static void streamCopy(InputStream in, OutputStream out, IProgress pg, int bytesDivisor) throws IOException{\n\t\tbyte[] b = new byte[BUFFER_SIZE];\n\t\tint read;\n\t\tint cp = 0;\n\t\twhile ((read = in.read(b)) != -1) {\n\t\t\tout.write(b, 0, read);\n\t\t\tcp += read;\n\t\t\tif(pg != null && cp > bytesDivisor) {\n\t\t\t\tpg.progress(cp / bytesDivisor);\n\t\t\t\tcp = cp % bytesDivisor; \n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void oneByteStreamCopy(InputStream in, OutputStream out) throws IOException{\n\t\tint read;\n\t\twhile ((read = in.read()) != -1) {\n\t\t\tout.write(read);\n\t\t}\n\t}\n\t\n\tpublic static void closeStream(Closeable stream){\n\t\ttry {\n\t\t\tif(stream != null){\n\t\t\t\tstream.close();\n\t\t\t}\n\t\t} catch(IOException e){\n\t\t\tlog.warn(\"Closing stream warn\", e); //$NON-NLS-1$\n\t\t}\n\t}\n\t\n\tpublic static void updateAllExistingImgTilesToOsmandFormat(File f){\n\t\tif(f.isDirectory()){\n\t\t\tfor(File c : f.listFiles()){\n\t\t\t\tupdateAllExistingImgTilesToOsmandFormat(c);\n\t\t\t}\n\t\t} else if(f.getName().endsWith(\".png\") || f.getName().endsWith(\".jpg\")){ //$NON-NLS-1$ //$NON-NLS-2$\n\t\t\tf.renameTo(new File(f.getAbsolutePath() + \".tile\")); //$NON-NLS-1$\n\t\t} else if(f.getName().endsWith(\".andnav2\")) { //$NON-NLS-1$\n\t\t\tf.renameTo(new File(f.getAbsolutePath().substring(0, f.getAbsolutePath().length() - \".andnav2\".length()) + \".tile\")); //$NON-NLS-1$ //$NON-NLS-2$\n\t\t}\n\t\t\t\n\t}\n\t\n\tpublic static StringBuilder readFromInputStream(InputStream i) throws IOException {\n\t\tStringBuilder responseBody = new StringBuilder();\n\t\tresponseBody.setLength(0);\n\t\tif (i != null) {\n\t\t\tBufferedReader in = new BufferedReader(new InputStreamReader(i, \"UTF-8\"), 256); //$NON-NLS-1$\n\t\t\tString s;\n\t\t\tboolean f = true;\n\t\t\twhile ((s = in.readLine()) != null) {\n\t\t\t\tif (!f) {\n\t\t\t\t\tresponseBody.append(\"\\n\"); //$NON-NLS-1$\n\t\t\t\t} else {\n\t\t\t\t\tf = false;\n\t\t\t\t}\n\t\t\t\tresponseBody.append(s);\n\t\t\t}\n\t\t}\n\t\treturn responseBody;\n\t}\n\t\n\tpublic static boolean removeAllFiles(File f) {\n\t\tif (f == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (f.isDirectory()) {\n\t\t\tFile[] fs = f.listFiles();\n\t\t\tif(fs != null) {\n\t\t\t for (File c : fs) {\n\t\t\t removeAllFiles(c);\n\t\t\t }\n\t\t\t}\n\t\t\treturn f.delete();\n\t\t} else {\n\t\t\treturn f.delete();\n\t\t}\n\t}\n\t\n\t\n\tpublic static long parseLongFromBytes(byte[] bytes, int offset) {\n\t\tlong o= 0xff & bytes[offset + 7];\n\t\to = o << 8 | (0xff & bytes[offset + 6]);\n\t\to = o << 8 | (0xff & bytes[offset + 5]);\n\t\to = o << 8 | (0xff & bytes[offset + 4]);\n\t\to = o << 8 | (0xff & bytes[offset + 3]);\n\t\to = o << 8 | (0xff & bytes[offset + 2]);\n\t\to = o << 8 | (0xff & bytes[offset + 1]);\n\t\to = o << 8 | (0xff & bytes[offset]);\n\t\treturn o;\n\t}\n\t\n\t\n\t\n\tpublic static void putLongToBytes(byte[] bytes, int offset, long l){\n\t\tbytes[offset] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 1] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 2] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 3] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 4] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 5] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 6] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 7] = (byte) (l & 0xff);\n\t}\n\t\n\t\n\tpublic static int parseIntFromBytes(byte[] bytes, int offset) {\n\t\tint o = (0xff & bytes[offset + 3]) << 24;\n\t\to |= (0xff & bytes[offset + 2]) << 16;\n\t\to |= (0xff & bytes[offset + 1]) << 8;\n\t\to |= (0xff & bytes[offset]);\n\t\treturn o;\n\t}\n\t\n\tpublic static void putIntToBytes(byte[] bytes, int offset, int l){\n\t\tbytes[offset] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 1] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 2] = (byte) (l & 0xff);\n\t\tl >>= 8;\n\t\tbytes[offset + 3] = (byte) (l & 0xff);\n\t}\n\t\n\t\n\tpublic static void writeLongInt(OutputStream stream, long l) throws IOException {\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t\tl >>= 8;\n\t\tstream.write((int) (l & 0xff));\n\t}\n\t\n\tpublic static void writeInt(OutputStream stream, int l) throws IOException {\n\t\tstream.write(l & 0xff);\n\t\tl >>= 8;\n\t\tstream.write(l & 0xff);\n\t\tl >>= 8;\n\t\tstream.write(l & 0xff);\n\t\tl >>= 8;\n\t\tstream.write(l & 0xff);\n\t}\n\t\n\n\tpublic static void writeSmallInt(OutputStream stream, int l) throws IOException {\n\t\tstream.write(l & 0xff);\n\t\tl >>= 8;\n\t\tstream.write(l & 0xff);\n\t\tl >>= 8;\n\t}\n\t\n\tpublic static int parseSmallIntFromBytes(byte[] bytes, int offset) {\n\t\tint s = (0xff & bytes[offset + 1]) << 8;\n\t\ts |= (0xff & bytes[offset]);\n\t\treturn s;\n\t}\n\t\n\tpublic static void putSmallIntBytes(byte[] bytes, int offset, int s){\n\t\tbytes[offset] = (byte) (s & 0xff);\n\t\ts >>= 8;\n\t\tbytes[offset + 1] = (byte) (s & 0xff);\n\t\ts >>= 8;\n\t}\n\n\tpublic static boolean containsDigit(String name) {\n\t\tfor (int i = 0; i < name.length(); i++) {\n\t\t\tif (Character.isDigit(name.charAt(i))) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\n\tpublic static String formatDuration(int seconds) {\n\t\tString sec;\n\t\tif (seconds % 60 < 10) {\n\t\t\tsec = \"0\" + (seconds % 60);\n\t\t} else {\n\t\t\tsec = (seconds % 60) + \"\";\n\t\t}\n\t\tint minutes = seconds / 60;\n\t\tif (minutes < 60) {\n\t\t\treturn minutes + \":\" + sec;\n\t\t} else {\n\t\t\tString min;\n\t\t\tif (minutes % 60 < 10) {\n\t\t\t\tmin = \"0\" + (minutes % 60);\n\t\t\t} else {\n\t\t\t\tmin = (minutes % 60) + \"\";\n\t\t\t}\n\t\t\tint hours = minutes / 60;\n\t\t\treturn hours + \":\" + min + \":\" + sec;\n\t\t}\n\t}\n\n\tpublic static String formatMinutesDuration(int minutes) {\n\t\tif (minutes < 60) {\n\t\t\treturn String.valueOf(minutes);\n\t\t} else {\n\t\t\tint min = minutes % 60;\n\t\t\tint hours = minutes / 60;\n\t\t\treturn String.format(\"%02d:%02d\", hours, min);\n\t\t}\n\t}\n\t\n\tpublic static <T extends Enum<T> > T parseEnumValue(T[] cl, String val, T defaultValue){\n\t\tfor(int i = 0; i< cl.length; i++) {\n\t\t\tif(cl[i].name().equalsIgnoreCase(val)) {\n\t\t\t\treturn cl[i];\n\t\t\t}\n\t\t}\n\t\treturn defaultValue;\n\t}\n\n\tpublic static String colorToString(int color) {\n\t\tif ((0xFF000000 & color) == 0xFF000000) {\n\t\t\treturn \"#\" + format(6, Integer.toHexString(color & 0x00FFFFFF)); //$NON-NLS-1$\n\t\t} else {\n\t\t\treturn \"#\" + format(8, Integer.toHexString(color)); //$NON-NLS-1$\n\t\t}\n\t}\n\n\tprivate static String format(int i, String hexString) {\n\t\twhile(hexString.length() < i) {\n\t\t\thexString = \"0\" + hexString;\n\t\t}\n\t\treturn hexString;\n\t}\n}" } ]
import net.osmand.data.LatLon; import net.osmand.util.Algorithms; import java.io.Serializable; import java.util.LinkedList; import java.util.List;
5,606
package net.osmand.map; public class WorldRegion implements Serializable { public static final String WORLD_BASEMAP = "world_basemap"; public static final String AFRICA_REGION_ID = "africa"; public static final String ASIA_REGION_ID = "asia"; public static final String AUSTRALIA_AND_OCEANIA_REGION_ID = "australia-oceania"; public static final String CENTRAL_AMERICA_REGION_ID = "centralamerica"; public static final String EUROPE_REGION_ID = "europe"; public static final String NORTH_AMERICA_REGION_ID = "northamerica"; public static final String RUSSIA_REGION_ID = "russia"; public static final String JAPAN_REGION_ID = "japan_asia"; public static final String SOUTH_AMERICA_REGION_ID = "southamerica"; protected static final String WORLD = "world"; // Just a string constant public static final String UNITED_KINGDOM_REGION_ID = "gb_europe"; // Hierarchy protected WorldRegion superregion; protected List<WorldRegion> subregions; // filled by osmand regions protected RegionParams params = new RegionParams(); protected String regionFullName; protected String regionParentFullName; protected String regionName; protected String regionNameEn; protected String regionNameLocale; protected String regionSearchText; protected String regionDownloadName; protected boolean regionMapDownload;
package net.osmand.map; public class WorldRegion implements Serializable { public static final String WORLD_BASEMAP = "world_basemap"; public static final String AFRICA_REGION_ID = "africa"; public static final String ASIA_REGION_ID = "asia"; public static final String AUSTRALIA_AND_OCEANIA_REGION_ID = "australia-oceania"; public static final String CENTRAL_AMERICA_REGION_ID = "centralamerica"; public static final String EUROPE_REGION_ID = "europe"; public static final String NORTH_AMERICA_REGION_ID = "northamerica"; public static final String RUSSIA_REGION_ID = "russia"; public static final String JAPAN_REGION_ID = "japan_asia"; public static final String SOUTH_AMERICA_REGION_ID = "southamerica"; protected static final String WORLD = "world"; // Just a string constant public static final String UNITED_KINGDOM_REGION_ID = "gb_europe"; // Hierarchy protected WorldRegion superregion; protected List<WorldRegion> subregions; // filled by osmand regions protected RegionParams params = new RegionParams(); protected String regionFullName; protected String regionParentFullName; protected String regionName; protected String regionNameEn; protected String regionNameLocale; protected String regionSearchText; protected String regionDownloadName; protected boolean regionMapDownload;
protected LatLon regionCenter;
0
2023-11-15 05:04:55+00:00
8k
orijer/IvritInterpreter
src/Evaluation/VariableValueSwapper.java
[ { "identifier": "UnevenBracketsException", "path": "src/IvritExceptions/InterpreterExceptions/EvaluatorExceptions/UnevenBracketsException.java", "snippet": "public class UnevenBracketsException extends UncheckedIOException{\r\n public UnevenBracketsException(String str) {\r\n super(\"נמצאה שגיאה באיזון הסוגריים בקטע: \" + str, new IOException());\r\n }\r\n \r\n}\r" }, { "identifier": "BooleanVariable", "path": "src/Variables/BooleanVariable.java", "snippet": "public class BooleanVariable extends AbstractVariable<Boolean> {\r\n //An array of all the operators boolean values support:\r\n public static String[] BOOLEAN_OPERATORS = { \"שווה\", \"לא-שווה\", \"וגם\", \"או\", \">\", \"<\" };\r\n\r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public BooleanVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n if (value) {\r\n return \"אמת\";\r\n }\r\n\r\n return \"שקר\";\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n if (newValue.equals(\"אמת\")) {\r\n this.value = true;\r\n } else if (newValue.equals(\"שקר\")) {\r\n this.value = false;\r\n } else {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג טענה.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked\r\n * @return true IFF checkValue is a valid boolean value in Ivrit.\r\n */\r\n public static boolean isBooleanValue(String checkValue) {\r\n return checkValue.equals(\"אמת\") || checkValue.equals(\"שקר\");\r\n }\r\n\r\n //Static methods:\r\n\r\n /**\r\n * @return true IFF the given data contains a boolean expression (that isn't in quotes, \"\"וגם\"\" doesn't count)\r\n */\r\n public static boolean containsBooleanExpression(String data) {\r\n boolean inQuotes = false;\r\n\r\n for (int index = 0; index < data.length(); index++) {\r\n if (data.charAt(index) == '\"')\r\n inQuotes = !inQuotes;\r\n else if (!inQuotes) {\r\n for (String operator : BOOLEAN_OPERATORS) {\r\n //Check if the data contains an operator here that isn't in quotes:\r\n if (data.startsWith(operator, index))\r\n return true;\r\n }\r\n }\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * @return 0 if the given string doesn't start with a boolean operatorm or the operator length (how many characters it has) otherwise.\r\n */\r\n public static int startsWithBooleanOperator(String data) {\r\n for (String operator : BOOLEAN_OPERATORS) {\r\n if (data.startsWith(operator))\r\n return operator.length();\r\n }\r\n\r\n return 0;\r\n }\r\n}\r" }, { "identifier": "FloatVariable", "path": "src/Variables/FloatVariable.java", "snippet": "public class FloatVariable extends AbstractVariable<Float> implements NumericVariable {\r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public FloatVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n return Float.toString(this.value);\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n try {\r\n this.value = Float.parseFloat(newValue);\r\n } catch (NumberFormatException exception) {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג עשרוני.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked.\r\n * @return true IFF checkValue is a valid float value in Ivrit.\r\n */\r\n public static boolean isFloatValue(String checkValue) {\r\n try {\r\n Float.parseFloat(checkValue);\r\n return true;\r\n } catch (NumberFormatException exception) {\r\n return false;\r\n }\r\n }\r\n\r\n //NumericVariable methods:\r\n\r\n @Override\r\n public void add(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value += Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value += Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחבר למשתנה מסוג עשרוני את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void substract(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value -= Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value -= Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחסר ממשתנה מסוג עשרוני את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void multiply(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value *= Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value *= Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן להכפיל משתנה מסוג עשרוני בערך \" + value);\r\n }\r\n\r\n @Override\r\n public void divide(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value /= Integer.parseInt(value);\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value /= Float.parseFloat(value);\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחלק משתנה מסוג עשרוני בערך \" + value);\r\n }\r\n\r\n @Override\r\n public BooleanVariable greaterThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value > Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value > Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג עשרוני לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n\r\n @Override\r\n public BooleanVariable lessThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value < Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value < Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג עשרוני לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n}\r" }, { "identifier": "IntegerVariable", "path": "src/Variables/IntegerVariable.java", "snippet": "public class IntegerVariable extends AbstractVariable<Integer> implements NumericVariable { \r\n /**\r\n * Constructor.\r\n * @param value - The value of the variable.\r\n */\r\n public IntegerVariable(String value) {\r\n super(value);\r\n }\r\n\r\n @Override\r\n public String getValue() {\r\n return Integer.toString(this.value);\r\n }\r\n\r\n @Override\r\n public void updateValue(String newValue) {\r\n try {\r\n this.value = Integer.parseInt(newValue);\r\n } catch (NumberFormatException exception) {\r\n throw new NumberFormatException(\"הערך \" + newValue + \" לא מתאים למשתנה מסוג שלם.\");\r\n }\r\n }\r\n\r\n /**\r\n * @param checkValue - The value to be checked.\r\n * @return true IFF checkValue is a valid integer value in Ivrit.\r\n */\r\n public static boolean isIntegerValue(String checkValue) {\r\n try {\r\n Integer.parseInt(checkValue);\r\n return true;\r\n } catch (NumberFormatException exception) {\r\n return false;\r\n }\r\n }\r\n\r\n //NumericVariable methods:\r\n\r\n @Override\r\n public void add(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value += Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value += (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחבר למשתנה מסוג שלם את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void substract(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value -= Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value -= (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחסר ממשתנה מסוג שלם את הערך \" + value);\r\n }\r\n\r\n @Override\r\n public void multiply(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value *= Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value *= (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להכפיל משתנה מסוג שלם בערך \" + value);\r\n }\r\n\r\n @Override\r\n public void divide(String value) {\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n this.value /= Integer.parseInt(value);\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n this.value /= (int) Float.parseFloat(value);\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן לחלק משתנה מסוג שלם בערך \" + value);\r\n }\r\n\r\n @Override\r\n public BooleanVariable greaterThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value > Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value > Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג שלם לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n\r\n @Override\r\n public BooleanVariable lessThen(String value) {\r\n String result = \"שקר\";\r\n\r\n if (IntegerVariable.isIntegerValue(value)) {\r\n if (this.value < Integer.parseInt(value))\r\n result = \"אמת\";\r\n\r\n } else if (FloatVariable.isFloatValue(value)) {\r\n if (this.value < Float.parseFloat(value))\r\n result = \"אמת\";\r\n\r\n } else\r\n throw new ClassCastException(\"לא ניתן להשוות משתנה מסוג שלם לערך \" + value);\r\n\r\n return new BooleanVariable(result);\r\n }\r\n}\r" }, { "identifier": "NumericVariable", "path": "src/Variables/NumericVariable.java", "snippet": "public interface NumericVariable extends Variable {\r\n //An array of all the operators Numeric Variables support:\r\n public static char[] NUMERIC_OPERATORS = { '+', '-', '*', '/' };\r\n\r\n /**\r\n * Adds the given value to the variable's value.\r\n * @param value - The value to be added (represented as a string).\r\n */\r\n public void add(String value);\r\n\r\n /**\r\n * Substracts the given value from the variable's value.\r\n * @param value - The value to substract (represented as a string).\r\n */\r\n public void substract(String value);\r\n\r\n /**\r\n * Multiplies the variable's value by the given value.\r\n * @param value - The value to multiply by (represented as a string).\r\n */\r\n public void multiply(String value);\r\n\r\n /**\r\n * Divides the variable's value by the given value.\r\n * @param value - The value to divide by (represented as a string).\r\n */\r\n public void divide(String value);\r\n\r\n /**\r\n * @return true IFF the variable's value is greater then the given value.\r\n */\r\n public BooleanVariable greaterThen(String value);\r\n\r\n /**\r\n * @return true IFF the variable's value is less then the given value.\r\n */\r\n public BooleanVariable lessThen(String value);\r\n //Static methods:\r\n\r\n /**\r\n * @return true IFF the given char is a numeric operator (as declared in the static field OPERATORS in this class).\r\n */\r\n public static boolean isNumericOperator(char ch) {\r\n for (char operator : NumericVariable.NUMERIC_OPERATORS) {\r\n if (ch == operator)\r\n return true;\r\n }\r\n\r\n return false;\r\n }\r\n\r\n /**\r\n * @return how many numeric operators are in the given string.\r\n */\r\n public static int countNumericOperators(String str) {\r\n String regex = \"\\\\+|-|\\\\*|/\";\r\n\r\n String[] parts = str.split(regex);\r\n\r\n return parts.length - 1;\r\n }\r\n}\r" }, { "identifier": "VariablesController", "path": "src/Variables/VariablesController.java", "snippet": "public class VariablesController {\r\n //A map that connects between the name of the variable to its value:\r\n private Map<String, Variable> dataMap;\r\n\r\n /**\r\n * Constructor.\r\n */\r\n public VariablesController() {\r\n this.dataMap = new HashMap<>();\r\n }\r\n\r\n /**\r\n * @param name - The name of the variable to check.\r\n * @return true IFF there is already a variable with the given name stored.\r\n */\r\n public boolean isVariable(String name) {\r\n return this.dataMap.containsKey(name);\r\n }\r\n\r\n /**\r\n * Creates a new variable.\r\n * @param variableName - The name of the new variable.\r\n * @param variableType - The type of the new variable.\r\n * @param variableValue - the value of the new variable.\r\n */\r\n public void createVariable(String variableName, String variableType, String variableValue) {\r\n Variable variable;\r\n if (this.dataMap.containsKey(variableValue)) {\r\n //If we are assigning a variable to this (we only copy by value):\r\n variable = VariablesFactory.createVariable(variableType, this.dataMap.get(variableValue).getValue());\r\n\r\n } else {\r\n //We are creating a variable from the value:\r\n variable = VariablesFactory.createVariable(variableType, variableValue);\r\n\r\n }\r\n\r\n this.dataMap.put(variableName, variable);\r\n }\r\n\r\n /**\r\n * Deletes the given variable from the program.\r\n * @param variableName - The name of the variable to delete.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public void deleteVariable(String variableName) {\r\n if (!this.dataMap.containsKey(variableName))\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n\r\n this.dataMap.remove(variableName);\r\n }\r\n\r\n /**\r\n * Updates the value of an existing variable.\r\n * @param variableName - The name of the variable to be updated.\r\n * @param newValue - The new value.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public void updateVariable(String variableName, String newValue) {\r\n Variable variable = this.dataMap.get(variableName);\r\n if (variable == null) {\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n }\r\n\r\n if (this.dataMap.containsKey(newValue)) {\r\n //If we are assigning a variable to this (we only copy by value):\r\n variable.updateValue(this.dataMap.get(newValue).getValue());\r\n } else {\r\n //We are updating from the value:\r\n variable.updateValue(newValue);\r\n\r\n }\r\n }\r\n\r\n /**\r\n * @param variableName - The name of the variable we wan the value of.\r\n * @return the value of the variable with the given name.\r\n * @throws NullPointerException when variableName isn't the name of a variable. \r\n */\r\n public String getVariableValue(String variableName) {\r\n Variable variable = this.dataMap.get(variableName);\r\n if (variable == null) {\r\n throw new NullPointerException(\"לא נמצא משתנה בשם: \" + variableName);\r\n }\r\n\r\n return variable.getValue();\r\n }\r\n\r\n /**\r\n * Clears all the variables created.\r\n */\r\n public void clear() {\r\n this.dataMap.clear();\r\n }\r\n\r\n /**\r\n * Prints all the variables in the format (variableName : variableValue).\r\n */\r\n public void printVariables() {\r\n for (Map.Entry<String, Variable> entry : this.dataMap.entrySet()) {\r\n System.out.println(\"(\" + entry.getKey() + \" : \" + entry.getValue().toString() + \")\");\r\n }\r\n }\r\n}\r" } ]
import java.io.IOException; import java.io.UncheckedIOException; import IvritExceptions.InterpreterExceptions.EvaluatorExceptions.UnevenBracketsException; import Variables.BooleanVariable; import Variables.FloatVariable; import Variables.IntegerVariable; import Variables.NumericVariable; import Variables.VariablesController;
5,126
package Evaluation; /** * Handles switching the variables with their values for the evaluation. */ public class VariableValueSwapper { //Contains the variables of the program: private VariablesController variablesController; /** * Constructor. * @param variablesController - The object that handles the variables of the program. */ public VariableValueSwapper(VariablesController variablesController) { this.variablesController = variablesController; } /** * Reads through a given data string and switches every occurence of a variable with its correct value. * @param data - The data to process. * @return a new string that is similar to the given string, but every occurence of a variable is switched with its value. */ public String swap(String originalData) { String data = originalData; //We want to keep the original data to be used when throwing an exception. StringBuilder swappedLine = new StringBuilder(); int endAt; while (data.length() > 0) { char firstChar = data.charAt(0); if (firstChar == '"') { data = copyStringLiteral(data, swappedLine, originalData); } else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) { //We are reading a space, a bracket, or an operator, just copy it: swappedLine.append(firstChar); data = data.substring(1); } else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) { //We are reading a boolean operator: swappedLine.append(data.substring(0, endAt)); data = data.substring(endAt); } else { //We are reading a literal (non-string) value or a variable: endAt = dataEndAt(data); String literalValueOrVariable = data.substring(0, endAt); if (this.variablesController.isVariable(literalValueOrVariable)) { //If it is a variable, switch it with its value: swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable)); } else { //If it is literal data, try to copy it: copyNonStringLiteral(literalValueOrVariable, swappedLine); } data = data.substring(endAt); } } return swappedLine.toString(); } /** * If given a valid string literal, add its value to the given StringBuilder, * and return the data without the string literal that was found. * @param data - The data that should start with a string literal. * @param swappedLine - The StringBuilder we build the evaluated result in. * @return a substring of the given data string that starts after the string literal that was found. */ private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) { int endAt = data.indexOf('"', 1); if (endAt == -1) { throw new UnevenBracketsException(originalData); } swappedLine.append(data.substring(0, endAt + 1)); return data.substring(endAt + 1); } /** * Copies a non string literal to the given StringBuilder, if it's valid (an actual value of a variable type). * @param literalData - The data that should be a literal of a certain variable type. * @param swappedLine - The string Builder we build the evaluaed result in. */ private void copyNonStringLiteral(String literalData, StringBuilder swappedLine) { if (BooleanVariable.isBooleanValue(literalData) || IntegerVariable.isIntegerValue(literalData)
package Evaluation; /** * Handles switching the variables with their values for the evaluation. */ public class VariableValueSwapper { //Contains the variables of the program: private VariablesController variablesController; /** * Constructor. * @param variablesController - The object that handles the variables of the program. */ public VariableValueSwapper(VariablesController variablesController) { this.variablesController = variablesController; } /** * Reads through a given data string and switches every occurence of a variable with its correct value. * @param data - The data to process. * @return a new string that is similar to the given string, but every occurence of a variable is switched with its value. */ public String swap(String originalData) { String data = originalData; //We want to keep the original data to be used when throwing an exception. StringBuilder swappedLine = new StringBuilder(); int endAt; while (data.length() > 0) { char firstChar = data.charAt(0); if (firstChar == '"') { data = copyStringLiteral(data, swappedLine, originalData); } else if (firstChar == ' ' || isBracket(firstChar) || NumericVariable.isNumericOperator(firstChar)) { //We are reading a space, a bracket, or an operator, just copy it: swappedLine.append(firstChar); data = data.substring(1); } else if ((endAt = BooleanVariable.startsWithBooleanOperator(data)) > 0) { //We are reading a boolean operator: swappedLine.append(data.substring(0, endAt)); data = data.substring(endAt); } else { //We are reading a literal (non-string) value or a variable: endAt = dataEndAt(data); String literalValueOrVariable = data.substring(0, endAt); if (this.variablesController.isVariable(literalValueOrVariable)) { //If it is a variable, switch it with its value: swappedLine.append(this.variablesController.getVariableValue(literalValueOrVariable)); } else { //If it is literal data, try to copy it: copyNonStringLiteral(literalValueOrVariable, swappedLine); } data = data.substring(endAt); } } return swappedLine.toString(); } /** * If given a valid string literal, add its value to the given StringBuilder, * and return the data without the string literal that was found. * @param data - The data that should start with a string literal. * @param swappedLine - The StringBuilder we build the evaluated result in. * @return a substring of the given data string that starts after the string literal that was found. */ private String copyStringLiteral(String data, StringBuilder swappedLine, String originalData) { int endAt = data.indexOf('"', 1); if (endAt == -1) { throw new UnevenBracketsException(originalData); } swappedLine.append(data.substring(0, endAt + 1)); return data.substring(endAt + 1); } /** * Copies a non string literal to the given StringBuilder, if it's valid (an actual value of a variable type). * @param literalData - The data that should be a literal of a certain variable type. * @param swappedLine - The string Builder we build the evaluaed result in. */ private void copyNonStringLiteral(String literalData, StringBuilder swappedLine) { if (BooleanVariable.isBooleanValue(literalData) || IntegerVariable.isIntegerValue(literalData)
|| FloatVariable.isFloatValue(literalData)) {
2
2023-11-17 09:15:07+00:00
8k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmAchievementEmployeeAppraisalController.java
[ { "identifier": "Result", "path": "common/common-web/src/main/java/com/kakarote/core/common/Result.java", "snippet": "public class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(value = \"code\", required = true, example = \"0\")\n private Integer code;\n\n @ApiModelProperty(value = \"msg\", required = true, example = \"success\")\n private String msg;\n\n private T data;\n\n Result() {\n\n }\n\n\n protected Result(ResultCode resultCode) {\n this.code = resultCode.getCode();\n this.msg = resultCode.getMsg();\n }\n\n private Result(ResultCode resultCode, String msg) {\n this.code = resultCode.getCode();\n this.msg = msg;\n }\n\n private Result(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n\n public Integer getCode() {\n return code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n\n public static Result<String> noAuth() {\n return error(SystemCodeEnum.SYSTEM_NO_AUTH);\n }\n\n public static <T> Result<T> error(ResultCode resultCode) {\n return new Result<>(resultCode);\n }\n\n public static <T> Result<T> error(int code, String msg) {\n return new Result<>(code, msg);\n }\n\n public static <T> Result<T> error(ResultCode resultCode, String msg) {\n return new Result<T>(resultCode, msg);\n }\n\n public static <T> Result<T> ok(T data) {\n Result<T> result = new Result<>(SystemCodeEnum.SYSTEM_OK);\n result.setData(data);\n return result;\n }\n\n\n public static <T> Result<T> ok() {\n return new Result<T>(SystemCodeEnum.SYSTEM_OK);\n }\n\n\n public Result<T> setData(T data) {\n this.data = data;\n return this;\n }\n\n public T getData() {\n return this.data;\n }\n\n public boolean hasSuccess() {\n return Objects.equals(SystemCodeEnum.SYSTEM_OK.getCode(), code);\n }\n\n public String toJSONString() {\n return JSON.toJSONString(this);\n }\n\n @Override\n public String toString() {\n return toJSONString();\n }\n\n\n\n}" }, { "identifier": "BasePage", "path": "common/common-web/src/main/java/com/kakarote/core/entity/BasePage.java", "snippet": "public class BasePage<T> implements IPage<T> {\n\n private static final long serialVersionUID = 8545996863226528798L;\n\n /**\n * 查询数据列表\n */\n private List<T> list;\n\n /**\n * 总数\n */\n private long totalRow;\n\n /**\n * 每页显示条数,默认 15\n */\n private long pageSize;\n\n /**\n * 当前页\n */\n private long pageNumber;\n\n /**\n * 排序字段信息\n */\n private List<OrderItem> orders;\n\n /**\n * 自动优化 COUNT SQL\n */\n private boolean optimizeCountSql;\n\n\n /**\n * 额外数据\n */\n private Object extraData;\n\n\n public BasePage() {\n this(null, null);\n }\n\n /**\n * 分页构造函数\n *\n * @param current 当前页\n * @param size 每页显示条数\n */\n public BasePage(Long current, Long size) {\n this(current, size, 0L);\n }\n\n /**\n * 分页构造函数\n *\n * @param current 当前页\n * @param size 每页显示条数\n * @param total 总行数\n */\n public BasePage(Long current, Long size, Long total) {\n this(current, size, total, new ArrayList<>());\n }\n\n /**\n * @param current 当前页\n * @param size 每页显示条数\n * @param total 总行数\n * @param list 数据列表\n */\n public BasePage(Long current, Long size, Long total, List<T> list) {\n if (current == null || current < 0L) {\n current = 1L;\n }\n if (size == null || size < 0L) {\n size = 15L;\n }\n if (total == null || total < 0L) {\n total = 0L;\n }\n\n this.pageNumber = current;\n this.pageSize = size;\n this.totalRow = total;\n this.orders = new ArrayList<>();\n this.optimizeCountSql = true;\n this.list = list;\n }\n\n\n @Override\n @JsonIgnore\n public List<T> getRecords() {\n return this.list;\n }\n\n public List<T> getList() {\n return this.list;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getTotalRow() {\n return this.totalRow;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getTotalPage() {\n if (getSize() == 0) {\n return 0L;\n }\n long pages = getTotal() / getSize();\n if (getTotal() % getSize() != 0) {\n pages++;\n }\n return pages;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getPageSize() {\n return this.pageSize;\n }\n\n @JsonSerialize(using = WebConfig.NumberSerializer.class)\n public Long getPageNumber() {\n return this.pageNumber;\n }\n\n public boolean isFirstPage() {\n return this.pageNumber == 1L;\n }\n\n public boolean isLastPage() {\n return getTotal() == 0 || this.pageNumber >= getTotalPage();\n }\n\n public void setPageNumber(long pageNumber) {\n this.pageNumber = pageNumber;\n }\n\n public void setList(List<T> list) {\n this.list = list;\n }\n\n @Override\n public BasePage<T> setRecords(List<T> records) {\n this.list = records;\n return this;\n }\n\n @Override\n @JsonIgnore\n public long getTotal() {\n return this.totalRow;\n }\n\n @Override\n public BasePage<T> setTotal(long total) {\n this.totalRow = total;\n return this;\n }\n\n @Override\n @JsonIgnore\n public long getSize() {\n return this.pageSize;\n }\n\n @Override\n public BasePage<T> setSize(long size) {\n this.pageSize = size;\n return this;\n }\n\n @Override\n @JsonIgnore\n public long getCurrent() {\n return this.pageNumber;\n }\n\n @Override\n public BasePage<T> setCurrent(long current) {\n this.pageNumber = current;\n return this;\n }\n\n\n @Override\n public List<OrderItem> orders() {\n return orders;\n }\n\n public void setOrders(List<OrderItem> orders) {\n this.orders = orders;\n }\n\n public List<OrderItem> getOrders() {\n return orders;\n }\n\n @Override\n public boolean optimizeCountSql() {\n return optimizeCountSql;\n }\n\n\n public BasePage<T> setOptimizeCountSql(boolean optimizeCountSql) {\n this.optimizeCountSql = optimizeCountSql;\n return this;\n }\n\n /**\n * 类型转换 通过beanCopy\n *\n * @param clazz 转换后的类\n * @param <R> R\n * @return BasePage\n */\n public <R> BasePage<R> copy(Class<R> clazz) {\n return copy(obj -> BeanUtil.copyProperties(obj, clazz));\n }\n\n /**\n * 类型转换 通过beanCopy\n *\n * @param <R> R\n * @return BasePage\n */\n public <R> BasePage<R> copy(Function<? super T, ? extends R> mapper) {\n BasePage<R> basePage = new BasePage<>(getCurrent(), getSize(), getTotal());\n basePage.setRecords(getRecords().stream().map(mapper).collect(Collectors.toList()));\n return basePage;\n }\n\n @Override\n @JsonIgnore\n public long getPages() {\n return getTotalPage();\n }\n\n public Object getExtraData() {\n return extraData;\n }\n\n public void setExtraData(Object extraData) {\n this.extraData = extraData;\n }\n}" }, { "identifier": "EmployeeHolder", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/common/EmployeeHolder.java", "snippet": "public class EmployeeHolder {\n\n private static ThreadLocal<EmployeeInfo> employeeInfoThreadLocal = new ThreadLocal<>();\n\n\n public static EmployeeInfo getEmployeeInfo() {\n return employeeInfoThreadLocal.get();\n }\n\n public static Long getEmployeeId() {\n if (employeeInfoThreadLocal.get() != null) {\n return employeeInfoThreadLocal.get().getEmployeeId();\n } else {\n return -1L;\n }\n }\n\n /**\n * 是否是人资管理角色\n *\n * @return\n */\n public static boolean isHrmAdmin() {\n EmployeeInfo employeeInfo = employeeInfoThreadLocal.get();\n AdminRole role = employeeInfo.getRole();\n return UserUtil.isAdmin() || (role != null && role.getLabel() == 91);\n }\n\n public static void setEmployeeInfo(EmployeeInfo employeeInfo) {\n employeeInfoThreadLocal.set(employeeInfo);\n }\n\n public static void remove() {\n employeeInfoThreadLocal.remove();\n }\n}" }, { "identifier": "EmployeeAppraisalStatus", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/constant/achievement/EmployeeAppraisalStatus.java", "snippet": "public enum EmployeeAppraisalStatus {\n /**\n * 考核状态 1 待填写 2 待目标确认 3 待评定 4 待结果确认 5 终止绩效\n */\n TO_BE_FILLED(1, \"待填写\"), PENDING_CONFIRMATION(2, \"待目标确认\"),\n TO_BE_ASSESSED(3, \"待结果评定\"), TO_BE_CONFIRMED(4, \"待结果确认\"),\n STOP(5, \"终止绩效\"), COMPLETE(6, \"考核完成\");\n\n EmployeeAppraisalStatus(int value, String name) {\n this.value = value;\n this.name = name;\n }\n\n\n private String name;\n private int value;\n\n public static String parseName(int type) {\n for (EmployeeAppraisalStatus value : EmployeeAppraisalStatus.values()) {\n if (value.value == type) {\n return value.name;\n }\n }\n return \"\";\n }\n\n public static int valueOfType(String name) {\n for (EmployeeAppraisalStatus value : EmployeeAppraisalStatus.values()) {\n if (value.name.equals(name)) {\n return value.value;\n }\n }\n return -1;\n }\n\n\n public String getName() {\n return name;\n }\n\n public int getValue() {\n return value;\n }\n}" }, { "identifier": "IHrmAchievementEmployeeAppraisalService", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/service/IHrmAchievementEmployeeAppraisalService.java", "snippet": "public interface IHrmAchievementEmployeeAppraisalService extends BaseService<HrmAchievementEmployeeAppraisal> {\n\n /**\n * 查询员工绩效数量\n *\n * @return\n */\n Map<Integer, Integer> queryAppraisalNum();\n\n /**\n * 查询我的绩效\n *\n * @param basePageBO\n * @return\n */\n BasePage<QueryMyAppraisalVO> queryMyAppraisal(BasePageBO basePageBO);\n\n /**\n * 查询目标确认列表\n *\n * @param basePageBO\n * @return\n */\n BasePage<TargetConfirmListVO> queryTargetConfirmList(BasePageBO basePageBO);\n\n /**\n * 查询结果评定列表\n *\n * @param evaluatoListBO\n * @return\n */\n BasePage<EvaluatoListVO> queryEvaluatoList(EvaluatoListBO evaluatoListBO);\n\n /**\n * 查询考核详情\n *\n * @param employeeAppraisalId\n * @return\n */\n EmployeeAppraisalDetailVO queryEmployeeAppraisalDetail(Long employeeAppraisalId);\n\n /**\n * 填写绩效\n *\n * @param writeAppraisalBO\n */\n void writeAppraisal(WriteAppraisalBO writeAppraisalBO);\n\n /**\n * 目标确认\n *\n * @param targetConfirmBO\n */\n void targetConfirm(TargetConfirmBO targetConfirmBO);\n\n /**\n * 结果评定\n *\n * @param resultEvaluatoBO\n */\n void resultEvaluato(ResultEvaluatoBO resultEvaluatoBO);\n\n /**\n * 查询结果确认列表\n *\n * @param basePageBO\n * @return\n */\n BasePage<ResultConfirmListVO> queryResultConfirmList(BasePageBO basePageBO);\n\n /**\n * 绩效结果确认\n *\n * @param appraisalId\n * @return\n */\n ResultConfirmByAppraisalIdVO queryResultConfirmByAppraisalId(Long appraisalId);\n\n /**\n * 修改考评分数\n *\n * @param updateScoreLevelBO\n */\n void updateScoreLevel(UpdateScoreLevelBO updateScoreLevelBO);\n\n /**\n * 结果确认\n *\n * @param appraisalId\n */\n void resultConfirm(Long appraisalId);\n\n /**\n * 修改目标进度\n *\n * @param updateScheduleBO\n */\n void updateSchedule(UpdateScheduleBO updateScheduleBO);\n\n /**\n * 查询目标确认列表的绩效筛选条件\n *\n * @return\n */\n\n List<AchievementAppraisalVO> queryTargetConfirmScreen(Long employeeId, Integer status);\n\n /**\n * 查询结果评定列表的绩效筛选条件\n *\n * @return\n */\n List<AchievementAppraisalVO> queryEvaluatoScreen(Long employeeId, Integer status);\n\n /**\n * 查询等级id通过评分\n *\n * @param queryLevelIdByScoreBO\n * @return\n */\n Long queryLevelIdByScore(QueryLevelIdByScoreBO queryLevelIdByScoreBO);\n\n\n}" } ]
import com.kakarote.core.common.Result; import com.kakarote.core.entity.BasePage; import com.kakarote.hrm.common.EmployeeHolder; import com.kakarote.hrm.constant.achievement.EmployeeAppraisalStatus; import com.kakarote.hrm.entity.BO.*; import com.kakarote.hrm.entity.VO.*; import com.kakarote.hrm.service.IHrmAchievementEmployeeAppraisalService; 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;
4,882
package com.kakarote.hrm.controller; /** * <p> * 员工绩效考核 前端控制器 * </p> * * @author huangmingbo * @since 2020-05-12 */ @RestController @RequestMapping("/hrmAchievementEmployeeAppraisal") @Api(tags = "绩效考核-员工端") public class HrmAchievementEmployeeAppraisalController { @Autowired private IHrmAchievementEmployeeAppraisalService employeeAppraisalService; @PostMapping("/queryAppraisalNum") @ApiOperation("查询员工绩效数量") public Result<Map<Integer, Integer>> queryAppraisalNum() { Map<Integer, Integer> map = employeeAppraisalService.queryAppraisalNum(); return Result.ok(map); } @PostMapping("/queryMyAppraisal") @ApiOperation("查询我的绩效") public Result<BasePage<QueryMyAppraisalVO>> queryMyAppraisal(@RequestBody BasePageBO basePageBO) { BasePage<QueryMyAppraisalVO> list = employeeAppraisalService.queryMyAppraisal(basePageBO); return Result.ok(list); } @PostMapping("/queryTargetConfirmList") @ApiOperation("查询目标确认列表") public Result<BasePage<TargetConfirmListVO>> queryTargetConfirmList(@RequestBody BasePageBO basePageBO) { BasePage<TargetConfirmListVO> page = employeeAppraisalService.queryTargetConfirmList(basePageBO); return Result.ok(page); } @PostMapping("/queryEvaluatoList") @ApiOperation("查询结果评定列表") public Result<BasePage<EvaluatoListVO>> queryEvaluatoList(@RequestBody EvaluatoListBO evaluatoListBO) { BasePage<EvaluatoListVO> page = employeeAppraisalService.queryEvaluatoList(evaluatoListBO); return Result.ok(page); } @PostMapping("/queryResultConfirmList") @ApiOperation("查询结果确认列表") public Result<BasePage<ResultConfirmListVO>> queryResultConfirmList(@RequestBody BasePageBO basePageBO) { BasePage<ResultConfirmListVO> page = employeeAppraisalService.queryResultConfirmList(basePageBO); return Result.ok(page); } @PostMapping("/queryEmployeeAppraisalDetail/{employeeAppraisalId}") @ApiOperation("查询考核详情") public Result<EmployeeAppraisalDetailVO> queryEmployeeAppraisalDetail(@PathVariable("employeeAppraisalId") Long employeeAppraisalId) { EmployeeAppraisalDetailVO employeeAppraisalDetailVO = employeeAppraisalService.queryEmployeeAppraisalDetail(employeeAppraisalId); return Result.ok(employeeAppraisalDetailVO); } @PostMapping("/writeAppraisal") @ApiOperation("填写绩效") public Result writeAppraisal(@RequestBody WriteAppraisalBO writeAppraisalBO) { employeeAppraisalService.writeAppraisal(writeAppraisalBO); return Result.ok(); } @PostMapping("/targetConfirm") @ApiOperation("目标确认") public Result targetConfirm(@RequestBody TargetConfirmBO targetConfirmBO) { employeeAppraisalService.targetConfirm(targetConfirmBO); return Result.ok(); } @PostMapping("/resultEvaluato") @ApiOperation("结果评定") public Result resultEvaluato(@RequestBody ResultEvaluatoBO resultEvaluatoBO) { employeeAppraisalService.resultEvaluato(resultEvaluatoBO); return Result.ok(); } @PostMapping("/queryResultConfirmByAppraisalId/{appraisalId}") @ApiOperation("绩效结果确认") public Result<ResultConfirmByAppraisalIdVO> queryResultConfirmByAppraisalId(@PathVariable("appraisalId") Long appraisalId) { ResultConfirmByAppraisalIdVO resultConfirmByAppraisalIdVO = employeeAppraisalService.queryResultConfirmByAppraisalId(appraisalId); return Result.ok(resultConfirmByAppraisalIdVO); } @PostMapping("/updateScoreLevel") @ApiOperation("修改考评分数") public Result updateScoreLevel(@RequestBody UpdateScoreLevelBO updateScoreLevelBO) { employeeAppraisalService.updateScoreLevel(updateScoreLevelBO); return Result.ok(); } @PostMapping("/resultConfirm/{appraisalId}") @ApiOperation("结果确认") public Result resultConfirm(@PathVariable("appraisalId") Long appraisalId) { employeeAppraisalService.resultConfirm(appraisalId); return Result.ok(); } @PostMapping("/updateSchedule") @ApiOperation("修改目标进度") public Result updateSchedule(@RequestBody UpdateScheduleBO updateScheduleBO) { employeeAppraisalService.updateSchedule(updateScheduleBO); return Result.ok(); } @PostMapping("/queryTargetConfirmScreen") @ApiOperation("查询目标确认列表的绩效筛选条件") public Result<List<AchievementAppraisalVO>> queryTargetConfirmScreen() {
package com.kakarote.hrm.controller; /** * <p> * 员工绩效考核 前端控制器 * </p> * * @author huangmingbo * @since 2020-05-12 */ @RestController @RequestMapping("/hrmAchievementEmployeeAppraisal") @Api(tags = "绩效考核-员工端") public class HrmAchievementEmployeeAppraisalController { @Autowired private IHrmAchievementEmployeeAppraisalService employeeAppraisalService; @PostMapping("/queryAppraisalNum") @ApiOperation("查询员工绩效数量") public Result<Map<Integer, Integer>> queryAppraisalNum() { Map<Integer, Integer> map = employeeAppraisalService.queryAppraisalNum(); return Result.ok(map); } @PostMapping("/queryMyAppraisal") @ApiOperation("查询我的绩效") public Result<BasePage<QueryMyAppraisalVO>> queryMyAppraisal(@RequestBody BasePageBO basePageBO) { BasePage<QueryMyAppraisalVO> list = employeeAppraisalService.queryMyAppraisal(basePageBO); return Result.ok(list); } @PostMapping("/queryTargetConfirmList") @ApiOperation("查询目标确认列表") public Result<BasePage<TargetConfirmListVO>> queryTargetConfirmList(@RequestBody BasePageBO basePageBO) { BasePage<TargetConfirmListVO> page = employeeAppraisalService.queryTargetConfirmList(basePageBO); return Result.ok(page); } @PostMapping("/queryEvaluatoList") @ApiOperation("查询结果评定列表") public Result<BasePage<EvaluatoListVO>> queryEvaluatoList(@RequestBody EvaluatoListBO evaluatoListBO) { BasePage<EvaluatoListVO> page = employeeAppraisalService.queryEvaluatoList(evaluatoListBO); return Result.ok(page); } @PostMapping("/queryResultConfirmList") @ApiOperation("查询结果确认列表") public Result<BasePage<ResultConfirmListVO>> queryResultConfirmList(@RequestBody BasePageBO basePageBO) { BasePage<ResultConfirmListVO> page = employeeAppraisalService.queryResultConfirmList(basePageBO); return Result.ok(page); } @PostMapping("/queryEmployeeAppraisalDetail/{employeeAppraisalId}") @ApiOperation("查询考核详情") public Result<EmployeeAppraisalDetailVO> queryEmployeeAppraisalDetail(@PathVariable("employeeAppraisalId") Long employeeAppraisalId) { EmployeeAppraisalDetailVO employeeAppraisalDetailVO = employeeAppraisalService.queryEmployeeAppraisalDetail(employeeAppraisalId); return Result.ok(employeeAppraisalDetailVO); } @PostMapping("/writeAppraisal") @ApiOperation("填写绩效") public Result writeAppraisal(@RequestBody WriteAppraisalBO writeAppraisalBO) { employeeAppraisalService.writeAppraisal(writeAppraisalBO); return Result.ok(); } @PostMapping("/targetConfirm") @ApiOperation("目标确认") public Result targetConfirm(@RequestBody TargetConfirmBO targetConfirmBO) { employeeAppraisalService.targetConfirm(targetConfirmBO); return Result.ok(); } @PostMapping("/resultEvaluato") @ApiOperation("结果评定") public Result resultEvaluato(@RequestBody ResultEvaluatoBO resultEvaluatoBO) { employeeAppraisalService.resultEvaluato(resultEvaluatoBO); return Result.ok(); } @PostMapping("/queryResultConfirmByAppraisalId/{appraisalId}") @ApiOperation("绩效结果确认") public Result<ResultConfirmByAppraisalIdVO> queryResultConfirmByAppraisalId(@PathVariable("appraisalId") Long appraisalId) { ResultConfirmByAppraisalIdVO resultConfirmByAppraisalIdVO = employeeAppraisalService.queryResultConfirmByAppraisalId(appraisalId); return Result.ok(resultConfirmByAppraisalIdVO); } @PostMapping("/updateScoreLevel") @ApiOperation("修改考评分数") public Result updateScoreLevel(@RequestBody UpdateScoreLevelBO updateScoreLevelBO) { employeeAppraisalService.updateScoreLevel(updateScoreLevelBO); return Result.ok(); } @PostMapping("/resultConfirm/{appraisalId}") @ApiOperation("结果确认") public Result resultConfirm(@PathVariable("appraisalId") Long appraisalId) { employeeAppraisalService.resultConfirm(appraisalId); return Result.ok(); } @PostMapping("/updateSchedule") @ApiOperation("修改目标进度") public Result updateSchedule(@RequestBody UpdateScheduleBO updateScheduleBO) { employeeAppraisalService.updateSchedule(updateScheduleBO); return Result.ok(); } @PostMapping("/queryTargetConfirmScreen") @ApiOperation("查询目标确认列表的绩效筛选条件") public Result<List<AchievementAppraisalVO>> queryTargetConfirmScreen() {
List<AchievementAppraisalVO> list = employeeAppraisalService.queryTargetConfirmScreen(EmployeeHolder.getEmployeeId(), EmployeeAppraisalStatus.PENDING_CONFIRMATION.getValue());
3
2023-10-17 05:49:52+00:00
8k
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_REQUESTS(429, \"Too many requests right now\");\n\n private final int code;\n private final String displayValue;\n\n CodeShellStatus(int i, String s) {\n code = i;\n displayValue = s;\n }\n\n public int getCode() {\n return code;\n }\n\n public String getDisplayValue() {\n return displayValue;\n }\n\n public static CodeShellStatus getStatusByCode(int code) {\n return Stream.of(CodeShellStatus.values())\n .filter(s -> s.getCode() == code)\n .findFirst()\n .orElse(CodeShellStatus.UNKNOWN);\n }\n}" }, { "identifier": "CodeShellCompleteService", "path": "src/main/java/com/codeshell/intellij/services/CodeShellCompleteService.java", "snippet": "public class CodeShellCompleteService {\n private final Logger logger = Logger.getInstance(this.getClass());\n private static final String PREFIX_TAG = \"<fim_prefix>\";\n private static final String SUFFIX_TAG = \"<fim_suffix>\";\n private static final String MIDDLE_TAG = \"<fim_middle>\";\n private static final String REG_EXP = \"data:\\\\s?(.*?)\\n\";\n private static final Pattern PATTERN = Pattern.compile(REG_EXP);\n private static long lastRequestTime = 0;\n private static boolean httpRequestFinFlag = true;\n private int statusCode = 200;\n\n public String[] getCodeCompletionHints(CharSequence editorContents, int cursorPosition) {\n CodeShellSettings settings = CodeShellSettings.getInstance();\n String contents = editorContents.toString();\n if (!httpRequestFinFlag || !settings.isSaytEnabled() || StringUtils.isBlank(contents)) {\n return null;\n }\n if (contents.contains(PREFIX_TAG) || contents.contains(SUFFIX_TAG) || contents.contains(MIDDLE_TAG) || contents.contains(PrefixString.RESPONSE_END_TAG)) {\n return null;\n }\n String prefix = contents.substring(CodeShellUtils.prefixHandle(0, cursorPosition), cursorPosition);\n String suffix = contents.substring(cursorPosition, CodeShellUtils.suffixHandle(cursorPosition, editorContents.length()));\n String generatedText = \"\";\n String codeShellPrompt = generateFIMPrompt(prefix, suffix);\n if(settings.isCPURadioButtonEnabled()){\n HttpPost httpPost = buildApiPostForCPU(settings, prefix, suffix);\n generatedText = getApiResponseForCPU(settings, httpPost, codeShellPrompt);\n }else{\n HttpPost httpPost = buildApiPostForGPU(settings, codeShellPrompt);\n generatedText = getApiResponseForGPU(settings, httpPost, codeShellPrompt);\n }\n String[] suggestionList = null;\n if (generatedText.contains(MIDDLE_TAG)) {\n String[] parts = generatedText.split(MIDDLE_TAG);\n if (parts.length > 0) {\n suggestionList = StringUtils.splitPreserveAllTokens(parts[1], \"\\n\");\n if (suggestionList.length == 1 && suggestionList[0].trim().isEmpty()) {\n return null;\n }\n if (suggestionList.length > 1) {\n for (int i = 0; i < suggestionList.length; i++) {\n StringBuilder sb = new StringBuilder(suggestionList[i]);\n sb.append(\"\\n\");\n suggestionList[i] = sb.toString();\n }\n }\n }\n }\n return suggestionList;\n }\n\n private String generateFIMPrompt(String prefix, String suffix) {\n return PREFIX_TAG + prefix + SUFFIX_TAG + suffix + MIDDLE_TAG;\n }\n\n private HttpPost buildApiPostForCPU(CodeShellSettings settings, String prefix,String suffix) {\n String apiURL = settings.getServerAddressURL() + CodeShellURI.CPU_COMPLETE.getUri();\n HttpPost httpPost = new HttpPost(apiURL);\n JsonObject httpBody = CodeShellUtils.pakgHttpRequestBodyForCPU(settings, prefix, suffix);\n StringEntity requestEntity = new StringEntity(httpBody.toString(), ContentType.APPLICATION_JSON);\n httpPost.setEntity(requestEntity);\n return httpPost;\n }\n\n private HttpPost buildApiPostForGPU(CodeShellSettings settings, String codeShellPrompt) {\n String apiURL = settings.getServerAddressURL() + CodeShellURI.GPU_COMPLETE.getUri();\n HttpPost httpPost = new HttpPost(apiURL);\n JsonObject httpBody = CodeShellUtils.pakgHttpRequestBodyForGPU(settings, codeShellPrompt);\n StringEntity requestEntity = new StringEntity(httpBody.toString(), ContentType.APPLICATION_JSON);\n httpPost.setEntity(requestEntity);\n return httpPost;\n }\n\n private String getApiResponseForCPU(CodeShellSettings settings, HttpPost httpPost, String codeShellPrompt) {\n String responseText = \"\";\n httpRequestFinFlag = false;\n try {\n CloseableHttpClient httpClient = HttpClients.createDefault();\n HttpResponse response = httpClient.execute(httpPost);\n int oldStatusCode = statusCode;\n statusCode = response.getStatusLine().getStatusCode();\n if (statusCode != oldStatusCode) {\n for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {\n WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);\n }\n }\n if (statusCode != 200) {\n return responseText;\n }\n String responseBody = EntityUtils.toString(response.getEntity(), \"UTF-8\");\n responseText = CodeShellUtils.parseHttpResponseContentForCPU(settings, responseBody, PATTERN);\n httpClient.close();\n } catch (IOException e) {\n logger.error(\"getApiResponseForCPU error\", e);\n } finally {\n httpRequestFinFlag = true;\n }\n return codeShellPrompt + responseText;\n }\n\n private String getApiResponseForGPU(CodeShellSettings settings, HttpPost httpPost, String codeShellPrompt) {\n String responseText = \"\";\n httpRequestFinFlag = false;\n try {\n CloseableHttpClient httpClient = HttpClients.createDefault();\n HttpResponse response = httpClient.execute(httpPost);\n int oldStatusCode = statusCode;\n statusCode = response.getStatusLine().getStatusCode();\n if (statusCode != oldStatusCode) {\n for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {\n WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);\n }\n }\n if (statusCode != 200) {\n return responseText;\n }\n String responseBody = EntityUtils.toString(response.getEntity());\n responseText = CodeShellUtils.parseHttpResponseContentForGPU(settings, responseBody);\n httpClient.close();\n } catch (IOException e) {\n logger.error(\"getApiResponseForGPU error\", e);\n } finally {\n httpRequestFinFlag = true;\n }\n\n return codeShellPrompt + responseText;\n }\n\n public int getStatus() {\n return statusCode;\n }\n\n\n}" }, { "identifier": "CodeShellSettings", "path": "src/main/java/com/codeshell/intellij/settings/CodeShellSettings.java", "snippet": "@State(name = \"CodeShellSettings\", storages = @Storage(\"codeshell_settings.xml\"))\npublic class CodeShellSettings implements PersistentStateComponent<Element> {\n public static final String SETTINGS_TAG = \"CodeShellSettings\";\n private static final String SERVER_ADDRESS_TAG = \"SERVER_ADDRESS_URL\";\n private static final String SAYT_TAG = \"SAYT_ENABLED\";\n private static final String CPU_RADIO_BUTTON_TAG = \"CPU_RADIO_BUTTON_ENABLED\";\n private static final String GPU_RADIO_BUTTON_TAG = \"GPU_RADIO_BUTTON_ENABLED\";\n private static final String TAB_ACTION_TAG = \"TAB_ACTION\";\n private static final String COMPLETION_MAX_TOKENS_TAG = \"COMPLETION_MAX_TOKENS\";\n private static final String CHAT_MAX_TOKENS_TAG = \"CHAT_MAX_TOKENS\";\n private boolean saytEnabled = true;\n private boolean cpuRadioButtonEnabled = true;\n private boolean gpuRadioButtonEnabled = false;\n private String serverAddressURL = \"http://127.0.0.1:8080\";\n private TabActionOption tabActionOption = TabActionOption.ALL;\n private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM;\n private ChatMaxToken chatMaxToken = ChatMaxToken.MEDIUM;\n\n private static final CodeShellSettings SHELL_CODER_SETTINGS_INSTANCE = new CodeShellSettings();\n\n @Override\n public @Nullable Element getState() {\n Element state = new Element(SETTINGS_TAG);\n state.setAttribute(CPU_RADIO_BUTTON_TAG, Boolean.toString(isCPURadioButtonEnabled()));\n state.setAttribute(GPU_RADIO_BUTTON_TAG, Boolean.toString(isGPURadioButtonEnabled()));\n state.setAttribute(SERVER_ADDRESS_TAG, getServerAddressURL());\n state.setAttribute(SAYT_TAG, Boolean.toString(isSaytEnabled()));\n state.setAttribute(TAB_ACTION_TAG, getTabActionOption().name());\n state.setAttribute(COMPLETION_MAX_TOKENS_TAG, getCompletionMaxToken().name());\n state.setAttribute(CHAT_MAX_TOKENS_TAG, getChatMaxToken().name());\n return state;\n }\n\n @Override\n public void loadState(@NotNull Element state) {\n if (Objects.nonNull(state.getAttributeValue(CPU_RADIO_BUTTON_TAG))) {\n setCPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(CPU_RADIO_BUTTON_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(GPU_RADIO_BUTTON_TAG))) {\n setGPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(GPU_RADIO_BUTTON_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(SERVER_ADDRESS_TAG))) {\n setServerAddressURL(state.getAttributeValue(SERVER_ADDRESS_TAG));\n }\n if (Objects.nonNull(state.getAttributeValue(SAYT_TAG))) {\n setSaytEnabled(Boolean.parseBoolean(state.getAttributeValue(SAYT_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(TAB_ACTION_TAG))) {\n setTabActionOption(TabActionOption.valueOf(state.getAttributeValue(TAB_ACTION_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG))) {\n setCompletionMaxToken(CompletionMaxToken.valueOf(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(CHAT_MAX_TOKENS_TAG))) {\n setChatMaxToken(ChatMaxToken.valueOf(state.getAttributeValue(CHAT_MAX_TOKENS_TAG)));\n }\n }\n\n public static CodeShellSettings getInstance() {\n if (Objects.isNull(ApplicationManager.getApplication())) {\n return SHELL_CODER_SETTINGS_INSTANCE;\n }\n\n CodeShellSettings service = ApplicationManager.getApplication().getService(CodeShellSettings.class);\n if (Objects.isNull(service)) {\n return SHELL_CODER_SETTINGS_INSTANCE;\n }\n return service;\n }\n\n public boolean isSaytEnabled() {\n return saytEnabled;\n }\n\n public void setSaytEnabled(boolean saytEnabled) {\n this.saytEnabled = saytEnabled;\n }\n\n public void toggleSaytEnabled() {\n this.saytEnabled = !this.saytEnabled;\n }\n\n public boolean isCPURadioButtonEnabled() {\n return cpuRadioButtonEnabled;\n }\n\n public void setCPURadioButtonEnabled(boolean cpuRadioButtonEnabled) {\n this.cpuRadioButtonEnabled = cpuRadioButtonEnabled;\n }\n\n public boolean isGPURadioButtonEnabled() {\n return gpuRadioButtonEnabled;\n }\n\n public void setGPURadioButtonEnabled(boolean gpuRadioButtonEnabled) {\n this.gpuRadioButtonEnabled = gpuRadioButtonEnabled;\n }\n\n public String getServerAddressURL() {\n return serverAddressURL;\n }\n\n public void setServerAddressURL(String serverAddressURL) {\n this.serverAddressURL = serverAddressURL;\n }\n\n public CompletionMaxToken getCompletionMaxToken() {\n return completionMaxToken;\n }\n\n public void setCompletionMaxToken(CompletionMaxToken completionMaxToken) {\n this.completionMaxToken = completionMaxToken;\n }\n\n public ChatMaxToken getChatMaxToken() {\n return chatMaxToken;\n }\n\n public void setChatMaxToken(ChatMaxToken chatMaxToken) {\n this.chatMaxToken = chatMaxToken;\n }\n\n public TabActionOption getTabActionOption() {\n return tabActionOption;\n }\n\n public void setTabActionOption(TabActionOption tabActionOption) {\n this.tabActionOption = tabActionOption;\n }\n\n}" }, { "identifier": "CodeGenHintRenderer", "path": "src/main/java/com/codeshell/intellij/utils/CodeGenHintRenderer.java", "snippet": "public class CodeGenHintRenderer implements EditorCustomElementRenderer {\n private final String myText;\n private Font myFont;\n\n public CodeGenHintRenderer(String text, Font font) {\n myText = text;\n myFont = font;\n }\n\n public CodeGenHintRenderer(String text) {\n myText = text;\n }\n\n @Override\n public int calcWidthInPixels(@NotNull Inlay inlay) {\n Editor editor = inlay.getEditor();\n Font font = editor.getColorsScheme().getFont(EditorFontType.PLAIN);\n myFont = new Font(font.getName(), Font.ITALIC, font.getSize());\n return editor.getContentComponent().getFontMetrics(font).stringWidth(myText);\n }\n\n @Override\n public void paint(@NotNull Inlay inlay, @NotNull Graphics g, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {\n g.setColor(JBColor.GRAY);\n g.setFont(myFont);\n g.drawString(myText, targetRegion.x, targetRegion.y + targetRegion.height - (int) Math.ceil((double) g.getFontMetrics().getFont().getSize() / 2) + 1);\n }\n\n}" }, { "identifier": "CodeShellIcons", "path": "src/main/java/com/codeshell/intellij/utils/CodeShellIcons.java", "snippet": "public interface CodeShellIcons {\n Icon Action = IconLoader.getIcon(\"/icons/actionIcon.svg\", CodeShellIcons.class);\n Icon ActionDark = IconLoader.getIcon(\"/icons/actionIcon_dark.svg\", CodeShellIcons.class);\n Icon WidgetEnabled = IconLoader.getIcon(\"/icons/widgetEnabled.svg\", CodeShellIcons.class);\n Icon WidgetEnabledDark = IconLoader.getIcon(\"/icons/widgetEnabled_dark.svg\", CodeShellIcons.class);\n Icon WidgetDisabled = IconLoader.getIcon(\"/icons/widgetDisabled.svg\", CodeShellIcons.class);\n Icon WidgetDisabledDark = IconLoader.getIcon(\"/icons/widgetDisabled_dark.svg\", CodeShellIcons.class);\n Icon WidgetError = IconLoader.getIcon(\"/icons/widgetError.svg\", CodeShellIcons.class);\n Icon WidgetErrorDark = IconLoader.getIcon(\"/icons/widgetError_dark.svg\", CodeShellIcons.class);\n}" }, { "identifier": "CodeShellUtils", "path": "src/main/java/com/codeshell/intellij/utils/CodeShellUtils.java", "snippet": "public class CodeShellUtils {\n public static String includePreText(String preText, String language, String text) {\n String sufText = \"\\n```\" + language + \"\\n\" + text + \"\\n```\\n\";\n return String.format(preText, language, sufText);\n }\n public static int prefixHandle(int begin, int end) {\n if (end - begin > 3000) {\n return end - 3000;\n } else {\n return begin;\n }\n }\n public static int suffixHandle(int begin, int end) {\n if (end - begin > 256) {\n return begin + 256;\n } else {\n return end;\n }\n }\n\n public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){\n JsonObject httpBody = new JsonObject();\n httpBody.addProperty(\"input_prefix\", prefix);\n httpBody.addProperty(\"input_suffix\", suffix);\n httpBody.addProperty(\"n_predict\", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));\n httpBody.addProperty(\"temperature\", 0.2);\n httpBody.addProperty(\"repetition_penalty\", 1.0);\n httpBody.addProperty(\"top_k\", 10);\n httpBody.addProperty(\"top_p\", 0.95);\n// httpBody.addProperty(\"prompt\", PrefixString.REQUST_END_TAG + codeShellPrompt);\n// httpBody.addProperty(\"frequency_penalty\", 1.2);\n// httpBody.addProperty(\"n_predict\", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));\n// httpBody.addProperty(\"stream\", false);\n// JsonArray stopArray = new JsonArray();\n// stopArray.add(\"|<end>|\");\n// httpBody.add(\"stop\", stopArray);\n return httpBody;\n }\n\n public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){\n JsonObject httpBody = new JsonObject();\n httpBody.addProperty(\"inputs\", codeShellPrompt);\n JsonObject parameters = new JsonObject();\n parameters.addProperty(\"max_new_tokens\", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));\n httpBody.add(\"parameters\", parameters);\n return httpBody;\n }\n\n public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){\n String generatedText = \"\";\n Matcher matcher = pattern.matcher(responseBody);\n StringBuilder contentBuilder = new StringBuilder();\n while (matcher.find()) {\n String jsonString = matcher.group(1);\n JSONObject json = JSONObject.parseObject(jsonString);\n String content = json.getString(\"content\");\n if(StringUtils.equalsAny(content, \"<|endoftext|>\", \"\")){\n continue;\n }\n contentBuilder.append(content);\n }\n return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, \"\");\n }\n\n public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){\n String generatedText = \"\";\n Gson gson = new Gson();\n GenerateModel generateModel = gson.fromJson(responseBody, GenerateModel.class);\n if (StringUtils.isNotBlank(generateModel.getGenerated_text())) {\n generatedText = generateModel.getGenerated_text();\n }\n return generatedText.replace(PrefixString.RESPONSE_END_TAG, \"\");\n }\n\n public static String getIDEVersion(String whichVersion) {\n ApplicationInfo applicationInfo = ApplicationInfo.getInstance();\n String version = \"\";\n try {\n if (whichVersion.equalsIgnoreCase(\"major\")) {\n version = applicationInfo.getMajorVersion();\n } else {\n version = applicationInfo.getFullVersion();\n }\n } catch (Exception e) {\n Logger.getInstance(CodeShellUtils.class).error(\"get IDE full version error\", e);\n }\n return version;\n }\n\n public static void addCodeSuggestion(Editor focusedEditor, VirtualFile file, int suggestionPosition, String[] hintList) {\n WriteCommandAction.runWriteCommandAction(focusedEditor.getProject(), () -> {\n if (suggestionPosition != focusedEditor.getCaretModel().getOffset()) {\n return;\n }\n if (Objects.nonNull(focusedEditor.getSelectionModel().getSelectedText())) {\n return;\n }\n\n file.putUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION, hintList);\n file.putUserData(CodeShellWidget.SHELL_CODER_POSITION, suggestionPosition);\n\n InlayModel inlayModel = focusedEditor.getInlayModel();\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n if (Objects.nonNull(hintList) && hintList.length > 0) {\n if (!hintList[0].trim().isEmpty()) {\n inlayModel.addInlineElement(suggestionPosition, true, new CodeGenHintRenderer(hintList[0]));\n }\n for (int i = 1; i < hintList.length; i++) {\n inlayModel.addBlockElement(suggestionPosition, false, false, 0, new CodeGenHintRenderer(hintList[i]));\n }\n }\n });\n }\n\n public static void disposeInlayHints(Inlay<?> inlay) {\n if (inlay.getRenderer() instanceof CodeGenHintRenderer) {\n inlay.dispose();\n }\n }\n\n}" }, { "identifier": "EditorUtils", "path": "src/main/java/com/codeshell/intellij/utils/EditorUtils.java", "snippet": "public class EditorUtils {\n\n public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, String preText) {\n return getFileSelectionDetails(editor, psiFile, false, preText);\n }\n\n public static boolean isNoneTextSelected(Editor editor) {\n return Objects.isNull(editor) || StringUtils.isEmpty(editor.getCaretModel().getCurrentCaret().getSelectedText());\n }\n\n public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, boolean isCodeNote, String preText) {\n if (Objects.isNull(editor)) {\n return getEmptyRange();\n } else {\n Document document = editor.getDocument();\n int startOffset;\n int endOffset;\n String editorText;\n\n if (editor.getSelectionModel().hasSelection()) {\n startOffset = editor.getSelectionModel().getSelectionStart();\n endOffset = editor.getSelectionModel().getSelectionEnd();\n editorText = editor.getSelectionModel().getSelectedText();\n } else {\n LogicalPosition logicalPos = editor.getCaretModel().getCurrentCaret().getLogicalPosition();\n int line = logicalPos.line;\n startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, 0));\n endOffset = editor.logicalPositionToOffset(new LogicalPosition(line, Integer.MAX_VALUE));\n editorText = lspPosition(document, endOffset).get(\"text\").toString();\n if (isCodeNote) {\n editor.getDocument();\n for (int linenumber = 0; linenumber < editor.getDocument().getLineCount(); ++linenumber) {\n startOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, 0));\n endOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, Integer.MAX_VALUE));\n String tempText = lspPosition(document, endOffset).get(\"text\").toString();\n if (Objects.nonNull(tempText) && !\"\\\"\\\"\".equals(tempText.trim()) && !tempText.trim().isEmpty()) {\n editorText = tempText;\n break;\n }\n }\n }\n }\n JsonObject range = new JsonObject();\n range.add(\"start\", lspPosition(document, startOffset));\n range.add(\"end\", lspPosition(document, endOffset));\n range.addProperty(\"selectedText\", includePreText(preText, psiFile.getLanguage().getID(), editorText));\n JsonObject sendText = new JsonObject();\n sendText.addProperty(\"inputs\", includePreText(preText, psiFile.getLanguage().getID(), editorText));\n JsonObject parameters = new JsonObject();\n parameters.addProperty(\"max_new_tokens\", CodeShellSettings.getInstance().getChatMaxToken().getDescription());\n sendText.add(\"parameters\", parameters);\n\n JsonObject returnObj = new JsonObject();\n returnObj.add(\"range\", range);\n if(CodeShellSettings.getInstance().isCPURadioButtonEnabled()){\n returnObj.addProperty(\"sendUrl\", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.CPU_CHAT.getUri());\n returnObj.addProperty(\"modelType\", \"CPU\");\n }else{\n returnObj.addProperty(\"sendUrl\", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.GPU_CHAT.getUri());\n returnObj.addProperty(\"modelType\", \"GPU\");\n }\n returnObj.addProperty(\"maxToken\", CodeShellSettings.getInstance().getChatMaxToken().getDescription());\n returnObj.add(\"sendText\", sendText);\n return returnObj;\n }\n }\n\n public static JsonObject lspPosition(Document document, int offset) {\n int line = document.getLineNumber(offset);\n int lineStart = document.getLineStartOffset(line);\n String lineTextBeforeOffset = document.getText(TextRange.create(lineStart, offset));\n int column = lineTextBeforeOffset.length();\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"line\", line);\n jsonObject.addProperty(\"column\", column);\n jsonObject.addProperty(\"text\", lineTextBeforeOffset);\n return jsonObject;\n }\n\n public static JsonObject getEmptyRange() {\n JsonObject jsonObject = new JsonObject();\n JsonObject range = new JsonObject();\n JsonObject lineCol = new JsonObject();\n lineCol.addProperty(\"line\", \"0\");\n lineCol.addProperty(\"column\", \"0\");\n lineCol.addProperty(\"text\", \"0\");\n range.add(\"start\", lineCol);\n range.add(\"end\", lineCol);\n jsonObject.add(\"range\", range);\n jsonObject.addProperty(\"selectedText\", \"\");\n return jsonObject;\n }\n\n private static String includePreText(String preText, String language, String text) {\n String sufText = \"\\n```\" + language + \"\\n\" + text + \"\\n```\\n\";\n return String.format(preText, language, sufText);\n }\n\n public static boolean isMainEditor(Editor editor) {\n return editor.getEditorKind() == EditorKind.MAIN_EDITOR || ApplicationManager.getApplication().isUnitTestMode();\n }\n\n}" } ]
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;
6,754
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();
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;
6
2023-10-18 06:29:13+00:00
8k
djkcyl/Shamrock
qqinterface/src/main/java/tencent/im/oidb/cmd0x5eb/oidb_0x5eb.java
[ { "identifier": "ByteStringMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java", "snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr, int i2, int i3) {\n return null;\n }\n\n public static ByteStringMicro copyFromUtf8(String str) {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public int size() {\n return 0;\n }\n\n public byte[] toByteArray() {\n return null;\n }\n\n public String toString(String str) {\n return \"\";\n }\n\n public String toStringUtf8() {\n return \"\";\n }\n}" }, { "identifier": "MessageMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/MessageMicro.java", "snippet": "public class MessageMicro<T extends MessageMicro<T>> {\n public final T mergeFrom(byte[] bArr) {\n return null;\n }\n\n public final byte[] toByteArray() {\n return null;\n }\n\n public T get() {\n return null;\n }\n\n public void set(T t) {\n }\n}" }, { "identifier": "PBBytesField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBBytesField.java", "snippet": "public class PBBytesField extends PBPrimitiveField<ByteStringMicro> {\n public static PBField<ByteStringMicro> __repeatHelper__;\n\n public PBBytesField(ByteStringMicro byteStringMicro, boolean z) {\n }\n\n public ByteStringMicro get() {\n return null;\n }\n\n public void set(ByteStringMicro byteStringMicro) {\n }\n}" }, { "identifier": "PBField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBField.java", "snippet": "public abstract class PBField<T> {\n public static <T extends MessageMicro<T>> PBRepeatMessageField<T> initRepeatMessage(Class<T> cls) {\n return new PBRepeatMessageField<>(cls);\n }\n\n public static <T> PBRepeatField<T> initRepeat(PBField<T> pBField) {\n return new PBRepeatField<>(pBField);\n }\n\n public static PBUInt32Field initUInt32(int i2) {\n return new PBUInt32Field(i2, false);\n }\n\n public static PBStringField initString(String str) {\n return new PBStringField(str, false);\n }\n\n public static PBBytesField initBytes(ByteStringMicro byteStringMicro) {\n return new PBBytesField(byteStringMicro, false);\n }\n\n public static PBBoolField initBool(boolean z) {\n return new PBBoolField(z, false);\n }\n\n public static PBInt32Field initInt32(int i2) {\n return new PBInt32Field(i2, false);\n }\n\n public static PBUInt64Field initUInt64(long j2) {\n return new PBUInt64Field(j2, false);\n }\n\n public static PBInt64Field initInt64(long j2) {\n return new PBInt64Field(j2, false);\n }\n\n public static PBEnumField initEnum(int i2) {\n return new PBEnumField(i2, false);\n }\n}" }, { "identifier": "PBStringField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBStringField.java", "snippet": "public class PBStringField extends PBPrimitiveField<String>{\n public PBStringField(String str, boolean z) {\n }\n\n public void set(String str, boolean z) {\n }\n\n public void set(String str) {\n }\n\n public String get() {\n return \"\";\n }\n}" }, { "identifier": "PBUInt32Field", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt32Field.java", "snippet": "public class PBUInt32Field extends PBPrimitiveField<Integer> {\n public static PBUInt32Field __repeatHelper__;\n\n public PBUInt32Field(int i2, boolean z) {\n }\n\n public void set(int i2) {\n\n }\n\n public int get() {\n return 0;\n }\n}" }, { "identifier": "PBUInt64Field", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt64Field.java", "snippet": "public class PBUInt64Field extends PBPrimitiveField<Long> {\n public static PBField<Long> __repeatHelper__;\n\n public PBUInt64Field(long i2, boolean z) {\n }\n\n public void set(long i2) {\n\n }\n\n public long get() {\n return 0;\n }\n}" } ]
import com.tencent.mobileqq.pb.ByteStringMicro; import com.tencent.mobileqq.pb.MessageMicro; import com.tencent.mobileqq.pb.PBBytesField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBStringField; import com.tencent.mobileqq.pb.PBUInt32Field; import com.tencent.mobileqq.pb.PBUInt64Field;
4,324
public final PBUInt32Field uint32_input_status_flag; public final PBUInt32Field uint32_lang1; public final PBUInt32Field uint32_lang2; public final PBUInt32Field uint32_lang3; public final PBUInt32Field uint32_lflag; public final PBUInt32Field uint32_lightalk_switch; public final PBUInt32Field uint32_love_status; public final PBUInt32Field uint32_mss_update_time; public final PBUInt32Field uint32_music_ring_autoplay; public final PBUInt32Field uint32_music_ring_redpoint; public final PBUInt32Field uint32_music_ring_visible; public final PBUInt32Field uint32_normal_night_mode_flag; public final PBUInt32Field uint32_notify_on_like_ranking_list_flag; public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag; public final PBUInt32Field uint32_oin; public final PBUInt32Field uint32_online_status_avatar_switch; public final PBUInt32Field uint32_plate_of_king_dan; public final PBUInt32Field uint32_plate_of_king_dan_display_switch; public final PBUInt32Field uint32_posterfont_id; public final PBUInt32Field uint32_preload_disable_flag; public final PBUInt32Field uint32_profession; public final PBUInt32Field uint32_profile_age_visible; public final PBUInt32Field uint32_profile_anonymous_answer_switch; public final PBUInt32Field uint32_profile_birthday_visible; public final PBUInt32Field uint32_profile_college_visible; public final PBUInt32Field uint32_profile_company_visible; public final PBUInt32Field uint32_profile_constellation_visible; public final PBUInt32Field uint32_profile_dressup_switch; public final PBUInt32Field uint32_profile_email_visible; public final PBUInt32Field uint32_profile_hometown_visible; public final PBUInt32Field uint32_profile_interest_switch; public final PBUInt32Field uint32_profile_life_achievement_switch; public final PBUInt32Field uint32_profile_location_visible; public final PBUInt32Field uint32_profile_membership_and_rank; public final PBUInt32Field uint32_profile_miniapp_switch; public final PBUInt32Field uint32_profile_music_switch; public final PBUInt32Field uint32_profile_musicbox_switch; public final PBUInt32Field uint32_profile_personal_note_visible; public final PBUInt32Field uint32_profile_personality_label_switch; public final PBUInt32Field uint32_profile_present_switch; public final PBUInt32Field uint32_profile_privilege; public final PBUInt32Field uint32_profile_profession_visible; public final PBUInt32Field uint32_profile_qqcard_switch; public final PBUInt32Field uint32_profile_qqcircle_switch; public final PBUInt32Field uint32_profile_sex_visible; public final PBUInt32Field uint32_profile_show_idol_switch; public final PBUInt32Field uint32_profile_splendid_switch; public final PBUInt32Field uint32_profile_sticky_note_offline; public final PBUInt32Field uint32_profile_sticky_note_switch; public final PBUInt32Field uint32_profile_weishi_switch; public final PBUInt32Field uint32_profile_wz_game_card_switch; public final PBUInt32Field uint32_profile_wz_game_skin_switch; public final PBUInt32Field uint32_pstn_c2c_call_time; public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_c2c_try_flag; public final PBUInt32Field uint32_pstn_c2c_vip; public final PBUInt32Field uint32_pstn_ever_c2c_vip; public final PBUInt32Field uint32_pstn_ever_multi_vip; public final PBUInt32Field uint32_pstn_multi_call_time; public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_multi_try_flag; public final PBUInt32Field uint32_pstn_multi_vip; public final PBUInt32Field uint32_qq_assistant_switch; public final PBUInt32Field uint32_req_font_effect_id; public final PBUInt32Field uint32_req_global_ring_id; public final PBUInt32Field uint32_req_invite2group_auto_agree_flag; public final PBUInt32Field uint32_req_medalwall_flag; public final PBUInt32Field uint32_req_push_notice_flag; public final PBUInt32Field uint32_req_small_world_head_flag; public final PBUInt32Field uint32_rsp_connections_switch_id; public final PBUInt32Field uint32_rsp_listen_together_player_id; public final PBUInt32Field uint32_rsp_qq_level_icon_type; public final PBUInt32Field uint32_rsp_theme_font_id; public final PBUInt32Field uint32_school_status_flag; public final PBUInt32Field uint32_simple_ui_pref; public final PBUInt32Field uint32_simple_ui_switch; public final PBUInt32Field uint32_simple_update_time; public final PBUInt32Field uint32_stranger_vote_switch; public final PBUInt32Field uint32_subaccount_display_third_qq_flag; public final PBUInt32Field uint32_subscribe_nearbyassistant_switch; public final PBUInt32Field uint32_suspend_effect_id; public final PBUInt32Field uint32_sync_C2C_message_switch; public final PBUInt32Field uint32_torch_disable_flag; public final PBUInt32Field uint32_torchbearer_flag; public final PBUInt32Field uint32_troop_honor_rich_flag; public final PBUInt32Field uint32_troop_lucky_character_switch; public final PBUInt32Field uint32_troophonor_switch; public final PBUInt32Field uint32_vas_colorring_id; public final PBUInt32Field uint32_vas_diy_font_timestamp; public final PBUInt32Field uint32_vas_emoticon_usage_info; public final PBUInt32Field uint32_vas_face_id; public final PBUInt32Field uint32_vas_font_id; public final PBUInt32Field uint32_vas_magicfont_flag; public final PBUInt32Field uint32_vas_pendant_diy_id; public final PBUInt32Field uint32_vas_praise_id; public final PBUInt32Field uint32_vas_voicebubble_id; public final PBUInt32Field uint32_vip_flag; public final PBUInt32Field uint32_zplan_add_frd; public final PBUInt32Field uint32_zplan_cmshow_month_active_user; public final PBUInt32Field uint32_zplan_master_show; public final PBUInt32Field uint32_zplan_message_notice_switch; public final PBUInt32Field uint32_zplan_open; public final PBUInt32Field uint32_zplan_operators_network_switch; public final PBUInt32Field uint32_zplan_profile_card_show; public final PBUInt32Field uint32_zplan_qzone_show; public final PBUInt32Field uint32_zplan_samestyle_asset_switch; public final PBUInt32Field uint32_zplan_samestyle_package_switch; public final PBUInt64Field uint64_face_addon_id; public final PBUInt64Field uint64_game_appid; public final PBUInt64Field uint64_game_last_login_time; public final PBUInt64Field uint64_uin = PBField.initUInt64(0); public final PBUInt32Field unit32_concise_mode_flag; public final PBUInt32Field unit32_hide_camera_emoticon_flag; public final PBUInt32Field unit32_hide_cm_show_emoticon_flag; public final PBUInt32Field unit32_online_state_praise_notify; public final PBBytesField zplan_appearanceKey; public final PBUInt32Field zplan_appearanceKey_time; public final PBUInt32Field zplan_avatar_gender; public UdcUinData() {
package tencent.im.oidb.cmd0x5eb; public class oidb_0x5eb { public static final class UdcUinData extends MessageMicro<UdcUinData> { public final PBBytesField bytes_basic_cli_flag; public final PBBytesField bytes_basic_svr_flag; public final PBBytesField bytes_birthday; public final PBBytesField bytes_city; public final PBBytesField bytes_city_id; public final PBBytesField bytes_country; public final PBBytesField bytes_full_age; public final PBBytesField bytes_full_birthday; public final PBBytesField bytes_mss1_service; public final PBBytesField bytes_mss2_identity; public final PBBytesField bytes_mss3_bitmapextra; public final PBBytesField bytes_music_gene; public final PBBytesField bytes_nick; public final PBBytesField bytes_openid; public final PBBytesField bytes_province; public final PBBytesField bytes_req_vip_ext_id; public final PBBytesField bytes_stranger_declare; public final PBBytesField bytes_stranger_nick; public final PBUInt32Field int32_history_num_flag; public final PBUInt32Field roam_flag_qq_7day; public final PBUInt32Field roam_flag_svip_2year; public final PBUInt32Field roam_flag_svip_5year; public final PBUInt32Field roam_flag_svip_forever; public final PBUInt32Field roam_flag_vip_30day; public final PBStringField str_zplanphoto_url; public final PBUInt32Field uint32_400_flag; public final PBUInt32Field uint32_age; public final PBUInt32Field uint32_allow; public final PBUInt32Field uint32_alphabetic_font_flag; public final PBUInt32Field uint32_apollo_status; public final PBUInt32Field uint32_apollo_timestamp; public final PBUInt32Field uint32_apollo_vip_flag; public final PBUInt32Field uint32_apollo_vip_level; public final PBUInt32Field uint32_auth_flag; public final PBUInt32Field uint32_auto_to_text_flag; public final PBUInt32Field uint32_bubble_id; public final PBUInt32Field uint32_bubble_unread_switch; public final PBUInt32Field uint32_business_user; public final PBUInt32Field uint32_c2c_aio_shortcut_switch; public final PBUInt32Field uint32_charm; public final PBUInt32Field uint32_charm_level; public final PBUInt32Field uint32_charm_shown; public final PBUInt32Field uint32_city_zone_id; public final PBUInt32Field uint32_cmshow_3d_flag; public final PBUInt32Field uint32_common_place1; public final PBUInt32Field uint32_constellation; public final PBUInt32Field uint32_dance_max_score; public final PBUInt32Field uint32_default_cover_in_use; public final PBUInt32Field uint32_do_not_disturb_mode_time; public final PBUInt32Field uint32_elder_mode_flag; public final PBUInt32Field uint32_ext_flag; public final PBUInt32Field uint32_extend_friend_card_shown; public final PBUInt32Field uint32_extend_friend_flag; public final PBUInt32Field uint32_extend_friend_switch; public final PBUInt32Field uint32_face_id; public final PBUInt32Field uint32_file_assist_top; public final PBUInt32Field uint32_flag_color_note_recent_switch; public final PBUInt32Field uint32_flag_hide_pretty_group_owner_identity; public final PBUInt32Field uint32_flag_is_pretty_group_owner; public final PBUInt32Field uint32_flag_kid_mode_can_pull_group; public final PBUInt32Field uint32_flag_kid_mode_can_search_by_strangers; public final PBUInt32Field uint32_flag_kid_mode_can_search_friends; public final PBUInt32Field uint32_flag_kid_mode_need_phone_verify; public final PBUInt32Field uint32_flag_kid_mode_switch; public final PBUInt32Field uint32_flag_qcircle_cover_switch; public final PBUInt32Field uint32_flag_school_verified; public final PBUInt32Field uint32_flag_study_mode_student; public final PBUInt32Field uint32_flag_study_mode_switch; public final PBUInt32Field uint32_flag_super_yellow_diamond; public final PBUInt32Field uint32_flag_use_mobile_net_switch; public final PBUInt32Field uint32_flag_zplan_edit_avatar; public final PBUInt32Field uint32_forbid_flag; public final PBUInt32Field uint32_freshnews_notify_flag; public final PBUInt32Field uint32_gender; public final PBUInt32Field uint32_global_group_level; public final PBUInt32Field uint32_god_flag; public final PBUInt32Field uint32_god_forbid; public final PBUInt32Field uint32_group_mem_credit_flag; public final PBUInt32Field uint32_guild_gray_flag; public final PBUInt32Field uint32_has_close_leba_youth_mode_plugin; public final PBUInt32Field uint32_hidden_session_switch; public final PBUInt32Field uint32_hidden_session_video_switch; public final PBUInt32Field uint32_input_status_flag; public final PBUInt32Field uint32_lang1; public final PBUInt32Field uint32_lang2; public final PBUInt32Field uint32_lang3; public final PBUInt32Field uint32_lflag; public final PBUInt32Field uint32_lightalk_switch; public final PBUInt32Field uint32_love_status; public final PBUInt32Field uint32_mss_update_time; public final PBUInt32Field uint32_music_ring_autoplay; public final PBUInt32Field uint32_music_ring_redpoint; public final PBUInt32Field uint32_music_ring_visible; public final PBUInt32Field uint32_normal_night_mode_flag; public final PBUInt32Field uint32_notify_on_like_ranking_list_flag; public final PBUInt32Field uint32_notify_partake_like_ranking_list_flag; public final PBUInt32Field uint32_oin; public final PBUInt32Field uint32_online_status_avatar_switch; public final PBUInt32Field uint32_plate_of_king_dan; public final PBUInt32Field uint32_plate_of_king_dan_display_switch; public final PBUInt32Field uint32_posterfont_id; public final PBUInt32Field uint32_preload_disable_flag; public final PBUInt32Field uint32_profession; public final PBUInt32Field uint32_profile_age_visible; public final PBUInt32Field uint32_profile_anonymous_answer_switch; public final PBUInt32Field uint32_profile_birthday_visible; public final PBUInt32Field uint32_profile_college_visible; public final PBUInt32Field uint32_profile_company_visible; public final PBUInt32Field uint32_profile_constellation_visible; public final PBUInt32Field uint32_profile_dressup_switch; public final PBUInt32Field uint32_profile_email_visible; public final PBUInt32Field uint32_profile_hometown_visible; public final PBUInt32Field uint32_profile_interest_switch; public final PBUInt32Field uint32_profile_life_achievement_switch; public final PBUInt32Field uint32_profile_location_visible; public final PBUInt32Field uint32_profile_membership_and_rank; public final PBUInt32Field uint32_profile_miniapp_switch; public final PBUInt32Field uint32_profile_music_switch; public final PBUInt32Field uint32_profile_musicbox_switch; public final PBUInt32Field uint32_profile_personal_note_visible; public final PBUInt32Field uint32_profile_personality_label_switch; public final PBUInt32Field uint32_profile_present_switch; public final PBUInt32Field uint32_profile_privilege; public final PBUInt32Field uint32_profile_profession_visible; public final PBUInt32Field uint32_profile_qqcard_switch; public final PBUInt32Field uint32_profile_qqcircle_switch; public final PBUInt32Field uint32_profile_sex_visible; public final PBUInt32Field uint32_profile_show_idol_switch; public final PBUInt32Field uint32_profile_splendid_switch; public final PBUInt32Field uint32_profile_sticky_note_offline; public final PBUInt32Field uint32_profile_sticky_note_switch; public final PBUInt32Field uint32_profile_weishi_switch; public final PBUInt32Field uint32_profile_wz_game_card_switch; public final PBUInt32Field uint32_profile_wz_game_skin_switch; public final PBUInt32Field uint32_pstn_c2c_call_time; public final PBUInt32Field uint32_pstn_c2c_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_c2c_try_flag; public final PBUInt32Field uint32_pstn_c2c_vip; public final PBUInt32Field uint32_pstn_ever_c2c_vip; public final PBUInt32Field uint32_pstn_ever_multi_vip; public final PBUInt32Field uint32_pstn_multi_call_time; public final PBUInt32Field uint32_pstn_multi_last_guide_recharge_time; public final PBUInt32Field uint32_pstn_multi_try_flag; public final PBUInt32Field uint32_pstn_multi_vip; public final PBUInt32Field uint32_qq_assistant_switch; public final PBUInt32Field uint32_req_font_effect_id; public final PBUInt32Field uint32_req_global_ring_id; public final PBUInt32Field uint32_req_invite2group_auto_agree_flag; public final PBUInt32Field uint32_req_medalwall_flag; public final PBUInt32Field uint32_req_push_notice_flag; public final PBUInt32Field uint32_req_small_world_head_flag; public final PBUInt32Field uint32_rsp_connections_switch_id; public final PBUInt32Field uint32_rsp_listen_together_player_id; public final PBUInt32Field uint32_rsp_qq_level_icon_type; public final PBUInt32Field uint32_rsp_theme_font_id; public final PBUInt32Field uint32_school_status_flag; public final PBUInt32Field uint32_simple_ui_pref; public final PBUInt32Field uint32_simple_ui_switch; public final PBUInt32Field uint32_simple_update_time; public final PBUInt32Field uint32_stranger_vote_switch; public final PBUInt32Field uint32_subaccount_display_third_qq_flag; public final PBUInt32Field uint32_subscribe_nearbyassistant_switch; public final PBUInt32Field uint32_suspend_effect_id; public final PBUInt32Field uint32_sync_C2C_message_switch; public final PBUInt32Field uint32_torch_disable_flag; public final PBUInt32Field uint32_torchbearer_flag; public final PBUInt32Field uint32_troop_honor_rich_flag; public final PBUInt32Field uint32_troop_lucky_character_switch; public final PBUInt32Field uint32_troophonor_switch; public final PBUInt32Field uint32_vas_colorring_id; public final PBUInt32Field uint32_vas_diy_font_timestamp; public final PBUInt32Field uint32_vas_emoticon_usage_info; public final PBUInt32Field uint32_vas_face_id; public final PBUInt32Field uint32_vas_font_id; public final PBUInt32Field uint32_vas_magicfont_flag; public final PBUInt32Field uint32_vas_pendant_diy_id; public final PBUInt32Field uint32_vas_praise_id; public final PBUInt32Field uint32_vas_voicebubble_id; public final PBUInt32Field uint32_vip_flag; public final PBUInt32Field uint32_zplan_add_frd; public final PBUInt32Field uint32_zplan_cmshow_month_active_user; public final PBUInt32Field uint32_zplan_master_show; public final PBUInt32Field uint32_zplan_message_notice_switch; public final PBUInt32Field uint32_zplan_open; public final PBUInt32Field uint32_zplan_operators_network_switch; public final PBUInt32Field uint32_zplan_profile_card_show; public final PBUInt32Field uint32_zplan_qzone_show; public final PBUInt32Field uint32_zplan_samestyle_asset_switch; public final PBUInt32Field uint32_zplan_samestyle_package_switch; public final PBUInt64Field uint64_face_addon_id; public final PBUInt64Field uint64_game_appid; public final PBUInt64Field uint64_game_last_login_time; public final PBUInt64Field uint64_uin = PBField.initUInt64(0); public final PBUInt32Field unit32_concise_mode_flag; public final PBUInt32Field unit32_hide_camera_emoticon_flag; public final PBUInt32Field unit32_hide_cm_show_emoticon_flag; public final PBUInt32Field unit32_online_state_praise_notify; public final PBBytesField zplan_appearanceKey; public final PBUInt32Field zplan_appearanceKey_time; public final PBUInt32Field zplan_avatar_gender; public UdcUinData() {
ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY;
0
2023-10-20 10:43:47+00:00
8k
zhaoeryu/eu-backend
eu-admin/src/main/java/cn/eu/system/controller/SysUserController.java
[ { "identifier": "EuBaseController", "path": "eu-common-core/src/main/java/cn/eu/common/base/controller/EuBaseController.java", "snippet": "public abstract class EuBaseController {\n}" }, { "identifier": "BusinessType", "path": "eu-common-core/src/main/java/cn/eu/common/enums/BusinessType.java", "snippet": "@Getter\r\n@AllArgsConstructor\r\npublic enum BusinessType {\r\n /**\r\n * 其它\r\n */\r\n OTHER(0, \"其它\"),\r\n\r\n /**\r\n * 查询\r\n */\r\n QUERY(1, \"查询\"),\r\n\r\n /**\r\n * 新增\r\n */\r\n INSERT(2, \"新增\"),\r\n\r\n /**\r\n * 修改\r\n */\r\n UPDATE(3, \"修改\"),\r\n\r\n /**\r\n * 删除\r\n */\r\n DELETE(4, \"删除\"),\r\n\r\n /**\r\n * 导出\r\n */\r\n EXPORT(5, \"导出\"),\r\n /**\r\n * 导出模版\r\n */\r\n EXPORT_TEMPLATE(6, \"导出模版\"),\r\n /**\r\n * 导入\r\n */\r\n IMPORT(7, \"导入\"),\r\n /**\r\n * 登录\r\n */\r\n LOGIN(8, \"登录\"),\r\n /**\r\n * 登出\r\n */\r\n LOGOUT(9, \"登出\"),\r\n /**\r\n * 踢人下线\r\n */\r\n KICKOUT(10, \"踢人下线\"),\r\n /**\r\n * 强制注销\r\n */\r\n FORCE_LOGOUT(11, \"强制注销\"),\r\n /**\r\n * 暂停/恢复任务\r\n */\r\n PAUSE_RESUME_JOB(12, \"暂停/恢复任务\"),\r\n /**\r\n * 执行任务\r\n */\r\n EXEC_JOB(13, \"执行任务\");\r\n\r\n\r\n private final int value;\r\n private final String desc;\r\n\r\n public static BusinessType valueOf(Integer value) {\r\n if (value == null) {\r\n return null;\r\n }\r\n for (BusinessType status : BusinessType.values()) {\r\n if (status.value == value) {\r\n return status;\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public static String parseValue(Integer value) {\r\n if (value == null) {\r\n return null;\r\n }\r\n for (BusinessType status : BusinessType.values()) {\r\n if (status.getValue() == value) {\r\n return status.getDesc();\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n public static Integer valueOfDesc(String desc) {\r\n if (desc == null) {\r\n return null;\r\n }\r\n for (BusinessType status : BusinessType.values()) {\r\n if (status.desc.equals(desc)) {\r\n return status.getValue();\r\n }\r\n }\r\n return null;\r\n }\r\n}\r" }, { "identifier": "PageResult", "path": "eu-common-core/src/main/java/cn/eu/common/model/PageResult.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PageResult<T> {\n\n private List<T> records;\n private Long total;\n\n public static <T> PageResult<T> of(List<T> records, Long total) {\n return new PageResult<>(records, total);\n }\n\n public static <T> PageResult<T> of(List<T> records) {\n PageInfo<T> pageInfo = new PageInfo<>(records);\n return of(pageInfo.getList(), pageInfo.getTotal());\n }\n\n}" }, { "identifier": "ResultBody", "path": "eu-common-core/src/main/java/cn/eu/common/model/ResultBody.java", "snippet": "public class ResultBody extends LinkedHashMap<String,Object> implements Serializable {\n private static final long serialVersionUID = 1L;\n\n private static final String CODE_KEY = \"code\";\n private static final String MSG_KEY = \"msg\";\n private static final String TIMESTAMP_KEY = \"timestamp\";\n private static final String PATH_KEY = \"path\";\n private static final String DATA_KEY = \"data\";\n\n public ResultBody() {\n super();\n this.code(IError.SUCCESS.getCode()).msg(IError.SUCCESS.getMessage());\n this.put(TIMESTAMP_KEY, System.currentTimeMillis());\n }\n\n public ResultBody(IError error) {\n super();\n this.code(error.getCode()).msg(error.getMessage());\n this.put(TIMESTAMP_KEY, System.currentTimeMillis());\n }\n\n public static ResultBody of(IError error) {\n return new ResultBody(error);\n }\n\n public static ResultBody ok() {\n return new ResultBody();\n }\n\n public static ResultBody failed() {\n return failed(IError.ERROR.getMessage());\n }\n public static ResultBody failed(String msg) {\n return new ResultBody().code(IError.ERROR.getCode()).msg(msg);\n }\n\n public static ResultBody warn() {\n return warn(IError.WARN.getMessage());\n }\n public static ResultBody warn(String msg) {\n return new ResultBody().code(IError.WARN.getCode()).msg(msg);\n }\n\n @Hidden\n public boolean isSuccess(){\n Object code = this.get(CODE_KEY);\n return code != null && IError.SUCCESS.getCode() == Integer.parseInt(code.toString());\n }\n\n public ResultBody code(int code) {\n this.put(CODE_KEY,code);\n return this;\n }\n\n public ResultBody msg(String message) {\n this.put(MSG_KEY,message);\n return this;\n }\n\n public ResultBody data(Object data){\n this.put(DATA_KEY,data);\n return this;\n }\n\n public ResultBody path(String path) {\n this.put(PATH_KEY, path);\n return this;\n }\n\n public String getCode(){\n return Optional.ofNullable(this.get(CODE_KEY)).map(String::valueOf).orElse(null);\n }\n\n public String getMsg(){\n return Optional.ofNullable(this.get(MSG_KEY)).map(String::valueOf).orElse(null);\n }\n public Object getData(){\n return this.get(DATA_KEY);\n }\n\n public ResultBody putValue(String key, Object value){\n super.put(key,value);\n return this;\n }\n\n public String toJsonString() {\n return JSONObject.toJSONString(this);\n }\n}" }, { "identifier": "EasyExcelHelper", "path": "eu-common-core/src/main/java/cn/eu/common/utils/EasyExcelHelper.java", "snippet": "@Slf4j\npublic class EasyExcelHelper {\n\n /**\n * 导出Excel\n * <code>\n * 例子:EasyExcelHelper.export(response, list, SysUser.class);\n * </code>\n * @param response HttpServletResponse\n * @param dataList 要导出的数据\n * @param clazz 要导出数据的实体类\n * @throws IOException io异常\n */\n public static <T> void export(HttpServletResponse response, List<T> dataList, Class<T> clazz) throws IOException {\n export(response, dataList, clazz, null);\n }\n public static <T> void export(HttpServletResponse response, List<T> dataList, Class<T> clazz, List<String> excludeColumnFieldNames) throws IOException {\n // 构建sheet\n ExcelWriterSheetBuilder builder = EasyExcel.writerSheet(\"Sheet1\")\n .head(clazz);\n\n if (CollUtil.isNotEmpty(excludeColumnFieldNames)) {\n builder.excludeColumnFieldNames(excludeColumnFieldNames);\n }\n\n WriteSheet writeSheet = builder.build();\n\n // 填写数据并写入到response\n EasyExcelWriteSheet sheet = EasyExcelWriteSheet.of(writeSheet, dataList)\n .registerStandardWriteHandler();\n export(response, sheet);\n }\n\n /**\n * 导出Excel\n * <code>\n * EasyExcelHelper.export(response, list, Arrays.asList(\n * EasyExcelCellItem.of(\"ID\" , SysUser::getId),\n * EasyExcelCellItem.of(\"登录名\" , SysUser::getUsername),\n * EasyExcelCellItem.of(\"用户昵称\" , SysUser::getNickname),\n * EasyExcelCellItem.of(\"最后一次活跃时间\" , SysUser::getLastActiveTime)\n * ));\n * </code>\n *\n * @param response HttpServletResponse\n * @param dataList 要导出的数据\n * @param easyExcelCellItems 导出的数据配置\n * @throws IOException io异常\n */\n public static <T> void export(HttpServletResponse response, List<T> dataList, List<EasyExcelCellItem<T>> easyExcelCellItems) throws IOException {\n // 构建Excel头部和内容\n EasyExcelHeadContent headContent = EasyExcelUtil.buildHeadContent(dataList, easyExcelCellItems);\n\n // 构建sheet\n WriteSheet writeSheet = EasyExcel.writerSheet(\"Sheet1\")\n .head(headContent.getHeadList())\n .build();\n\n // 填写数据并写入到response\n EasyExcelWriteSheet sheet = EasyExcelWriteSheet.of(writeSheet, headContent.getContentList())\n .registerStandardWriteHandler();\n export(response, sheet);\n }\n\n public static void export(HttpServletResponse response, EasyExcelWriteSheet... sheetItems) throws IOException {\n Assert.notEmpty(sheetItems, \"最少要写入一个sheet\");\n try {\n ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())\n .autoCloseStream(false)\n .build();\n\n for (EasyExcelWriteSheet sheetItem : sheetItems) {\n // 数据写入sheet\n excelWriter.write(sheetItem.getDataList(), sheetItem.getWriteSheet());\n }\n\n excelWriter.finish();\n } catch (IOException e) {\n // 重置response\n response.reset();\n response.setContentType(\"application/json\");\n response.setCharacterEncoding(\"utf-8\");\n response.getWriter().write(ResultBody.failed()\n .msg(\"下载文件失败\")\n .toJsonString());\n }\n }\n\n public static <T> void importData(MultipartFile file, Class<T> clazz, Consumer<List<T>> saveConsumer) throws IOException {\n importData(file, clazz, saveConsumer, true);\n }\n\n public static <T> void importData(MultipartFile file, Class<T> clazz, Consumer<List<T>> saveConsumer, boolean isPrintLog) throws IOException {\n importData(file, clazz, saveConsumer, isPrintLog, 100);\n }\n\n /**\n * 导出数据\n * @param file MultipartFile\n * @param clazz 实体类类型\n * @param saveConsumer 保存数据的回掉\n * @param isPrintLog 是否打印日志\n * @param batchCount 每隔(batchCount)条存储数据库,然后清理list ,方便内存回收\n * @throws IOException io异常\n */\n public static <T> void importData(MultipartFile file, Class<T> clazz, Consumer<List<T>> saveConsumer, boolean isPrintLog, int batchCount) throws IOException {\n EasyExcel.read(file.getInputStream(), clazz, new ReadListener<T>() {\n /**\n * 缓存的数据\n */\n private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);\n\n @Override\n public void invoke(T entity, AnalysisContext analysisContext) {\n if (isPrintLog) {\n log.debug(\"解析到一条数据:{}\", JSONObject.toJSONString(entity));\n }\n cachedDataList.add(entity);\n // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM\n if (cachedDataList.size() >= batchCount) {\n saveData();\n // 存储完成清理 list\n cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);\n }\n }\n\n @Override\n public void doAfterAllAnalysed(AnalysisContext analysisContext) {\n // 这里也要保存数据,确保最后遗留的数据也存储到数据库\n saveData();\n if (isPrintLog) {\n log.info(\"所有数据解析完成!\");\n }\n }\n\n private void saveData() {\n if (CollUtil.isEmpty(this.cachedDataList)) {\n return;\n }\n saveConsumer.accept(this.cachedDataList);\n }\n }).sheet().doRead();\n }\n\n}" }, { "identifier": "SpringContextHolder", "path": "eu-common-core/src/main/java/cn/eu/common/utils/SpringContextHolder.java", "snippet": "public class SpringContextHolder implements ApplicationContextAware {\n private static ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) {\n SpringContextHolder.applicationContext = applicationContext;\n }\n\n public static ApplicationContext getApplicationContext() {\n checkApplicationContext();\n return applicationContext;\n }\n\n public static Object getBean(String name) {\n checkApplicationContext();\n return applicationContext.getBean(name);\n }\n\n public static <T> T getBean(Class<T> clazz) {\n checkApplicationContext();\n return (T) applicationContext.getBean(clazz);\n }\n\n public static void clear() {\n applicationContext = null;\n }\n\n private static void checkApplicationContext() {\n if (applicationContext == null) {\n throw new IllegalStateException(\"applicationContext未注入Spring容器中\");\n }\n }\n} " }, { "identifier": "LoginCacheRefreshEvent", "path": "eu-admin/src/main/java/cn/eu/event/LoginCacheRefreshEvent.java", "snippet": "public class LoginCacheRefreshEvent extends ApplicationEvent {\n\n public LoginCacheRefreshEvent(Object source) {\n super(source);\n }\n}" }, { "identifier": "PasswordEncoder", "path": "eu-admin/src/main/java/cn/eu/security/PasswordEncoder.java", "snippet": "public class PasswordEncoder {\n\n /**\n * 密码加密\n * @param password 明文密码\n */\n public static String encode(String password) {\n return BCrypt.hashpw(password, BCrypt.gensalt(5));\n }\n\n /**\n * 密码校验\n * @param password 明文密码\n * @param encodedPassword 加密后的密码\n */\n public static boolean matches(String password, String encodedPassword) {\n return BCrypt.checkpw(password, encodedPassword);\n }\n\n public static void main(String[] args) {\n System.out.println(matches(\"admin123\", encode(\"admin123\")));\n }\n}" }, { "identifier": "SysUser", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysUser.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_user\")\npublic class SysUser extends BaseEntity {\n\n private static final long serialVersionUID = 1L;\n\n @ExcelIgnore\n @ExcelProperty(\"ID\")\n @TableId\n private String id;\n /** 登录名 */\n @Xss(message = \"登录名不能包含脚本字符\")\n @ExcelProperty(\"登录名\")\n @NotBlank(message = \"登录名不能为空\")\n private String username;\n /** 用户昵称 */\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @ExcelProperty(\"用户昵称\")\n @NotBlank(message = \"用户昵称不能为空\")\n private String nickname;\n /** 用户头像 */\n @ExcelProperty(value = \"头像\", converter = StringUrlImageConverter.class)\n private String avatar;\n /** 手机号 */\n @ExcelProperty(\"手机号\")\n private String mobile;\n /** 邮箱 */\n @ExcelProperty(\"邮箱\")\n @TableField(updateStrategy = FieldStrategy.IGNORED)\n private String email;\n /** 密码 */\n @ExcelIgnore\n @JsonIgnore // 密码不返回给前端\n private String password;\n /** 性别 */\n @ExcelProperty(value = \"性别\", converter = SysUserSexConverter.class)\n private Integer sex;\n /** 是否管理员 */\n @ExcelProperty(value = \"是否管理员\", converter = SysUserAdminConverter.class)\n private Integer admin;\n /** 部门ID */\n @ExcelProperty(value = \"部门\", converter = SysDeptConverter.class)\n @TableField(updateStrategy = FieldStrategy.IGNORED)\n private Integer deptId;\n /** 账号状态 */\n @ExcelProperty(value = \"账号状态\", converter = SysUserStatusConverter.class)\n private Integer status;\n /** 登录IP */\n @ExcelProperty(\"登录IP\")\n private String loginIp;\n /** 登录时间 */\n @ExcelProperty(\"登录时间\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime loginTime;\n /** 最后一次活跃时间 */\n @ExcelProperty(\"最后一次活跃时间\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime lastActiveTime;\n /** 密码重置时间 */\n @ExcelProperty(\"密码重置时间\")\n private LocalDateTime passwordResetTime;\n\n}" }, { "identifier": "UpdatePasswordBody", "path": "eu-admin/src/main/java/cn/eu/system/model/pojo/UpdatePasswordBody.java", "snippet": "@Data\npublic class UpdatePasswordBody {\n\n @NotBlank(message = \"旧密码不能为空\")\n private String oldPassword;\n @NotBlank(message = \"新密码不能为空\")\n private String newPassword;\n\n}" }, { "identifier": "AssignRoleQuery", "path": "eu-admin/src/main/java/cn/eu/system/model/query/AssignRoleQuery.java", "snippet": "@Data\npublic class AssignRoleQuery {\n\n @NotNull(message = \"角色id不能为空\")\n private Integer roleId;\n /**\n * 是否查询已经拥有该角色的用户\n * 1: 是\n * 0: 否\n */\n @NotNull(message = \"是否查询已经拥有该角色的用户不能为空\")\n private Integer hasRole;\n\n private String nickname;\n private String mobile;\n\n}" }, { "identifier": "SysUserQueryCriteria", "path": "eu-admin/src/main/java/cn/eu/system/model/query/SysUserQueryCriteria.java", "snippet": "@Data\npublic class SysUserQueryCriteria {\n\n @Query(type = Query.Type.LIKE)\n private String nickname;\n @Query\n private String mobile;\n @Query(type = Query.Type.LIKE)\n private String username;\n\n private Integer deptId;\n\n @Query(type = Query.Type.BETWEEN)\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private List<LocalDateTime> lastActiveTime;\n\n}" }, { "identifier": "ISysPostService", "path": "eu-admin/src/main/java/cn/eu/system/service/ISysPostService.java", "snippet": "public interface ISysPostService extends IEuService<SysPost> {\n\n PageResult<SysPost> page(SysPostQueryCriteria criteria, Pageable pageable);\n\n List<SysPost> list(SysPostQueryCriteria criteria);\n\n List<Integer> getPostIdsByUserId(String userId);\n\n void exportTemplate(HttpServletResponse response) throws IOException;\n\n ImportResult importData(MultipartFile file, Integer importMode) throws IOException;\n}" }, { "identifier": "ISysRoleService", "path": "eu-admin/src/main/java/cn/eu/system/service/ISysRoleService.java", "snippet": "public interface ISysRoleService extends IEuService<SysRole> {\n\n PageResult<SysRole> page(SysRoleQueryCriteria criteria, Pageable pageable);\n\n List<SysRole> list(SysRoleQueryCriteria criteria);\n\n List<String> getRolePermissionByUserId(String userId);\n\n List<SysRole> getRolesByUserId(String userId);\n\n List<Integer> getRoleIdsByUserId(String userId);\n\n void createRole(SysRoleDto entity);\n\n void updateRole(SysRoleDto entity);\n\n List<Integer> getMenuIdsByRoleId(Integer roleId);\n List<Integer> getDeptIdsByRoleId(Integer roleId);\n\n void exportTemplate(HttpServletResponse response) throws IOException;\n\n ImportResult importData(MultipartFile file, Integer importMode) throws IOException;\n}" }, { "identifier": "ISysUserService", "path": "eu-admin/src/main/java/cn/eu/system/service/ISysUserService.java", "snippet": "public interface ISysUserService extends IEuService<SysUser> {\n\n PageResult<SysUser> page(SysUserQueryCriteria criteria, Pageable pageable);\n\n List<SysUser> list(SysUserQueryCriteria criteria);\n\n /**\n * 创建用户\n * @param dto\n */\n void createUser(SysUserDto dto);\n\n void updateUser(SysUserDto dto);\n\n void assignRole(String userId, List<Integer> roleIds);\n\n PageResult<SysUser> roleUserList(AssignRoleQuery query, Pageable pageable);\n\n void cancelAuth(AssignRoleDto dto);\n\n void batchAssignRole(AssignRoleDto dto);\n\n int countByRoleIds(List<Integer> roleIds);\n int countByDeptIds(List<Integer> deptId);\n int countByPostIds(List<Integer> postIds);\n\n ImportResult importData(MultipartFile file, Integer importMode) throws IOException;\n\n void exportTemplate(HttpServletResponse response) throws IOException;\n}" } ]
import cn.dev33.satoken.annotation.SaCheckPermission; import cn.dev33.satoken.stp.StpUtil; import cn.eu.common.annotation.Log; import cn.eu.common.base.controller.EuBaseController; import cn.eu.common.enums.BusinessType; import cn.eu.common.model.PageResult; import cn.eu.common.model.ResultBody; import cn.eu.common.utils.EasyExcelHelper; import cn.eu.common.utils.SpringContextHolder; import cn.eu.event.LoginCacheRefreshEvent; import cn.eu.security.PasswordEncoder; import cn.eu.system.domain.SysUser; import cn.eu.system.model.dto.*; import cn.eu.system.model.pojo.UpdatePasswordBody; import cn.eu.system.model.query.AssignRoleQuery; import cn.eu.system.model.query.SysUserQueryCriteria; import cn.eu.system.service.ISysPostService; import cn.eu.system.service.ISysRoleService; import cn.eu.system.service.ISysUserService; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.util.Assert; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.util.*;
5,376
package cn.eu.system.controller; /** * @author zhaoeryu * @since 2023/5/31 */ @Slf4j @RequestMapping("/system/user") @RestController public class SysUserController extends EuBaseController { @Autowired ISysUserService sysUserService; @Autowired ISysRoleService roleService; @Autowired ISysPostService postService; @Log(title = "查看用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false) @SaCheckPermission("system:user:list") @GetMapping("/page")
package cn.eu.system.controller; /** * @author zhaoeryu * @since 2023/5/31 */ @Slf4j @RequestMapping("/system/user") @RestController public class SysUserController extends EuBaseController { @Autowired ISysUserService sysUserService; @Autowired ISysRoleService roleService; @Autowired ISysPostService postService; @Log(title = "查看用户列表", businessType = BusinessType.QUERY, isSaveResponseData = false) @SaCheckPermission("system:user:list") @GetMapping("/page")
public ResultBody page(SysUserQueryCriteria criteria, @PageableDefault(page = 1) Pageable pageable) {
11
2023-10-20 07:08:37+00:00
8k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java
[ { "identifier": "BlockBase01", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/BlockBase01.java", "snippet": "public class BlockBase01 extends Block {\n\n // region Constructors\n protected BlockBase01(Material materialIn) {\n super(materialIn);\n }\n\n public BlockBase01() {\n this(Material.iron);\n this.setCreativeTab(GTCMCreativeTabs.tabMetaBlock01);\n }\n\n public BlockBase01(String unlocalizedName, String localName) {\n this();\n this.unlocalizedName = unlocalizedName;\n texter(localName, \"blockBase01.\" + unlocalizedName + \".name\");\n }\n\n // endregion\n // -----------------------\n // region member variables\n\n private String unlocalizedName;\n\n // endregion\n // -----------------------\n // region getters\n\n @Override\n public String getUnlocalizedName() {\n return this.unlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region setters\n\n public void setUnlocalizedName(String aUnlocalizedName) {\n this.unlocalizedName = aUnlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region Overrides\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < BlockStaticDataClientOnly.iconsBlockMap01.size()\n ? BlockStaticDataClientOnly.iconsBlockMap01.get(meta)\n : BlockStaticDataClientOnly.iconsBlockMap01.get(0);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:MetaBlocks/0\");\n for (int Meta : MetaBlockSet01) {\n BlockStaticDataClientOnly.iconsBlockMap01\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:MetaBlocks/\" + Meta));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : MetaBlockSet01) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n @Override\n public int damageDropped(int meta) {\n return meta;\n }\n\n @Override\n public boolean canBeReplacedByLeaves(IBlockAccess world, int x, int y, int z) {\n return false;\n }\n\n @Override\n public boolean canEntityDestroy(IBlockAccess world, int x, int y, int z, Entity entity) {\n return false;\n }\n\n @Override\n public boolean canCreatureSpawn(EnumCreatureType type, IBlockAccess world, int x, int y, int z) {\n return false;\n }\n\n // endregion\n}" }, { "identifier": "BlockNuclearReactor", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/BlockNuclearReactor.java", "snippet": "public class BlockNuclearReactor extends BlockBase01 {\n\n public BlockNuclearReactor(String unlocalizedName, String localName) {\n this.setUnlocalizedName(unlocalizedName);\n texter(localName, unlocalizedName + \".name\");\n this.setHardness(9.0F);\n this.setResistance(5.0F);\n this.setHarvestLevel(\"wrench\", 1);\n this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab);\n NuclearReactorBlockSet.add(0);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < BlockStaticDataClientOnly.iconsNuclearReactor.size()\n ? BlockStaticDataClientOnly.iconsNuclearReactor.get(meta)\n : BlockStaticDataClientOnly.iconsNuclearReactor.get(0);\n }\n\n public static class innerItemBlock extends ItemBlockBase01 {\n\n public innerItemBlock(Block aBlock) {\n super(aBlock);\n }\n }\n\n public static final Set<Integer> NuclearReactorBlockSet = new HashSet<>();\n\n public static ItemStack NuclearReactorBlockMeta(String i18nName, int meta) {\n\n return initMetaItemStack(i18nName, meta, NuclearReactorBlock, NuclearReactorBlockSet);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : NuclearReactorBlockSet) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:nuclear/0\");\n for (int Meta : NuclearReactorBlockSet) {\n BlockStaticDataClientOnly.iconsNuclearReactor\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:nuclear/\" + Meta));\n }\n }\n}" }, { "identifier": "PhotonControllerUpgradeCasing", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/PhotonControllerUpgradeCasing.java", "snippet": "public class PhotonControllerUpgradeCasing extends BlockBase01 {\n\n // region Constructors\n\n public PhotonControllerUpgradeCasing() {\n this.setHardness(9.0F);\n this.setResistance(5.0F);\n this.setHarvestLevel(\"wrench\", 1);\n this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab);\n PhotonControllerUpgradeCasingSet.add(0);\n GregTech_API.registerMachineBlock(this, -1);\n }\n\n public PhotonControllerUpgradeCasing(String unlocalizedName, String localName) {\n this();\n this.unlocalizedName = unlocalizedName;\n texter(localName, unlocalizedName + \".name\");\n }\n\n // endregion\n // -----------------------\n // region Member Variables\n\n public static Set<Integer> PhotonControllerUpgradeCasingSet = new HashSet<>();\n\n /**\n * The Speed Increment of the Upgrade Casing.\n * Total Speed Increment is the sum of each Upgrade Casing.\n * Total value 10,000 means time cost *0.5 .\n */\n public static int[] speedIncrement = PhotonControllerUpgradeCasingSpeedIncrement;\n // public static int[] speedIncrement = new int[] { /* LV */100, /* MV */200, /* HV */300, /* EV */400, /* IV */500,\n // /* LuV */1000, /* ZPM */2000, /* UV */4000, /* UHV */7000, /* UEV */10000, /* UIV */14000, /* UMV */19000,\n // /* UXV */25000, /* MAX */32000 };\n\n /**\n * Tooltips of these blocks' ItemBlock.\n */\n public static String[][] PhCUpgradeCasingTooltipsArray = new String[14][];\n private IIcon blockIcon;\n private String unlocalizedName;\n\n // endregion\n // -----------------------\n // region Meta Generator\n\n public static ItemStack photonControllerUpgradeCasingMeta(String i18nName, int meta) {\n\n return initMetaItemStack(i18nName, meta, PhotonControllerUpgrade, PhotonControllerUpgradeCasingSet);\n }\n\n public static ItemStack photonControllerUpgradeCasingMeta(String i18nName, int meta, String[] tooltips) {\n // Handle the tooltips\n PhCUpgradeCasingTooltipsArray[meta] = tooltips;\n return photonControllerUpgradeCasingMeta(i18nName, meta);\n }\n\n // endregion\n // -----------------------\n // region Getters\n\n public int getSpeedIncrement(int meta) {\n return speedIncrement[meta];\n }\n\n @Override\n public String getUnlocalizedName() {\n return this.unlocalizedName;\n }\n\n // endregion\n // -----------------------\n // region Setters\n\n public void setSpeedIncrement(int speedIncrement, int meta) {\n PhotonControllerUpgradeCasing.speedIncrement[meta] = speedIncrement;\n }\n\n // endregion\n // -----------------------\n // region Overrides\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < iconsBlockPhotonControllerUpgradeMap.size() ? iconsBlockPhotonControllerUpgradeMap.get(meta)\n : iconsBlockPhotonControllerUpgradeMap.get(0);\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:PhotonControllerUpgrades/0\");\n for (int Meta : PhotonControllerUpgradeCasingSet) {\n iconsBlockPhotonControllerUpgradeMap\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:PhotonControllerUpgrades/\" + Meta));\n }\n }\n\n @Override\n public void onBlockAdded(World aWorld, int aX, int aY, int aZ) {\n if (GregTech_API.isMachineBlock(this, aWorld.getBlockMetadata(aX, aY, aZ))) {\n GregTech_API.causeMachineUpdate(aWorld, aX, aY, aZ);\n }\n }\n\n @Override\n public void breakBlock(World aWorld, int aX, int aY, int aZ, Block aBlock, int aMetaData) {\n if (GregTech_API.isMachineBlock(this, aWorld.getBlockMetadata(aX, aY, aZ))) {\n GregTech_API.causeMachineUpdate(aWorld, aX, aY, aZ);\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : PhotonControllerUpgradeCasingSet) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n // endregion\n\n}" }, { "identifier": "SpaceStationAntiGravityCasing", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/spaceStation/SpaceStationAntiGravityCasing.java", "snippet": "public class SpaceStationAntiGravityCasing extends BlockBase01 {\n\n public SpaceStationAntiGravityCasing() {\n this.setHardness(9.0F);\n this.setResistance(5.0F);\n this.setHarvestLevel(\"wrench\", 1);\n this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab);\n SpaceStationAntiGravityCasingCasingSet.add(0);\n GregTech_API.registerMachineBlock(this, -1);\n }\n\n public SpaceStationAntiGravityCasing(String unlocalizedName, String localName) {\n this();\n this.unlocalizedName = unlocalizedName;\n texter(localName, unlocalizedName + \".name\");\n }\n\n public static Set<Integer> SpaceStationAntiGravityCasingCasingSet = new HashSet<>();\n\n /**\n * Tooltips of these blocks' ItemBlock.\n */\n public static String[][] SpaceStationAntiGravityCasingTooltipsArray = new String[14][];\n private String unlocalizedName;\n\n // endregion\n // -----------------------\n // region Meta Generator\n\n public static ItemStack SpaceStationAntiGravityCasingMeta(String i18nName, int meta) {\n\n return initMetaItemStack(i18nName, meta, SpaceStationAntiGravityBlock, SpaceStationAntiGravityCasingCasingSet);\n }\n\n public static ItemStack SpaceStationAntiGravityCasingMeta(String i18nName, int meta, String[] tooltips) {\n // Handle the tooltips\n SpaceStationAntiGravityCasingTooltipsArray[meta] = tooltips;\n return SpaceStationAntiGravityCasingMeta(i18nName, meta);\n }\n\n // endregion\n // -----------------------\n // region Getters\n\n @Override\n public String getUnlocalizedName() {\n return this.unlocalizedName;\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < iconsSpaceStationAntiGravityCasingMap.size() ? iconsSpaceStationAntiGravityCasingMap.get(meta)\n : iconsSpaceStationAntiGravityCasingMap.get(0);\n }\n\n @Override\n public void onBlockAdded(World aWorld, int aX, int aY, int aZ) {\n if (GregTech_API.isMachineBlock(this, aWorld.getBlockMetadata(aX, aY, aZ))) {\n GregTech_API.causeMachineUpdate(aWorld, aX, aY, aZ);\n }\n }\n\n @Override\n public void breakBlock(World aWorld, int aX, int aY, int aZ, Block aBlock, int aMetaData) {\n if (GregTech_API.isMachineBlock(this, aWorld.getBlockMetadata(aX, aY, aZ))) {\n GregTech_API.causeMachineUpdate(aWorld, aX, aY, aZ);\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : SpaceStationAntiGravityCasingCasingSet) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:SpaceStationAntiGravityCasing/0\");\n for (int Meta : SpaceStationAntiGravityCasingCasingSet) {\n iconsSpaceStationAntiGravityCasingMap\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:SpaceStationAntiGravityCasing/\" + Meta));\n }\n }\n\n // endregion\n}" }, { "identifier": "SpaceStationStructureCasing", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/spaceStation/SpaceStationStructureCasing.java", "snippet": "public class SpaceStationStructureCasing extends BlockBase01 {\n\n public SpaceStationStructureCasing() {\n this.setHardness(9.0F);\n this.setResistance(5.0F);\n this.setHarvestLevel(\"wrench\", 1);\n this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab);\n SpaceStationStructureCasingCasingSet.add(0);\n GregTech_API.registerMachineBlock(this, -1);\n }\n\n public SpaceStationStructureCasing(String unlocalizedName, String localName) {\n this();\n this.unlocalizedName = unlocalizedName;\n texter(localName, unlocalizedName + \".name\");\n }\n\n public static Set<Integer> SpaceStationStructureCasingCasingSet = new HashSet<>();\n\n /**\n * Tooltips of these blocks' ItemBlock.\n */\n public static String[][] SpaceStationStructureCasingTooltipsArray = new String[14][];\n private String unlocalizedName;\n\n // endregion\n // -----------------------\n // region Meta Generator\n\n public static ItemStack SpaceStationStructureCasingMeta(String i18nName, int meta) {\n\n return initMetaItemStack(i18nName, meta, spaceStationStructureBlock, SpaceStationStructureCasingCasingSet);\n }\n\n public static ItemStack SpaceStationStructureCasingMeta(String i18nName, int meta, String[] tooltips) {\n // Handle the tooltips\n SpaceStationStructureCasingTooltipsArray[meta] = tooltips;\n return SpaceStationStructureCasingMeta(i18nName, meta);\n }\n\n // endregion\n // -----------------------\n // region Getters\n\n @Override\n public String getUnlocalizedName() {\n return this.unlocalizedName;\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public IIcon getIcon(int side, int meta) {\n return meta < iconsSpaceStationStructureCasingMap.size() ? iconsSpaceStationStructureCasingMap.get(meta)\n : iconsSpaceStationStructureCasingMap.get(0);\n }\n\n @Override\n public void onBlockAdded(World aWorld, int aX, int aY, int aZ) {\n if (GregTech_API.isMachineBlock(this, aWorld.getBlockMetadata(aX, aY, aZ))) {\n GregTech_API.causeMachineUpdate(aWorld, aX, aY, aZ);\n }\n }\n\n @Override\n public void breakBlock(World aWorld, int aX, int aY, int aZ, Block aBlock, int aMetaData) {\n if (GregTech_API.isMachineBlock(this, aWorld.getBlockMetadata(aX, aY, aZ))) {\n GregTech_API.causeMachineUpdate(aWorld, aX, aY, aZ);\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item aItem, CreativeTabs aCreativeTabs, List list) {\n for (int Meta : SpaceStationStructureCasingCasingSet) {\n list.add(new ItemStack(aItem, 1, Meta));\n }\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerBlockIcons(IIconRegister reg) {\n this.blockIcon = reg.registerIcon(\"gtnhcommunitymod:SpaceStationStructureCasing/0\");\n for (int Meta : SpaceStationStructureCasingCasingSet) {\n iconsSpaceStationStructureCasingMap\n .put(Meta, reg.registerIcon(\"gtnhcommunitymod:SpaceStationStructureCasing/\" + Meta));\n }\n }\n\n // endregion\n}" } ]
import net.minecraft.block.Block; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockBase01; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.BlockNuclearReactor; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.PhotonControllerUpgradeCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationAntiGravityCasing; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings.spaceStation.SpaceStationStructureCasing;
4,490
package com.Nxer.TwistSpaceTechnology.common.block; public class BasicBlocks { public static final Block MetaBlock01 = new BlockBase01("MetaBlock01", "MetaBlock01"); public static final Block PhotonControllerUpgrade = new PhotonControllerUpgradeCasing( "PhotonControllerUpgrades", "Photon Controller Upgrade"); public static final Block spaceStationStructureBlock = new SpaceStationStructureCasing( "SpaceStationStructureBlock", "Space Station Structure Block");
package com.Nxer.TwistSpaceTechnology.common.block; public class BasicBlocks { public static final Block MetaBlock01 = new BlockBase01("MetaBlock01", "MetaBlock01"); public static final Block PhotonControllerUpgrade = new PhotonControllerUpgradeCasing( "PhotonControllerUpgrades", "Photon Controller Upgrade"); public static final Block spaceStationStructureBlock = new SpaceStationStructureCasing( "SpaceStationStructureBlock", "Space Station Structure Block");
public static final Block SpaceStationAntiGravityBlock = new SpaceStationAntiGravityCasing(
3
2023-10-16 09:57:15+00:00
8k
wyjsonGo/GoRouter
GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/processor/GenerateRouteModuleProcessor.java
[ { "identifier": "ACTIVITY", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String ACTIVITY = \"android.app.Activity\";" }, { "identifier": "BOOLEAN_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String BOOLEAN_PACKAGE = LANG + \".Boolean\";" }, { "identifier": "BOOLEAN_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String BOOLEAN_PRIMITIVE = \"boolean\";" }, { "identifier": "BYTE_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String BYTE_PACKAGE = LANG + \".Byte\";" }, { "identifier": "BYTE_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String BYTE_PRIMITIVE = \"byte\";" }, { "identifier": "CHAR_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String CHAR_PACKAGE = LANG + \".Character\";" }, { "identifier": "CHAR_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String CHAR_PRIMITIVE = \"char\";" }, { "identifier": "DOUBLE_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String DOUBLE_PACKAGE = LANG + \".Double\";" }, { "identifier": "DOUBLE_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String DOUBLE_PRIMITIVE = \"double\";" }, { "identifier": "FLOAT_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String FLOAT_PACKAGE = LANG + \".Float\";" }, { "identifier": "FLOAT_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String FLOAT_PRIMITIVE = \"float\";" }, { "identifier": "FRAGMENT", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String FRAGMENT = \"androidx.fragment.app.Fragment\";" }, { "identifier": "GOROUTER", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String GOROUTER = PACKAGE_NAME + \".GoRouter\";" }, { "identifier": "INTEGER_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String INTEGER_PACKAGE = LANG + \".Integer\";" }, { "identifier": "INTEGER_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String INTEGER_PRIMITIVE = \"int\";" }, { "identifier": "I_ROUTE_MODULE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String I_ROUTE_MODULE = PACKAGE_NAME + \".module.interfaces.IRouteModule\";" }, { "identifier": "I_ROUTE_MODULE_GROUP", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String I_ROUTE_MODULE_GROUP = PACKAGE_NAME + \".module.interfaces.IRouteModuleGroup\";" }, { "identifier": "I_ROUTE_MODULE_GROUP_METHOD_NAME_LOAD", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String I_ROUTE_MODULE_GROUP_METHOD_NAME_LOAD = \"load\";" }, { "identifier": "LONG_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String LONG_PACKAGE = LANG + \".Long\";" }, { "identifier": "LONG_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String LONG_PRIMITIVE = \"long\";" }, { "identifier": "METHOD_NAME_LOAD", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_LOAD = \"load\";" }, { "identifier": "METHOD_NAME_LOAD_ROUTE_FOR_x_GROUP", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_LOAD_ROUTE_FOR_x_GROUP = \"loadRouteFor%sGroup\";" }, { "identifier": "METHOD_NAME_LOAD_ROUTE_GROUP", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_LOAD_ROUTE_GROUP = \"loadRouteGroup\";" }, { "identifier": "PARAM_NAME_ROUTE_GROUPS", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String PARAM_NAME_ROUTE_GROUPS = \"routeGroups\";" }, { "identifier": "PARCELABLE_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String PARCELABLE_PACKAGE = \"android.os.Parcelable\";" }, { "identifier": "PREFIX_OF_LOGGER", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String PREFIX_OF_LOGGER = PROJECT + \"::Compiler \";" }, { "identifier": "ROUTE_CENTER", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String ROUTE_CENTER = PACKAGE_NAME + \".core.RouteCenter\";" }, { "identifier": "ROUTE_CENTER_METHOD_NAME_GET_ROUTE_GROUPS", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String ROUTE_CENTER_METHOD_NAME_GET_ROUTE_GROUPS = \"getRouteGroups\";" }, { "identifier": "ROUTE_MODULE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String ROUTE_MODULE = PACKAGE_NAME + \".module.route\";" }, { "identifier": "ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX = SEPARATOR + \"Route\";" }, { "identifier": "SERIALIZABLE_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String SERIALIZABLE_PACKAGE = \"java.io.Serializable\";" }, { "identifier": "SHORT_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String SHORT_PACKAGE = LANG + \".Short\";" }, { "identifier": "SHORT_PRIMITIVE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String SHORT_PRIMITIVE = \"short\";" }, { "identifier": "STRING_PACKAGE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String STRING_PACKAGE = LANG + \".String\";" }, { "identifier": "WARNING_TIPS", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String WARNING_TIPS = \"DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY GOROUTER.\";" }, { "identifier": "DocumentUtils", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/doc/DocumentUtils.java", "snippet": "public class DocumentUtils {\n\n private static Writer docWriter;\n private static DocumentModel documentModel;\n private static boolean isDocEnable;\n\n public static void createDoc(Filer mFiler, String moduleName, Logger logger, boolean isEnable) {\n isDocEnable = isEnable;\n if (!isDocEnable)\n return;\n try {\n documentModel = new DocumentModel();\n docWriter = mFiler.createResource(\n StandardLocation.SOURCE_OUTPUT,\n DOCS,\n moduleName + \"-\" + DOCUMENT_FILE_NAME\n ).openWriter();\n } catch (IOException e) {\n logger.error(moduleName + \" Failed to create the document because \" + e.getMessage());\n }\n }\n\n public static void generateDoc(String moduleName, Logger logger) {\n if (!isDocEnable)\n return;\n try {\n docWriter.append(new GsonBuilder().setPrettyPrinting().create().toJson(documentModel));\n docWriter.flush();\n docWriter.close();\n } catch (IOException e) {\n logger.error(moduleName + \" Failed to generate the document because \" + e.getMessage());\n }\n }\n\n public static void addServiceDoc(String moduleName, Logger logger, Element element, Service service) {\n if (!isDocEnable)\n return;\n try {\n String className = ((TypeElement) element).getInterfaces().get(0).toString();\n String key = className.substring(className.lastIndexOf(\".\") + 1);\n if (!StringUtils.isEmpty(service.alias())) {\n key += \"$\" + service.alias();\n }\n documentModel.getServices().put(key, new ServiceModel(service.alias(), className, element.toString(), service.remark(), moduleName));\n } catch (Exception e) {\n logger.error(moduleName + \" Failed to add service [\" + element.toString() + \"] document, \" + e.getMessage());\n }\n }\n\n public static void addInterceptorDoc(String moduleName, Logger logger, Element element, Interceptor interceptor) {\n if (!isDocEnable)\n return;\n try {\n documentModel.getInterceptors().add(new InterceptorModel(interceptor.ordinal(), element.toString(), interceptor.remark(), moduleName));\n } catch (Exception e) {\n logger.error(moduleName + \" Failed to add interceptor [\" + element.toString() + \"] document, \" + e.getMessage());\n }\n }\n\n public static void addRouteGroupDoc(String moduleName, Logger logger, String group, List<RouteModel> routeModelList) {\n if (!isDocEnable)\n return;\n try {\n documentModel.getRoutes().put(group, routeModelList);\n } catch (Exception e) {\n logger.error(moduleName + \" Failed to add route group [\" + group + \"] document, \" + e.getMessage());\n }\n }\n\n public static void addRouteDoc(String moduleName, Logger logger, Element element, List<RouteModel> routeModelList, Route route, String typeDoc, Types types, TypeMirror serializableType, TypeMirror parcelableType) {\n if (!isDocEnable)\n return;\n try {\n RouteModel routeModel = new RouteModel();\n routeModel.setPath(route.path());\n routeModel.setType(typeDoc);\n routeModel.setPathClass(element.toString());\n if (!StringUtils.isEmpty(route.remark())) {\n routeModel.setRemark(route.remark());\n }\n if (route.tag() != 0) {\n routeModel.setTag(route.tag());\n }\n routeModel.setModuleName(moduleName);\n if (route.deprecated()) {\n routeModel.setDeprecated(true);\n }\n if (route.ignoreHelper()) {\n routeModel.setIgnoreHelper(true);\n }\n addParamCode(moduleName, logger, element, routeModel, types, serializableType, parcelableType);\n routeModelList.add(routeModel);\n } catch (Exception e) {\n logger.error(moduleName + \" Failed to add route [\" + element.toString() + \"] document, \" + e.getMessage());\n }\n }\n\n private static void addParamCode(String moduleName, Logger logger, Element element, RouteModel routeModel, Types types, TypeMirror serializableType, TypeMirror parcelableType) {\n List<ParamModel> tempParamModels = new ArrayList<>();\n for (Element field : element.getEnclosedElements()) {\n if (field.getKind().isField() && field.getAnnotation(Param.class) != null) {\n Param param = field.getAnnotation(Param.class);\n String paramName = field.getSimpleName().toString();\n TypeMirror typeMirror = field.asType();\n String typeStr = typeMirror.toString();\n\n ParamModel paramModel = new ParamModel();\n if (!StringUtils.isEmpty(param.remark())) {\n paramModel.setRemark(param.remark());\n }\n paramModel.setRequired(param.required());\n paramModel.setType(typeStr);\n\n switch (typeStr) {\n case BYTE_PACKAGE, BYTE_PRIMITIVE -> paramModel.setIntentType(\"withByte\");\n case SHORT_PACKAGE, SHORT_PRIMITIVE -> paramModel.setIntentType(\"withShort\");\n case INTEGER_PACKAGE, INTEGER_PRIMITIVE -> paramModel.setIntentType(\"withInt\");\n case LONG_PACKAGE, LONG_PRIMITIVE -> paramModel.setIntentType(\"withLong\");\n case FLOAT_PACKAGE, FLOAT_PRIMITIVE -> paramModel.setIntentType(\"withFloat\");\n case DOUBLE_PACKAGE, DOUBLE_PRIMITIVE -> paramModel.setIntentType(\"withDouble\");\n case BOOLEAN_PACKAGE, BOOLEAN_PRIMITIVE -> paramModel.setIntentType(\"withBoolean\");\n case CHAR_PACKAGE, CHAR_PRIMITIVE -> paramModel.setIntentType(\"withChar\");\n case STRING_PACKAGE -> paramModel.setIntentType(\"withString\");\n default -> {\n if (types.isSubtype(typeMirror, parcelableType)) {\n paramModel.setIntentType(\"withParcelable\");\n } else if (types.isSubtype(typeMirror, serializableType)) {\n paramModel.setIntentType(\"withSerializable\");\n } else {\n paramModel.setIntentType(\"withObject\");\n }\n }\n }\n\n if (StringUtils.isEmpty(param.name()) && !param.required()) {\n paramModel.setName(paramName);\n } else {\n if (!StringUtils.isEmpty(param.name())) {\n paramModel.setName(param.name());\n } else {\n paramModel.setName(paramName);\n }\n }\n tempParamModels.add(paramModel);\n }\n }\n\n // The parent class parameter is processed before the subclass parameter\n if (!tempParamModels.isEmpty()) {\n tempParamModels.addAll(routeModel.getParamsType());\n routeModel.setParamsType(tempParamModels);\n }\n\n // if has parent?\n TypeMirror parent = ((TypeElement) element).getSuperclass();\n if (parent instanceof DeclaredType) {\n Element parentElement = ((DeclaredType) parent).asElement();\n if (parentElement instanceof TypeElement && !((TypeElement) parentElement).getQualifiedName().toString().startsWith(\"android\")) {\n addParamCode(moduleName, logger, parentElement, routeModel, types, serializableType, parcelableType);\n }\n }\n }\n\n}" }, { "identifier": "RouteModel", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/doc/model/RouteModel.java", "snippet": "public class RouteModel {\n\n private String path;\n private String remark;\n private String moduleName;\n private String type;\n private String pathClass;\n private Integer tag;\n private Boolean deprecated;\n private Boolean ignoreHelper;\n private List<ParamModel> paramsType;\n\n public RouteModel() {\n }\n\n public RouteModel(String path, String type, String pathClass, Integer tag, List<ParamModel> paramsType, String remark, String moduleName, Boolean deprecated, Boolean ignoreHelper) {\n this.path = path;\n this.type = type;\n this.pathClass = pathClass;\n this.tag = tag;\n this.moduleName = moduleName;\n this.deprecated = deprecated;\n this.ignoreHelper = ignoreHelper;\n if (!StringUtils.isEmpty(remark)) {\n this.remark = remark;\n }\n }\n\n public String getPath() {\n return path;\n }\n\n public void setPath(String path) {\n this.path = path;\n }\n\n public String getRemark() {\n return remark;\n }\n\n public void setRemark(String remark) {\n this.remark = remark;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getPathClass() {\n return pathClass;\n }\n\n public void setPathClass(String pathClass) {\n this.pathClass = pathClass;\n }\n\n public Integer getTag() {\n return tag;\n }\n\n public void setTag(Integer tag) {\n this.tag = tag;\n }\n\n public List<ParamModel> getParamsType() {\n if (paramsType == null) {\n paramsType = new ArrayList<>();\n }\n return paramsType;\n }\n\n public void setParamsType(List<ParamModel> paramsType) {\n this.paramsType = paramsType;\n }\n\n public String getModuleName() {\n return moduleName;\n }\n\n public void setModuleName(String moduleName) {\n this.moduleName = moduleName;\n }\n\n public Boolean getDeprecated() {\n return deprecated;\n }\n\n public void setDeprecated(Boolean deprecated) {\n this.deprecated = deprecated;\n }\n\n public Boolean getIgnoreHelper() {\n return ignoreHelper;\n }\n\n public void setIgnoreHelper(Boolean ignoreHelper) {\n this.ignoreHelper = ignoreHelper;\n }\n}" } ]
import static com.wyjson.router.compiler.utils.Constants.ACTIVITY; import static com.wyjson.router.compiler.utils.Constants.BOOLEAN_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.BOOLEAN_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.BYTE_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.BYTE_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.CHAR_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.CHAR_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.DOUBLE_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.DOUBLE_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.FLOAT_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.FLOAT_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.FRAGMENT; import static com.wyjson.router.compiler.utils.Constants.GOROUTER; import static com.wyjson.router.compiler.utils.Constants.INTEGER_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.INTEGER_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.I_ROUTE_MODULE; import static com.wyjson.router.compiler.utils.Constants.I_ROUTE_MODULE_GROUP; import static com.wyjson.router.compiler.utils.Constants.I_ROUTE_MODULE_GROUP_METHOD_NAME_LOAD; import static com.wyjson.router.compiler.utils.Constants.LONG_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.LONG_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_LOAD; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_LOAD_ROUTE_FOR_x_GROUP; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_LOAD_ROUTE_GROUP; import static com.wyjson.router.compiler.utils.Constants.PARAM_NAME_ROUTE_GROUPS; import static com.wyjson.router.compiler.utils.Constants.PARCELABLE_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.PREFIX_OF_LOGGER; import static com.wyjson.router.compiler.utils.Constants.ROUTE_CENTER; import static com.wyjson.router.compiler.utils.Constants.ROUTE_CENTER_METHOD_NAME_GET_ROUTE_GROUPS; import static com.wyjson.router.compiler.utils.Constants.ROUTE_MODULE; import static com.wyjson.router.compiler.utils.Constants.ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX; import static com.wyjson.router.compiler.utils.Constants.SERIALIZABLE_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.SHORT_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.SHORT_PRIMITIVE; import static com.wyjson.router.compiler.utils.Constants.STRING_PACKAGE; import static com.wyjson.router.compiler.utils.Constants.WARNING_TIPS; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeSpec; import com.wyjson.router.annotation.Interceptor; import com.wyjson.router.annotation.Param; import com.wyjson.router.annotation.Route; import com.wyjson.router.annotation.Service; import com.wyjson.router.compiler.doc.DocumentUtils; import com.wyjson.router.compiler.doc.model.RouteModel; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror;
4,764
package com.wyjson.router.compiler.processor; @AutoService(Processor.class) public class GenerateRouteModuleProcessor extends BaseProcessor { TypeElement mGoRouter; TypeElement mIRouteModule; TypeElement mRouteCenter; TypeElement mIRouteModuleGroup; TypeMirror serializableType; TypeMirror parcelableType; TypeMirror activityType; TypeMirror fragmentType; private final Map<String, Set<Element>> routeGroupMap = new HashMap<>(); @Override public Set<String> getSupportedAnnotationTypes() { Set<String> set = new LinkedHashSet<>(); set.add(Service.class.getCanonicalName()); set.add(Interceptor.class.getCanonicalName()); set.add(Route.class.getCanonicalName()); return set; } @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); logger.info(moduleName + " >>> GenerateRouteModuleProcessor init. <<<"); mGoRouter = elementUtils.getTypeElement(GOROUTER); mIRouteModule = elementUtils.getTypeElement(I_ROUTE_MODULE); } @Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { if (CollectionUtils.isEmpty(set)) return false; DocumentUtils.createDoc(mFiler, moduleName, logger, isGenerateDoc); String className = generateClassName + ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX; MethodSpec.Builder loadIntoMethod = MethodSpec.methodBuilder(METHOD_NAME_LOAD) .addModifiers(PUBLIC) .addAnnotation(Override.class); loadIntoMethod.addJavadoc("load the $S route", moduleName); addService(roundEnvironment, loadIntoMethod); addInterceptor(roundEnvironment, loadIntoMethod); LinkedHashSet<MethodSpec> routeGroupMethods = addRouteGroup(roundEnvironment, loadIntoMethod); try { JavaFile.builder(ROUTE_MODULE, TypeSpec.classBuilder(className) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(mIRouteModule))
package com.wyjson.router.compiler.processor; @AutoService(Processor.class) public class GenerateRouteModuleProcessor extends BaseProcessor { TypeElement mGoRouter; TypeElement mIRouteModule; TypeElement mRouteCenter; TypeElement mIRouteModuleGroup; TypeMirror serializableType; TypeMirror parcelableType; TypeMirror activityType; TypeMirror fragmentType; private final Map<String, Set<Element>> routeGroupMap = new HashMap<>(); @Override public Set<String> getSupportedAnnotationTypes() { Set<String> set = new LinkedHashSet<>(); set.add(Service.class.getCanonicalName()); set.add(Interceptor.class.getCanonicalName()); set.add(Route.class.getCanonicalName()); return set; } @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); logger.info(moduleName + " >>> GenerateRouteModuleProcessor init. <<<"); mGoRouter = elementUtils.getTypeElement(GOROUTER); mIRouteModule = elementUtils.getTypeElement(I_ROUTE_MODULE); } @Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { if (CollectionUtils.isEmpty(set)) return false; DocumentUtils.createDoc(mFiler, moduleName, logger, isGenerateDoc); String className = generateClassName + ROUTE_MODULE_GENERATE_CLASS_NAME_SUFFIX; MethodSpec.Builder loadIntoMethod = MethodSpec.methodBuilder(METHOD_NAME_LOAD) .addModifiers(PUBLIC) .addAnnotation(Override.class); loadIntoMethod.addJavadoc("load the $S route", moduleName); addService(roundEnvironment, loadIntoMethod); addInterceptor(roundEnvironment, loadIntoMethod); LinkedHashSet<MethodSpec> routeGroupMethods = addRouteGroup(roundEnvironment, loadIntoMethod); try { JavaFile.builder(ROUTE_MODULE, TypeSpec.classBuilder(className) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(mIRouteModule))
.addJavadoc(WARNING_TIPS)
34
2023-10-18 13:52:07+00:00
8k
trpc-group/trpc-java
trpc-core/src/main/java/com/tencent/trpc/core/serialization/support/JSONSerialization.java
[ { "identifier": "SerializationType", "path": "trpc-core/src/main/java/com/tencent/trpc/core/serialization/SerializationType.java", "snippet": "public interface SerializationType {\n\n /**\n * Protocol Buffers format.\n */\n int PB = 0;\n /**\n * JCE format.\n */\n int JCE = 1;\n /**\n * JSON format.\n */\n int JSON = 2;\n\n}" }, { "identifier": "Serialization", "path": "trpc-core/src/main/java/com/tencent/trpc/core/serialization/spi/Serialization.java", "snippet": "@Extensible(\"pb\")\npublic interface Serialization {\n\n /**\n * Serialization interface.\n *\n * @param obj the object to be serialized\n * @return the serialized byte array\n * @throws IOException IO exception\n */\n byte[] serialize(Object obj) throws IOException;\n\n /**\n * Deserialize byte array into an object, does not support generics.\n *\n * @param bytes the byte array to be deserialized\n * @param clz the object type after deserialization\n * @param <T> the instance type after deserialization\n * @return the instance after deserialization\n * @throws IOException IO exception\n */\n <T> T deserialize(byte[] bytes, Class<T> clz) throws IOException;\n\n /**\n * Deserialize byte array into an object, supports JSON deserialization generics.\n *\n * <p>The default implementation does not support generics, only the Json serialization implementation needs to\n * override this method.</p>\n *\n * @param bytes the byte array to be deserialized\n * @param type the original object type\n * @param <T> the generic type\n * @return the object after deserialization\n * @throws IOException io exception\n */\n default <T> T deserialize(byte[] bytes, Type type) throws IOException {\n return deserialize(bytes, (Class<T>) type);\n }\n\n /**\n * Framework usage: 0-127.\n */\n int type();\n\n String name();\n\n}" }, { "identifier": "ClassUtils", "path": "trpc-core/src/main/java/com/tencent/trpc/core/utils/ClassUtils.java", "snippet": "public class ClassUtils {\n\n private static final Logger logger = LoggerFactory.getLogger(ClassUtils.class);\n\n public static boolean isByteArray(Object obj) {\n return ((obj instanceof byte[]) || (obj instanceof Byte[]));\n }\n\n public static boolean isByteArray(Class<?> type) {\n return type == byte[].class || type == Byte[].class;\n }\n\n public static byte[] cast2ByteArray(Object obj) {\n PreconditionUtils.checkArgument(isByteArray(obj), \"%s is not instanceof byte array\", obj);\n if ((obj instanceof byte[])) {\n return (byte[]) obj;\n } else {\n return ArrayUtils.toPrimitive((Byte[]) obj);\n }\n }\n\n public static <T> T newInstance(Class<?> clazz) {\n try {\n return (T) clazz.newInstance();\n } catch (Exception e) {\n throw new RuntimeException(\n \"instance Class: \" + clazz.getName() + \" with ex: \" + e.getMessage(), e);\n }\n }\n\n public static List<Class> getAllInterfaces(final Class cls) {\n if (cls == null) {\n return Collections.emptyList();\n }\n final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>();\n getAllInterfaces(cls, interfacesFound);\n return new ArrayList<>(interfacesFound);\n }\n\n /**\n * Get the interfaces for the specified class.\n */\n private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {\n while (cls != null) {\n final Class<?>[] interfaces = cls.getInterfaces();\n for (final Class<?> i : interfaces) {\n if (interfacesFound.add(i)) {\n getAllInterfaces(i, interfacesFound);\n }\n }\n cls = cls.getSuperclass();\n }\n }\n\n /**\n * Get the specified method of the specified class, returns null when the method does not exist.\n *\n * @param clazz the class to get the method from\n * @param name method name\n * @param parameterTypes parameter types\n * @return the corresponding method if it exists, otherwise returns null\n */\n public static Method getDeclaredMethod(Class<?> clazz, String name,\n Class<?>... parameterTypes) {\n if (clazz == null) {\n return null;\n }\n\n try {\n return clazz.getDeclaredMethod(name, parameterTypes);\n } catch (NoSuchMethodException e) {\n logger.error(\"the class:{} no such method:{}, parameterTypes:{}\", clazz, name,\n parameterTypes);\n }\n return null;\n }\n\n /**\n * Get the value of a field.\n *\n * @param target target object instance\n * @param field field of the object's class\n * @return value of target object instance\n */\n public static Optional<Object> getValue(Object target, Field field) {\n boolean accessible = field.isAccessible();\n Object result = null;\n try {\n if (!accessible) {\n field.setAccessible(true);\n }\n result = field.get(target);\n } catch (IllegalAccessException e) {\n logger.error(\"get value from obj: {}, field: {} error: \", target, field.getName(), e);\n } finally {\n field.setAccessible(accessible);\n }\n return Optional.ofNullable(result);\n }\n\n /**\n * Get the static value of a field.\n *\n * @param field field of the class\n * @return static value\n */\n public static Optional<Object> getStaticValue(Field field) {\n return getValue(null, field);\n }\n\n /**\n * Get constant values of target clazz. Field must be public static final.\n *\n * @param clazz target clazz\n * @return constant values\n */\n public static List<Object> getConstantValues(Class<?> clazz) {\n return Stream.of(clazz.getFields())\n // getFields must return public, skip filter Modifier.isPublic\n .filter(f -> Modifier.isStatic(f.getModifiers()))\n .filter(f -> Modifier.isFinal(f.getModifiers()))\n .map(ClassUtils::getStaticValue)\n .filter(Optional::isPresent)\n .map(Optional::get)\n .collect(Collectors.toList());\n }\n\n}" }, { "identifier": "JsonUtils", "path": "trpc-core/src/main/java/com/tencent/trpc/core/utils/JsonUtils.java", "snippet": "public class JsonUtils {\n\n /**\n * Default global serialization object.\n */\n private static final ObjectMapper objectMapper = new ObjectMapper();\n private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);\n\n static {\n // Serialization does not include null properties\n objectMapper.setSerializationInclusion(Include.NON_NULL);\n // Do not throw an error when deserializing if there are no corresponding properties\n objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);\n }\n\n /**\n * ObjectMapper copy method, used for different serialization configurations.\n *\n * @return ObjectMapper object\n */\n public static ObjectMapper copy() {\n return objectMapper.copy();\n }\n\n /**\n * JSON to Object.\n *\n * @param is JSON input stream\n * @param clz the class of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromInputStream(InputStream is, Class<T> clz) {\n try {\n return objectMapper.readValue(is, clz);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, jsonStream:%s, clz:%s\", is, clz);\n }\n }\n\n /**\n * JSON to Object.\n *\n * @param json JSON string\n * @param clz the class of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromJson(String json, Class<T> clz) {\n try {\n return objectMapper.readValue(json, clz);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, json:%s, clz:%s\", json, clz);\n }\n }\n\n /**\n * JSON to Object.\n *\n * @param json JSON string\n * @param javaType the Java type of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromJson(String json, JavaType javaType) {\n try {\n return objectMapper.readValue(json, javaType);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, json:%s, javaType:%s\", json, javaType);\n }\n }\n\n /**\n * JSON to Object.\n *\n * @param json JSON string\n * @param typeReference the type reference of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromJson(String json, TypeReference<T> typeReference) {\n try {\n return objectMapper.readValue(json, typeReference);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, json:%s, typeReference:%s\", json,\n typeReference);\n }\n }\n\n /**\n * Byte arrays to Object.\n *\n * @param bytes byte array\n * @param clz the class of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromBytes(byte[] bytes, Class<T> clz) {\n try {\n return objectMapper.readValue(bytes, clz);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, clz:%s\", clz);\n }\n }\n\n /**\n * Byte arrays to Object\n *\n * @param bytes byte array\n * @param typeReference the type reference of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromBytes(byte[] bytes, TypeReference<T> typeReference) {\n try {\n return objectMapper.readValue(bytes, typeReference);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, typeReference:%s\", typeReference);\n }\n }\n\n /**\n * JSON string to Object.\n *\n * @param jsonStr JSON string\n * @param typeReference the type reference of the object to deserialize\n * @param <T> the type of the deserialized object\n * @return the deserialized object\n */\n public static <T> T fromBytes(String jsonStr, TypeReference<T> typeReference) {\n try {\n return objectMapper.readValue(jsonStr, typeReference);\n } catch (IOException e) {\n logger.error(\"object mapper readValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper readValue error, typeReference:%s\", typeReference);\n }\n }\n\n /**\n * Object to JSON.\n *\n * @param obj the object to serialize\n * @return the serialized string\n */\n public static String toJson(Object obj) {\n try {\n return objectMapper.writeValueAsString(obj);\n } catch (IOException e) {\n logger.error(\"object mapper writeValueAsString error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper writeValueAsString error, obj:%s\", obj);\n }\n }\n\n /**\n * Object to JSON.\n *\n * @param obj the object to serialize\n * @return the serialized string\n */\n public static String toJson(Object obj, String defaultValue) {\n try {\n return objectMapper.writeValueAsString(obj);\n } catch (IOException e) {\n logger.error(\"object mapper writeValueAsString error:\", e);\n return defaultValue;\n }\n }\n\n /**\n * Object to bytes.\n *\n * @param obj the object to serialize\n * @return the serialized bytes\n */\n public static byte[] toBytes(Object obj) {\n try {\n return objectMapper.writeValueAsBytes(obj);\n } catch (IOException e) {\n logger.error(\"object mapper writeValueAsBytes error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_DESERIALIZATION_ERR, 0,\n \"object mapper writeValueAsBytes error, obj:%s\", obj);\n }\n }\n\n /**\n * Object conversion.\n *\n * @param object the original data\n * @param tClass the class of the target object\n * @param <T> the type of the deserialized object\n * @return the target object\n */\n public static <T> T convertValue(Object object, Class<T> tClass) {\n try {\n return objectMapper.convertValue(object, tClass);\n } catch (Exception e) {\n logger.error(\"object mapper convertValue error:\", e);\n throw TRpcException.newException(ErrorCode.JSON_SERIALIZATION_ERR, 0,\n \"object mapper convertValue error, obj:%s, target class:%s\", object, tClass);\n }\n }\n\n}" }, { "identifier": "ProtoJsonConverter", "path": "trpc-core/src/main/java/com/tencent/trpc/core/utils/ProtoJsonConverter.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class ProtoJsonConverter {\n\n private static final Logger LOG = LoggerFactory.getLogger(ProtoJsonConverter.class);\n\n private static final Map<Class<? extends Message>, Builder> BUILDER_CACHE = new ConcurrentHashMap<>(64);\n\n private static <R extends Builder, T extends Message> R newBuilder(Class<T> clazz) {\n Objects.requireNonNull(clazz, \"protobuf message class must not be null\");\n return (R) BUILDER_CACHE.computeIfAbsent(clazz, c -> {\n try {\n return (Builder) c.getMethod(\"newBuilder\").invoke(null);\n } catch (Exception e) {\n throw new IllegalStateException(\"newBuilder for class '\" + clazz + \"' error\", e);\n }\n }).getDefaultInstanceForType().newBuilderForType();\n }\n\n /**\n * Used only for human-readable logging, not for logical processing.\n *\n * @param value the object to be printed\n * @return the resulting string\n */\n public static String toString(Object value) {\n return toString(value, false);\n }\n\n /**\n * toString method, used only for human-readable logging.\n *\n * @param value the object to be printed\n * @param throwException whether to throw an exception\n * @return the resulting string\n */\n public static String toString(Object value, boolean throwException) {\n try {\n if (value == null) {\n return null;\n }\n if (value instanceof Message) {\n return ProtoJsonConverter.messageToJson((Message) value);\n }\n return value.toString();\n } catch (Exception ex) {\n if (throwException) {\n throw new RuntimeException(ex);\n } else {\n LOG.error(\"toString exception\", ex);\n return ex.toString();\n }\n }\n }\n\n /**\n * Convert Protocol Buffers message to a map.\n *\n * @param message the source Protocol Buffers message\n * @return the resulting map\n */\n public static Map<String, Object> messageToMap(Message message) {\n try {\n Objects.requireNonNull(message, \"message\");\n return JsonUtils.fromJson(\n JsonFormat.printer().printingEnumsAsInts().includingDefaultValueFields()\n .print(message),\n Map.class);\n } catch (Exception ex) {\n throw new RuntimeException(\"pb message to map exception:\", ex);\n }\n }\n\n /**\n * Convert a map to a Protocol Buffers message.\n *\n * @param map the source map\n * @param message the Protocol Buffers message object instance\n * @return the resulting Protocol Buffers message\n */\n public static Message mapToMessage(Map<String, Object> map, Message message) {\n try {\n Objects.requireNonNull(map, \"map\");\n Objects.requireNonNull(message, \"message\");\n return jsonToMessage(JsonUtils.toJson(map), message);\n } catch (Exception ex) {\n throw new RuntimeException(\"map to pb message exception:\", ex);\n }\n }\n\n /**\n * Convert a map to a Protocol Buffers builder.\n *\n * @param map the source map\n * @param builder the target Protocol Buffers builder object instance\n */\n public static void mapToBuilder(Map<String, Object> map, Builder builder) {\n try {\n Objects.requireNonNull(map, \"map\");\n Objects.requireNonNull(builder, \"builder\");\n JsonFormat.parser().ignoringUnknownFields()\n .merge(JsonUtils.toJson(map), builder);\n } catch (Exception ex) {\n throw new RuntimeException(\"map to pb builder exception:\", ex);\n }\n }\n\n /**\n * Convert a Protocol Buffers message to JSON.\n *\n * @param message the source Protocol Buffers message\n * @return the resulting JSON string\n */\n public static String messageToJson(Message message) {\n return messageToJson(message, true, true);\n }\n\n /**\n * Convert a Protocol Buffers message to JSON.\n *\n * @param message the source of pb message\n * @param pretty whether to output json that fits in a page for pretty printing\n * @param includingDefaultValueFields whether to print fields set to their defaults\n * @return the result of json string\n */\n public static String messageToJson(Message message, boolean pretty, boolean includingDefaultValueFields) {\n try {\n Objects.requireNonNull(message, \"message\");\n return newJsonFormatPrinter(pretty, includingDefaultValueFields).print(message);\n } catch (Exception ex) {\n throw new RuntimeException(\"pb message to json exception:\", ex);\n }\n }\n\n /**\n * Convert a JSON string to a Protocol Buffers message.\n *\n * @param json the source JSON string\n * @param message the Protocol Buffers message object instance\n * @return the resulting Protocol Buffers message\n */\n public static Message jsonToMessage(String json, Message message) {\n try {\n Objects.requireNonNull(json, \"json\");\n Objects.requireNonNull(message, \"message\");\n Builder builder = message.toBuilder();\n JsonFormat.parser().ignoringUnknownFields().merge(json, builder);\n return builder.build();\n } catch (Exception ex) {\n throw new RuntimeException(\"json to pb message exception:\", ex);\n }\n }\n\n /**\n * The json string to pb.\n *\n * @param json the source of json string\n * @param clazz the pb message type\n * @return the result of pb message\n */\n public static <T extends Message> T jsonToMessage(String json, Class<T> clazz) {\n Message message = newBuilder((Class<Message>) clazz).build();\n return (T) jsonToMessage(json, message);\n }\n\n /**\n * New JsonFormat Printer.\n *\n * @param pretty whether to output json that fits in a page for pretty printing\n * @param includingDefaultValueFields whether to print fields set to their defaults\n * @return the printer converts the protobuf message to json\n */\n private static Printer newJsonFormatPrinter(boolean pretty, boolean includingDefaultValueFields) {\n Printer printer = JsonFormat.printer().printingEnumsAsInts();\n if (!pretty) {\n printer = printer.omittingInsignificantWhitespace();\n }\n if (includingDefaultValueFields) {\n printer = printer.includingDefaultValueFields();\n }\n return printer;\n }\n\n}" } ]
import com.fasterxml.jackson.core.type.TypeReference; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.google.protobuf.Message; import com.tencent.trpc.core.extension.Extension; import com.tencent.trpc.core.serialization.SerializationType; import com.tencent.trpc.core.serialization.spi.Serialization; import com.tencent.trpc.core.utils.ClassUtils; import com.tencent.trpc.core.utils.JsonUtils; import com.tencent.trpc.core.utils.ProtoJsonConverter; import java.io.IOException; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Objects;
5,405
/* * 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.serialization.support; @Extension(JSONSerialization.NAME) @SuppressWarnings("unchecked") public class JSONSerialization implements Serialization { public static final String NAME = "json"; /** * PB class method information cache. One class per method, initial cache size 20, maximum 500. */ private static final Cache<Class, Method> CLASS_METHOD_CACHE = Caffeine.newBuilder() .initialCapacity(20) .maximumSize(500) .build(); /** * Default UTF-8 serialize. * * @param obj the object to be serialized * @return the serialized byte array * @throws IOException IO exception */ @Override public byte[] serialize(Object obj) throws IOException { try { // pb to bytes if (obj instanceof Message) {
/* * 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.serialization.support; @Extension(JSONSerialization.NAME) @SuppressWarnings("unchecked") public class JSONSerialization implements Serialization { public static final String NAME = "json"; /** * PB class method information cache. One class per method, initial cache size 20, maximum 500. */ private static final Cache<Class, Method> CLASS_METHOD_CACHE = Caffeine.newBuilder() .initialCapacity(20) .maximumSize(500) .build(); /** * Default UTF-8 serialize. * * @param obj the object to be serialized * @return the serialized byte array * @throws IOException IO exception */ @Override public byte[] serialize(Object obj) throws IOException { try { // pb to bytes if (obj instanceof Message) {
return JsonUtils.toBytes(ProtoJsonConverter.messageToMap((Message) obj));
3
2023-10-19 10:54:11+00:00
8k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/XposedInit.java
[ { "identifier": "CopyUrlHook", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/hooks/CopyUrlHook.java", "snippet": "public class CopyUrlHook extends BaseHook {\r\n @Override\r\n public void startHook(int appVersionCode, ClassLoader classLoader) throws ClassNotFoundException {\r\n XposedHelpers.findAndHookMethod(ClipboardManager.class, \"setPrimaryClip\", ClipData.class, new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n Context context = (Context) XposedHelpers.getObjectField(param.thisObject,\"mContext\");\r\n ClipData clipData = (ClipData) param.args[0];\r\n ClipData.Item item = clipData.getItemAt(0);\r\n if (item == null) {\r\n return;\r\n }\r\n if (item.getText() == null){\r\n return;\r\n }\r\n String text = item.getText().toString();\r\n XposedBridge.log(\"YouTube要复制的文本:\"+text);\r\n int questionMarkIndex = text.indexOf(\"?si=\");\r\n String newText = questionMarkIndex != -1 ? text.substring(0, questionMarkIndex) : text;\r\n //Hook 环境不可以将字符串写在strings.xml\r\n if (questionMarkIndex != -1){\r\n String toast = \"The tracking parameter \\\"?si=xxx\\\" of the YT shared link has been removed, and the purified link is:\";\r\n if (Locale.getDefault().getLanguage().equals(\"zh\")){\r\n toast = \"已将YT分享链接的追踪参数\\\"?si=xxx\\\"去除,净化后的链接:\";\r\n }\r\n String log = \"The tracking parameter \\\"?si=xxx\\\" of YT sharing link has been removed:[%s ==> %s]\";\r\n if (Locale.getDefault().getLanguage().equals(\"zh\")){\r\n log = \"已将YT分享链接的追踪参数\\\"?si=xxx\\\"去除:[%s ==> %s]\";\r\n }\r\n XposedBridge.log(String.format(log,text,newText));\r\n Toast.makeText(context, toast+newText, Toast.LENGTH_LONG).show();\r\n }\r\n param.args[0] = ClipData.newPlainText(null,newText);\r\n }\r\n });\r\n }\r\n\r\n}\r" }, { "identifier": "OpenLinkHook", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/hooks/OpenLinkHook.java", "snippet": "public class OpenLinkHook extends BaseHook {\r\n\r\n @Override\r\n public void startHook(int appVersionCode, ClassLoader classLoader) throws ClassNotFoundException {\r\n XposedHelpers.findAndHookMethod(Activity.class, \"startActivity\", Intent.class, new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n Intent intent = (Intent) param.args[0];\r\n String action = intent.getAction();\r\n if (action != null && action.equals(Intent.ACTION_VIEW)) {\r\n Uri data = intent.getData();\r\n if (data != null && data.getPath() != null && data.getPath().equals(\"/redirect\")) {\r\n String url = data.getQueryParameter(\"q\");\r\n if (url != null) {\r\n intent.setData(Uri.parse(url));\r\n String msg = \"Tracked redirect links have been converted into normal links:\";\r\n if (Locale.getDefault().getLanguage().equals(\"zh\")){\r\n msg = \"已将追踪式重定向链接转为正常链接:\";\r\n }\r\n Toast.makeText((Context) param.thisObject, msg + url, Toast.LENGTH_SHORT).show();\r\n XposedBridge.log(String.format(msg+\"[%s ==> %s]\", data.toString(), url));\r\n }\r\n }\r\n }\r\n }\r\n });\r\n\r\n /* XposedHelpers.findAndHookMethod(\"hfq\", classLoader, \"c\", android.content.res.Configuration.class, new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n XposedBridge.log(\"Configuration:\"+param.args[0]);\r\n }\r\n @Override\r\n protected void afterHookedMethod(MethodHookParam param) throws Throwable {\r\n super.afterHookedMethod(param);\r\n }\r\n });*/\r\n }\r\n}\r" }, { "identifier": "PostCommentHook", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/hooks/PostCommentHook.java", "snippet": "public class PostCommentHook extends BaseHook {\r\n Map<Object, ByteArrayOutputStream> callbackMap = new HashMap<>();\r\n AtomicReference<Context> currentContext = new AtomicReference<>();\r\n private final InHookXConfig config = InHookXConfig.getInstance();\r\n Class<?> urlRequest$CallbackImplClass = null;\r\n String simpleImmutableEntryFieldName = null;\r\n String cronetUploadDataStreamFieldName = null;\r\n\r\n /*\r\n 适配版本:\r\n 18.32.36(1539433920)\r\n 18.40.33(1540476352)\r\n 请勿更新到不适配的版本,随时失效!\r\n */\r\n @Override\r\n public void startHook(int appVersionCode, ClassLoader classLoader) throws ClassNotFoundException {\r\n\r\n Class<?> cronetUrlRequestClass = XposedHelpers.findClass(\"org.chromium.net.impl.CronetUrlRequest\", classLoader);\r\n for (Field field : cronetUrlRequestClass.getDeclaredFields()) {\r\n //XposedBridge.log(\"fieldType:\"+field.getType()+\" fieldName:\"+field.getName());\r\n if (field.getType().getCanonicalName().equals(\"org.chromium.net.impl.CronetUploadDataStream\")){\r\n cronetUploadDataStreamFieldName = field.getName();\r\n }\r\n Class<?> superclass = field.getType().getSuperclass();\r\n if (superclass != null){\r\n if (superclass.getCanonicalName() == null) return;\r\n //XposedBridge.log(\"super:\"+superclass);\r\n if (superclass.getCanonicalName().equals(\"org.chromium.net.UrlRequest$Callback\")){\r\n urlRequest$CallbackImplClass = field.getType();\r\n } else if (superclass.getCanonicalName().equals(\"java.util.ArrayList\")){\r\n simpleImmutableEntryFieldName = field.getName();\r\n }\r\n }\r\n }\r\n\r\n if (urlRequest$CallbackImplClass == null){\r\n XposedBridge.log(\"未找到org.chromium.net.UrlRequest$Callback的实现类,请降级版本到所支持的YouTube版本!\");\r\n XposedBridge.log(\"The implementation class of org.chromium.net.UrlRequest$Callback was not found. Please downgrade the version to a supported version!\");\r\n return;\r\n }\r\n XposedBridge.log(\"Find UrlRequest$CallbackImplClass:\"+urlRequest$CallbackImplClass.getCanonicalName());\r\n\r\n XposedHelpers.findAndHookMethod(Activity.class, \"onCreate\", Bundle.class, new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n }\r\n\r\n @Override\r\n protected void afterHookedMethod(MethodHookParam param) throws Throwable {\r\n super.afterHookedMethod(param);\r\n Context context = (Context) param.thisObject;\r\n currentContext.set(context);\r\n XposedBridge.log(\"context:\" + context);\r\n }\r\n });\r\n hookUrlRequestCallbackImpl(classLoader,urlRequest$CallbackImplClass);\r\n /*if (appVersionCode < 1540476352) {\r\n hookUrlRequestCallbackImpl(classLoader, \"ayng\");\r\n } else if (appVersionCode <= 1540476352) {\r\n hookUrlRequestCallbackImpl(classLoader, \"azyn\");\r\n } else {\r\n hookUrlRequestCallbackImpl(classLoader, \"bapr\");\r\n }*/\r\n }\r\n\r\n\r\n private void hookUrlRequestCallbackImpl(ClassLoader classLoader, Class<?> implName) throws ClassNotFoundException {\r\n XposedHelpers.findAndHookMethod(implName, \"onReadCompleted\", classLoader.loadClass(\"org.chromium.net.UrlRequest\"), classLoader.loadClass(\"org.chromium.net.UrlResponseInfo\"), java.nio.ByteBuffer.class, new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n\r\n Object urlRequest_Callback_sub_ayng = param.thisObject;\r\n Object urlResponseInfo = param.args[1];\r\n ByteBuffer byteBuffer = (ByteBuffer) param.args[2];\r\n String url = (String) XposedHelpers.callMethod(urlResponseInfo, \"getUrl\");\r\n //XposedBridge.log(\"url:\" + url);\r\n if (url.contains(\"create_comment\")) {\r\n if (!callbackMap.containsKey(urlRequest_Callback_sub_ayng)) {\r\n callbackMap.put(urlRequest_Callback_sub_ayng, new ByteArrayOutputStream());\r\n }\r\n ByteArrayOutputStream byteArrayOutputStream = callbackMap.get(urlRequest_Callback_sub_ayng);\r\n //XposedBridge.log(\"onReadCompleted UrlResponseInfo:\"+urlResponseInfo);\r\n //XposedBridge.log(byteBuffer.toString());\r\n byteArrayOutputStream.write(bytebuffer2ByteArray(byteBuffer));\r\n //XposedBridge.log(\"onReadCompleted buffer:\" + Base64.encodeToString(byteBuffer.array(), Base64.DEFAULT));\r\n }\r\n }\r\n\r\n @Override\r\n protected void afterHookedMethod(MethodHookParam param) throws Throwable {\r\n super.afterHookedMethod(param);\r\n }\r\n });\r\n\r\n XposedHelpers.findAndHookMethod(implName, \"onSucceeded\", classLoader.loadClass(\"org.chromium.net.UrlRequest\"), classLoader.loadClass(\"org.chromium.net.UrlResponseInfo\"), new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n Object urlRequest = param.args[0];\r\n Object urlResponseInfo = param.args[1];\r\n String url = (String) XposedHelpers.callMethod(urlResponseInfo, \"getUrl\");\r\n ArrayList<AbstractMap.SimpleImmutableEntry<String, String>> headers = (ArrayList<AbstractMap.SimpleImmutableEntry<String, String>>) XposedHelpers.getObjectField(urlRequest, simpleImmutableEntryFieldName);\r\n if (url.startsWith(\"https://youtubei.googleapis.com/youtubei/\")) {\r\n outHeadersToFile(headers);\r\n }\r\n if (url.contains(\"create_comment\")) {\r\n //XposedBridge.log(\"onSucceeded callback:\"+XposedHelpers.getObjectField(param.thisObject,\"a\"));\r\n ByteArrayOutputStream byteArrayOutputStream = callbackMap.get(param.thisObject);\r\n //XposedBridge.log(\"list element type:\"+headers.get(0).getClass().getCanonicalName());\r\n /*FileOutputStream fileOutputStream = new FileOutputStream(\"/data/data/com.google.android.youtube/files/resp.pb\");\r\n fileOutputStream.write(byteArrayOutputStream.toByteArray());\r\n fileOutputStream.close();*/\r\n //XposedBridge.log(\"urlRequest:\"+urlRequest);\r\n Object cronetUploadDataStream = XposedHelpers.getObjectField(urlRequest, cronetUploadDataStreamFieldName);\r\n if (cronetUploadDataStream != null) {\r\n Object uploadDataProvider_aynf = XposedHelpers.getObjectField(cronetUploadDataStream, \"b\");\r\n Object uploadDataProvider_sub_aylc = XposedHelpers.getObjectField(uploadDataProvider_aynf, \"a\");\r\n ByteBuffer byteBuffer = (ByteBuffer) XposedHelpers.getObjectField(uploadDataProvider_sub_aylc, \"a\");\r\n /*FileOutputStream fileOutputStream1 = new FileOutputStream(\"/data/data/com.google.android.youtube/files/req.pb\");\r\n fileOutputStream1.write(byteBuffer.array());\r\n fileOutputStream1.close();*/\r\n if (config.getAntiFraudEnabled()) {\r\n startCheck(byteBuffer.array(), byteArrayOutputStream.toByteArray(), headers);\r\n }\r\n\r\n }\r\n callbackMap.remove(param.thisObject);\r\n }\r\n\r\n }\r\n\r\n @Override\r\n protected void afterHookedMethod(MethodHookParam param) throws Throwable {\r\n super.afterHookedMethod(param);\r\n }\r\n });\r\n }\r\n\r\n private synchronized void outHeadersToFile(ArrayList<AbstractMap.SimpleImmutableEntry<String, String>> headers) {\r\n File mediaDir = new File(\"/storage/emulated/0/Android/media/com.google.android.youtube/\");\r\n if (!mediaDir.exists()) {\r\n mediaDir.mkdirs();\r\n }\r\n //XposedBridge.log(headers.toString());\r\n File headersFile = new File(mediaDir, \"headers.txt\");\r\n StringBuilder sb = new StringBuilder();\r\n boolean hasAuthorization = false;\r\n for (int i = 0; i < headers.size(); i++) {\r\n String key = headers.get(i).getKey();\r\n if (key.equals(\"Authorization\")) {\r\n hasAuthorization = true;\r\n }\r\n sb.append(key).append(\"=\").append(headers.get(i).getValue());\r\n if (i != headers.size() - 1) {\r\n sb.append(\"\\n\");\r\n }\r\n }\r\n if (hasAuthorization) {\r\n try {\r\n FileOutputStream fileOutputStream = new FileOutputStream(headersFile);\r\n fileOutputStream.write(sb.toString().getBytes(StandardCharsets.UTF_8));\r\n fileOutputStream.close();\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n }\r\n\r\n private void startCheck(byte[] requestBody, byte[] responseBody, ArrayList<AbstractMap.SimpleImmutableEntry<String, String>> headers) throws InvalidProtocolBufferException {\r\n CreatCommentRequest creatCommentRequest = CreatCommentRequest.parseFrom(requestBody);\r\n CreatCommentResponse creatCommentResponse = CreatCommentResponse.parseFrom(responseBody);\r\n Intent intent = new Intent();\r\n intent.setComponent(new ComponentName(\"icu.freedomintrovert.YTSendCommAntiFraud\", \"icu.freedomintrovert.YTSendCommAntiFraud.ByXposedLunchedActivity\"));\r\n intent.putExtra(\"context1\", creatCommentRequest.getContext1().toByteArray());\r\n intent.putExtra(\"commentText\", creatCommentRequest.getCommentText());\r\n RunAttestationCommand runAttestationCommand = creatCommentResponse.getActions().getRunAttestationCommand();\r\n String commentId = runAttestationCommand.getIds(0).getCommentId();\r\n String videoId = runAttestationCommand.getIds(1).getEncryptedVideoId();\r\n intent.putExtra(\"commentId\", commentId);\r\n intent.putExtra(\"videoId\", videoId);\r\n Bundle headersBundle = new Bundle();\r\n for (AbstractMap.SimpleImmutableEntry<String, String> header : headers) {\r\n headersBundle.putString(header.getKey(), header.getValue());\r\n }\r\n intent.putExtra(\"headers\", headersBundle);\r\n intent.putExtra(\"action\", Action.CHECK_VIDEO_COMMENT);\r\n\r\n //由于视频评论区与社区评论区共用一个api但请求体响应体存在很大差异,若未获取到视频ID则说明是社区不跳转检查\r\n if (!TextUtils.isEmpty(videoId)) {\r\n currentContext.get().startActivity(intent);\r\n }\r\n }\r\n\r\n public static byte[] bytebuffer2ByteArray(ByteBuffer buffer) {\r\n //重置 limit 和postion 值\r\n buffer.flip();\r\n //获取buffer中有效大小\r\n int len = buffer.limit() - buffer.position();\r\n\r\n byte[] bytes = new byte[len];\r\n\r\n for (int i = 0; i < bytes.length; i++) {\r\n bytes[i] = buffer.get();\r\n }\r\n\r\n return bytes;\r\n }\r\n}\r" }, { "identifier": "SetOrientationHook", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/xposed/hooks/SetOrientationHook.java", "snippet": "public class SetOrientationHook extends BaseHook {\r\n private long lastOnResumeTime = 0;\r\n\r\n @Override\r\n public void startHook(int appVersionCode, ClassLoader classLoader) throws ClassNotFoundException {\r\n XposedHelpers.findAndHookMethod(Activity.class, \"setRequestedOrientation\", int.class, new XC_MethodHook() {\r\n @Override\r\n protected void beforeHookedMethod(MethodHookParam param) throws Throwable {\r\n super.beforeHookedMethod(param);\r\n Activity activity = (Activity) param.thisObject;\r\n\r\n int orientation = (int) param.args[0];\r\n if (orientation == ActivityInfo.SCREEN_ORIENTATION_USER && activity.getResources().getConfiguration().orientation == 2 && lastOnResumeTime + 5000 >= System.currentTimeMillis()) {\r\n XposedBridge.log(\"已禁止返回时旋转至竖屏\");\r\n param.args[0] = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;\r\n }\r\n }\r\n\r\n @Override\r\n protected void afterHookedMethod(MethodHookParam param) throws Throwable {\r\n super.afterHookedMethod(param);\r\n\r\n }\r\n });\r\n XposedHelpers.findAndHookMethod(\"com.google.android.apps.youtube.app.watchwhile.WatchWhileActivity\", classLoader, \"onResume\", new XC_MethodHook() {\r\n @Override\r\n protected void afterHookedMethod(MethodHookParam param) throws Throwable {\r\n super.afterHookedMethod(param);\r\n lastOnResumeTime = System.currentTimeMillis();\r\n }\r\n });\r\n }\r\n}\r" } ]
import android.content.Context; import java.util.Arrays; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.XC_MethodReplacement; import de.robv.android.xposed.XposedBridge; import de.robv.android.xposed.XposedHelpers; import de.robv.android.xposed.callbacks.XC_LoadPackage; import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.CopyUrlHook; import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.OpenLinkHook; import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.PostCommentHook; import icu.freedomintrovert.YTSendCommAntiFraud.xposed.hooks.SetOrientationHook;
4,264
package icu.freedomintrovert.YTSendCommAntiFraud.xposed; public class XposedInit implements IXposedHookLoadPackage { @Override public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { if (loadPackageParam.packageName.equals("com.google.android.youtube") || loadPackageParam.packageName.equals("app.rvx.android.youtube")) { InHookXConfig config = InHookXConfig.getInstance(); ClassLoader classLoader = loadPackageParam.classLoader; int appVersionCode = systemContext().getPackageManager().getPackageInfo(loadPackageParam.packageName, 0).versionCode; XposedBridge.log("YouTube version code:" + appVersionCode); HookStater hookStater = new HookStater(appVersionCode,classLoader); hookStater.startHook(new PostCommentHook());//因有时候要抓取请求头,所以若关闭该选项仅不打开activity,保留记录请求头 if (config.getShareUrlAntiTrackingEnabled()) {
package icu.freedomintrovert.YTSendCommAntiFraud.xposed; public class XposedInit implements IXposedHookLoadPackage { @Override public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable { if (loadPackageParam.packageName.equals("com.google.android.youtube") || loadPackageParam.packageName.equals("app.rvx.android.youtube")) { InHookXConfig config = InHookXConfig.getInstance(); ClassLoader classLoader = loadPackageParam.classLoader; int appVersionCode = systemContext().getPackageManager().getPackageInfo(loadPackageParam.packageName, 0).versionCode; XposedBridge.log("YouTube version code:" + appVersionCode); HookStater hookStater = new HookStater(appVersionCode,classLoader); hookStater.startHook(new PostCommentHook());//因有时候要抓取请求头,所以若关闭该选项仅不打开activity,保留记录请求头 if (config.getShareUrlAntiTrackingEnabled()) {
hookStater.startHook(new CopyUrlHook());
0
2023-10-15 01:18:28+00:00
8k
New-Barams/This-Year-Ajaja-BE
src/main/java/com/newbarams/ajaja/module/plan/presentation/PlanController.java
[ { "identifier": "AjajaResponse", "path": "src/main/java/com/newbarams/ajaja/global/common/AjajaResponse.java", "snippet": "@Getter\n@JsonPropertyOrder({\"success\", \"data\"})\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class AjajaResponse<T> {\n\tprivate final Boolean success;\n\tprivate final T data;\n\n\tpublic AjajaResponse(Boolean success, T data) {\n\t\tthis.success = success;\n\t\tthis.data = data;\n\t}\n\n\tpublic static <T> AjajaResponse<T> ok(T data) {\n\t\treturn new AjajaResponse<>(true, data);\n\t}\n\n\tpublic static AjajaResponse<Void> ok() {\n\t\treturn new AjajaResponse<>(true, null);\n\t}\n}" }, { "identifier": "JwtParser", "path": "src/main/java/com/newbarams/ajaja/global/security/jwt/util/JwtParser.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class JwtParser {\n\tprivate final CustomUserDetailsService userDetailService;\n\tprivate final JwtSecretProvider jwtSecretProvider;\n\tprivate final RawParser rawParser;\n\n\tpublic Authentication parseAuthentication(String jwt) {\n\t\tLong userId = parseId(jwt);\n\t\tUserDetails user = userDetailService.loadUserByUsername(String.valueOf(userId));\n\t\treturn new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());\n\t}\n\n\tpublic Long parseId(String jwt) {\n\t\treturn getSpecificClaim(jwt, jwtSecretProvider.getSignature(), Long.class);\n\t}\n\n\tboolean isParsable(String jwt) {\n\t\treturn rawParser.isParsable(jwt);\n\t}\n\n\tDate parseExpireIn(String refreshToken) {\n\t\treturn getSpecificClaim(refreshToken, jwtSecretProvider.getDateKey(), Date.class);\n\t}\n\n\tprivate <T> T getSpecificClaim(String token, String key, Class<T> type) {\n\t\treturn rawParser.parseClaim(token)\n\t\t\t.map(claims -> claims.get(key, type))\n\t\t\t.orElseThrow(() -> new AjajaException(INVALID_TOKEN));\n\t}\n}" }, { "identifier": "BearerUtils", "path": "src/main/java/com/newbarams/ajaja/global/util/BearerUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class BearerUtils {\n\tprivate static final String BEARER_PREFIX = \"Bearer \";\n\n\tpublic static String toBearer(String token) {\n\t\tObjects.requireNonNull(token, \"Token must be not null\");\n\t\treturn BEARER_PREFIX + token;\n\t}\n\n\tpublic static void validate(String token) {\n\t\tif (isNotBearer(token)) {\n\t\t\tthrow new AjajaException(INVALID_BEARER_TOKEN);\n\t\t}\n\t}\n\n\tprivate static boolean isNotBearer(String token) {\n\t\treturn token == null || !token.startsWith(BEARER_PREFIX);\n\t}\n\n\tpublic static String resolve(String bearerToken) {\n\t\treturn bearerToken.substring(BEARER_PREFIX.length());\n\t}\n}" }, { "identifier": "SwitchAjajaService", "path": "src/main/java/com/newbarams/ajaja/module/ajaja/application/SwitchAjajaService.java", "snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class SwitchAjajaService {\n\tprivate final AjajaRepository ajajaRepository;\n\tprivate final LoadPlanService loadPlanService;\n\n\tpublic void switchOrAddIfNotExist(Long userId, Long planId) {\n\t\tPlan plan = loadPlanService.loadPlanOrElseThrow(planId);\n\n\t\tAjaja ajaja = ajajaRepository.findByTargetIdAndUserIdAndType(planId, userId, PLAN.name())\n\t\t\t.orElseGet(Ajaja::defaultValue);\n\n\t\tif (ajaja.isEqualsDefault()) {\n\t\t\taddToPlan(plan, userId);\n\t\t\treturn;\n\t\t}\n\n\t\tswitchStatus(ajaja);\n\t}\n\n\tprivate void addToPlan(Plan plan, Long userId) {\n\t\tAjaja ajaja = Ajaja.plan(plan.getId(), userId);\n\t\tajajaRepository.save(ajaja);\n\t}\n\n\tprivate void switchStatus(Ajaja ajaja) {\n\t\tajaja.switchStatus();\n\t\tajajaRepository.save(ajaja);\n\t}\n}" }, { "identifier": "CreatePlanService", "path": "src/main/java/com/newbarams/ajaja/module/plan/application/CreatePlanService.java", "snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class CreatePlanService {\n\tprivate static final int MAX_NUMBER_OF_PLANS = 4;\n\n\tprivate final PlanRepository planRepository;\n\tprivate final PlanQueryRepository planQueryRepository;\n\tprivate final CreatePlanTagService createPlanTagService;\n\tprivate final PlanMapper planMapper;\n\n\tpublic PlanResponse.Create create(Long userId, PlanRequest.Create request, int month) {\n\t\tcheckNumberOfUserPlans(userId);\n\n\t\tPlan plan = Plan.create(planMapper.toParam(userId, request, month));\n\t\tPlan savedPlan = planRepository.save(plan);\n\n\t\tList<String> tags = createPlanTagService.create(savedPlan.getId(), request.getTags());\n\n\t\treturn planMapper.toResponse(savedPlan, tags);\n\t}\n\n\tprivate void checkNumberOfUserPlans(Long userId) {\n\t\tlong countOfPlans = planQueryRepository.countByUserId(userId);\n\n\t\tif (isMoreThanMaxNumberOfPlans(countOfPlans)) {\n\t\t\tthrow new AjajaException(EXCEED_MAX_NUMBER_OF_PLANS);\n\t\t}\n\t}\n\n\tprivate boolean isMoreThanMaxNumberOfPlans(long count) {\n\t\treturn count >= MAX_NUMBER_OF_PLANS;\n\t}\n}" }, { "identifier": "DeletePlanService", "path": "src/main/java/com/newbarams/ajaja/module/plan/application/DeletePlanService.java", "snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class DeletePlanService {\n\tprivate final LoadPlanService getPlanService;\n\tprivate final DeletePlanTagService deletePlanTagService;\n\tprivate final PlanRepository planRepository;\n\n\tpublic void delete(Long id, Long userId, int month) {\n\t\tdeletePlanTagService.delete(id);\n\n\t\tPlan plan = getPlanService.loadPlanOrElseThrow(id);\n\t\tplan.delete(userId, month);\n\n\t\tplanRepository.save(plan);\n\t}\n}" }, { "identifier": "LoadPlanInfoService", "path": "src/main/java/com/newbarams/ajaja/module/plan/application/LoadPlanInfoService.java", "snippet": "@Service\n@Transactional(readOnly = true)\n@RequiredArgsConstructor\npublic class LoadPlanInfoService {\n\tprivate final PlanQueryRepository planQueryRepository;\n\tprivate final LoadTotalAchieveService loadTotalAchieveService;\n\tprivate final PlanMapper mapper;\n\n\tpublic List<PlanResponse.MainInfo> loadPlanInfo(Long userId) {\n\t\tList<PlanResponse.PlanInfo> planInfos = planQueryRepository.findAllPlanByUserId(userId);\n\n\t\tif (planInfos.isEmpty()) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tint currentYear = planInfos.get(0).getYear();\n\t\tint firstYear = planInfos.get(planInfos.size() - 1).getYear();\n\n\t\treturn loadPlanInfoResponses(currentYear, firstYear, planInfos, userId);\n\t}\n\n\tprivate List<PlanResponse.MainInfo> loadPlanInfoResponses(\n\t\tint currentYear,\n\t\tint firstYear,\n\t\tList<PlanResponse.PlanInfo> planInfos,\n\t\tLong userId\n\t) {\n\t\tList<PlanResponse.MainInfo> planInfoResponses = new ArrayList<>();\n\n\t\tfor (int planYear = currentYear; planYear >= firstYear; planYear--) {\n\t\t\tint totalAchieve = loadTotalAchieveService.loadTotalAchieve(userId, planYear);\n\t\t\tPlanResponse.MainInfo planInfoResponse\n\t\t\t\t= mapper.toResponse(planYear, totalAchieve, planInfos);\n\t\t\tplanInfoResponses.add(planInfoResponse);\n\t\t}\n\n\t\treturn planInfoResponses;\n\t}\n}" }, { "identifier": "LoadPlanService", "path": "src/main/java/com/newbarams/ajaja/module/plan/application/LoadPlanService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class LoadPlanService {\n\tprivate final PlanRepository planRepository;\n\tprivate final PlanQueryRepository planQueryRepository;\n\tprivate final PlanMapper planMapper;\n\n\tpublic PlanResponse.Detail loadByIdAndOptionalUser(Long userId, Long id) {\n\t\treturn planQueryRepository.findPlanDetailByIdAndOptionalUser(userId, id)\n\t\t\t.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));\n\t}\n\n\tpublic Plan loadByUserIdAndPlanId(Long userId, Long id) {\n\t\treturn planQueryRepository.findByUserIdAndPlanId(userId, id);\n\t}\n\n\tpublic Plan loadPlanOrElseThrow(Long id) {\n\t\treturn planRepository.findById(id)\n\t\t\t.orElseThrow(() -> AjajaException.withId(id, NOT_FOUND_PLAN));\n\t}\n\n\tpublic PlanFeedbackInfo loadPlanFeedbackInfoByPlanId(Long userId, Long planId) {\n\t\tPlan plan = loadByUserIdAndPlanId(userId, planId);\n\t\treturn planMapper.toModel(plan);\n\t}\n\n\tpublic List<PlanResponse.GetAll> loadAllPlans(PlanRequest.GetAll request) {\n\t\treturn planQueryRepository.findAllByCursorAndSorting(request);\n\t}\n}" }, { "identifier": "UpdatePlanService", "path": "src/main/java/com/newbarams/ajaja/module/plan/application/UpdatePlanService.java", "snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class UpdatePlanService {\n\tprivate final LoadPlanService getPlanService;\n\tprivate final UpdatePlanTagService updatePlanTagService;\n\tprivate final PlanRepository planRepository;\n\tprivate final PlanMapper planMapper;\n\n\tpublic void updatePublicStatus(Long id, Long userId) {\n\t\tPlan plan = getPlanService.loadPlanOrElseThrow(id);\n\n\t\tplan.updatePublicStatus(userId);\n\t\tplanRepository.save(plan);\n\t}\n\n\tpublic void updateRemindStatus(Long id, Long userId) {\n\t\tPlan plan = getPlanService.loadPlanOrElseThrow(id);\n\n\t\tplan.updateRemindStatus(userId);\n\t\tplanRepository.save(plan);\n\t}\n\n\tpublic void updateAjajaStatus(Long id, Long userId) {\n\t\tPlan plan = getPlanService.loadPlanOrElseThrow(id);\n\n\t\tplan.updateAjajaStatus(userId);\n\t\tplanRepository.save(plan);\n\t}\n\n\tpublic PlanResponse.Detail update(Long id, Long userId, PlanRequest.Update request, int month) {\n\t\tPlan plan = getPlanService.loadPlanOrElseThrow(id);\n\t\tupdatePlanTagService.update(id, request.getTags());\n\n\t\tplan.update(planMapper.toParam(userId, request, month));\n\n\t\tplanRepository.save(plan);\n\n\t\treturn getPlanService.loadByIdAndOptionalUser(userId, id);\n\t}\n}" }, { "identifier": "UpdateRemindInfoService", "path": "src/main/java/com/newbarams/ajaja/module/plan/application/UpdateRemindInfoService.java", "snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class UpdateRemindInfoService {\n\tprivate final PlanQueryRepository planQueryRepository;\n\tprivate final PlanRepository planRepository;\n\tprivate final MessageMapper mapper;\n\n\tpublic void updateRemindInfo(Long userId, Long planId, PlanRequest.UpdateRemind request) {\n\t\tPlan plan = planQueryRepository.findByUserIdAndPlanId(userId, planId);\n\n\t\tplan.updateRemind(mapper.toDomain(request), mapper.toDomain(request.getMessages()));\n\t\tplanRepository.save(plan);\n\t}\n}" }, { "identifier": "PlanRequest", "path": "src/main/java/com/newbarams/ajaja/module/plan/dto/PlanRequest.java", "snippet": "public class PlanRequest {\n\t@Data\n\tpublic static class Create {\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int remindTotalPeriod;\n\t\tprivate final int remindTerm;\n\t\tprivate final int remindDate;\n\t\tprivate final String remindTime;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final List<Message> messages;\n\t}\n\n\t@Data\n\tpublic static class Message {\n\t\tprivate final String content;\n\t\tprivate final int remindMonth;\n\t\tprivate final int remindDay;\n\t}\n\n\t@Data\n\tpublic static class Update {\n\t\tprivate final int iconNumber;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final List<String> tags;\n\t}\n\n\t@Data\n\tpublic static class UpdateRemind {\n\t\tint remindTotalPeriod;\n\t\tint remindTerm;\n\t\tint remindDate;\n\t\tString remindTime;\n\t\tList<Message> messages;\n\t}\n\n\t@Data\n\tpublic static class GetAll {\n\t\tprivate final String sort;\n\t\tprivate final boolean current;\n\t\tprivate final Integer ajaja;\n\t\tprivate final Long start;\n\t}\n}" }, { "identifier": "PlanResponse", "path": "src/main/java/com/newbarams/ajaja/module/plan/dto/PlanResponse.java", "snippet": "public final class PlanResponse {\n\t@Data\n\tpublic static class Detail {\n\t\tprivate final Writer writer;\n\t\tprivate final Long id;\n\t\tprivate final String title;\n\t\tprivate final String description;\n\t\tprivate final int icon;\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\t\tprivate final long ajajas;\n\t\tprivate final List<String> tags;\n\t\tprivate final Instant createdAt;\n\n\t\t@QueryProjection\n\t\tpublic Detail(Writer writer, Long id, String title, String description, int icon, boolean isPublic,\n\t\t\tboolean canRemind, boolean canAjaja, long ajajas, List<String> tags, Instant createdAt\n\t\t) {\n\t\t\tthis.writer = writer;\n\t\t\tthis.id = id;\n\t\t\tthis.title = title;\n\t\t\tthis.description = description;\n\t\t\tthis.icon = icon;\n\t\t\tthis.isPublic = isPublic;\n\t\t\tthis.canRemind = canRemind;\n\t\t\tthis.canAjaja = canAjaja;\n\t\t\tthis.ajajas = ajajas;\n\t\t\tthis.tags = tags;\n\t\t\tthis.createdAt = createdAt;\n\t\t}\n\t}\n\n\t@Data\n\tpublic static class Writer {\n\t\tprivate final String nickname;\n\t\tprivate final boolean isOwner;\n\t\tprivate final boolean isAjajaPressed;\n\n\t\t@QueryProjection\n\t\tpublic Writer(String nickname, boolean isOwner, boolean isAjajaPressed) {\n\t\t\tthis.nickname = nickname;\n\t\t\tthis.isOwner = isOwner;\n\t\t\tthis.isAjajaPressed = isAjajaPressed;\n\t\t}\n\t}\n\n\t@Data\n\tpublic static class GetOne {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\t\tprivate final String nickname;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final long ajajas;\n\t\tprivate final boolean isPressAjaja;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final Instant createdAt;\n\t}\n\n\t@Data\n\tpublic static class GetAll {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\t\tprivate final String nickname;\n\n\t\tprivate final String title;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final long ajajas;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final Instant createdAt;\n\t}\n\n\t@Data\n\tpublic static class Create {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final int ajajas = 0;\n\n\t\tprivate final List<String> tags;\n\t}\n\n\t@Data\n\tpublic static class MainInfo {\n\t\tprivate final int year;\n\t\tprivate final int totalAchieveRate;\n\t\tprivate final List<PlanResponse.PlanInfo> getPlanList;\n\t}\n\n\t@Data\n\tpublic static class PlanInfo {\n\t\tprivate final int year;\n\t\tprivate final Long planId;\n\t\tprivate final String title;\n\t\tprivate final boolean remindable;\n\t\tprivate final int achieveRate;\n\t\tprivate final int icon;\n\t}\n}" } ]
import static org.springframework.http.HttpHeaders.*; import static org.springframework.http.HttpStatus.*; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.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.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.newbarams.ajaja.global.common.AjajaResponse; import com.newbarams.ajaja.global.exception.ErrorResponse; import com.newbarams.ajaja.global.security.common.UserId; import com.newbarams.ajaja.global.security.jwt.util.JwtParser; import com.newbarams.ajaja.global.util.BearerUtils; import com.newbarams.ajaja.module.ajaja.application.SwitchAjajaService; 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.plan.dto.PlanRequest; import com.newbarams.ajaja.module.plan.dto.PlanResponse; import io.swagger.v3.oas.annotations.Operation; 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.tags.Tag; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; import lombok.RequiredArgsConstructor;
4,669
package com.newbarams.ajaja.module.plan.presentation; @Tag(name = "plan") @Validated @RestController @RequiredArgsConstructor @RequestMapping("/plans") public class PlanController { private final CreatePlanService createPlanService; private final LoadPlanService getPlanService; private final DeletePlanService deletePlanService; private final UpdatePlanService updatePlanService; private final LoadPlanInfoService loadPlanInfoService; private final UpdateRemindInfoService updateRemindInfoService; private final SwitchAjajaService switchAjajaService; private final JwtParser jwtParser; // todo: delete when authentication filtering update @PostMapping("/{id}/ajaja") public AjajaResponse<Void> switchAjaja(@UserId Long userId, @PathVariable Long id) { switchAjajaService.switchOrAddIfNotExist(userId, id); return AjajaResponse.ok(); } @Operation(summary = "계획 단건 조회 API", description = "토큰을 추가해서 보내면 계획 작성자인지, 아좌좌를 눌렀는지 추가적으로 판별합니다.") @GetMapping("/{id}") @ResponseStatus(OK) public AjajaResponse<PlanResponse.Detail> getPlanWithOptionalUser( @RequestHeader(value = AUTHORIZATION, required = false) String accessToken, @PathVariable Long id ) { Long userId = accessToken == null ? null : parseUserId(accessToken); PlanResponse.Detail response = getPlanService.loadByIdAndOptionalUser(userId, id); return AjajaResponse.ok(response); } private Long parseUserId(String accessToken) { BearerUtils.validate(accessToken); return jwtParser.parseId(BearerUtils.resolve(accessToken)); } @Operation(summary = "[토큰 필요] 계획 생성 API") @PostMapping @ResponseStatus(CREATED) public AjajaResponse<PlanResponse.Create> createPlan( @UserId Long userId,
package com.newbarams.ajaja.module.plan.presentation; @Tag(name = "plan") @Validated @RestController @RequiredArgsConstructor @RequestMapping("/plans") public class PlanController { private final CreatePlanService createPlanService; private final LoadPlanService getPlanService; private final DeletePlanService deletePlanService; private final UpdatePlanService updatePlanService; private final LoadPlanInfoService loadPlanInfoService; private final UpdateRemindInfoService updateRemindInfoService; private final SwitchAjajaService switchAjajaService; private final JwtParser jwtParser; // todo: delete when authentication filtering update @PostMapping("/{id}/ajaja") public AjajaResponse<Void> switchAjaja(@UserId Long userId, @PathVariable Long id) { switchAjajaService.switchOrAddIfNotExist(userId, id); return AjajaResponse.ok(); } @Operation(summary = "계획 단건 조회 API", description = "토큰을 추가해서 보내면 계획 작성자인지, 아좌좌를 눌렀는지 추가적으로 판별합니다.") @GetMapping("/{id}") @ResponseStatus(OK) public AjajaResponse<PlanResponse.Detail> getPlanWithOptionalUser( @RequestHeader(value = AUTHORIZATION, required = false) String accessToken, @PathVariable Long id ) { Long userId = accessToken == null ? null : parseUserId(accessToken); PlanResponse.Detail response = getPlanService.loadByIdAndOptionalUser(userId, id); return AjajaResponse.ok(response); } private Long parseUserId(String accessToken) { BearerUtils.validate(accessToken); return jwtParser.parseId(BearerUtils.resolve(accessToken)); } @Operation(summary = "[토큰 필요] 계획 생성 API") @PostMapping @ResponseStatus(CREATED) public AjajaResponse<PlanResponse.Create> createPlan( @UserId Long userId,
@RequestBody PlanRequest.Create request,
10
2023-10-23 07:24:17+00:00
8k
eclipse-jgit/jgit
org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/PackReverseIndex.java
[ { "identifier": "CorruptObjectException", "path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/CorruptObjectException.java", "snippet": "public class CorruptObjectException extends IOException {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate ObjectChecker.ErrorType errorType;\n\n\t/**\n\t * Report a specific error condition discovered in an object.\n\t *\n\t * @param type\n\t * type of error\n\t * @param id\n\t * identity of the bad object\n\t * @param why\n\t * description of the error.\n\t * @since 4.2\n\t */\n\tpublic CorruptObjectException(ObjectChecker.ErrorType type, AnyObjectId id,\n\t\t\tString why) {\n\t\tsuper(MessageFormat.format(JGitText.get().objectIsCorrupt3,\n\t\t\t\ttype.getMessageId(), id.name(), why));\n\t\tthis.errorType = type;\n\t}\n\n\t/**\n\t * Construct a CorruptObjectException for reporting a problem specified\n\t * object id\n\t *\n\t * @param id\n\t * a {@link org.eclipse.jgit.lib.AnyObjectId}\n\t * @param why\n\t * error message\n\t */\n\tpublic CorruptObjectException(AnyObjectId id, String why) {\n\t\tsuper(MessageFormat.format(JGitText.get().objectIsCorrupt, id.name(), why));\n\t}\n\n\t/**\n\t * Construct a CorruptObjectException for reporting a problem specified\n\t * object id\n\t *\n\t * @param id\n\t * a {@link org.eclipse.jgit.lib.ObjectId}\n\t * @param why\n\t * error message\n\t */\n\tpublic CorruptObjectException(ObjectId id, String why) {\n\t\tsuper(MessageFormat.format(JGitText.get().objectIsCorrupt, id.name(), why));\n\t}\n\n\t/**\n\t * Construct a CorruptObjectException for reporting a problem not associated\n\t * with a specific object id.\n\t *\n\t * @param why\n\t * error message\n\t */\n\tpublic CorruptObjectException(String why) {\n\t\tsuper(why);\n\t}\n\n\t/**\n\t * Construct a CorruptObjectException for reporting a problem not associated\n\t * with a specific object id.\n\t *\n\t * @param why\n\t * message describing the corruption.\n\t * @param cause\n\t * optional root cause exception\n\t * @since 3.4\n\t */\n\tpublic CorruptObjectException(String why, Throwable cause) {\n\t\tsuper(why);\n\t\tinitCause(cause);\n\t}\n\n\t/**\n\t * Specific error condition identified by\n\t * {@link org.eclipse.jgit.lib.ObjectChecker}.\n\t *\n\t * @return error condition or null.\n\t * @since 4.2\n\t */\n\t@Nullable\n\tpublic ObjectChecker.ErrorType getErrorType() {\n\t\treturn errorType;\n\t}\n}" }, { "identifier": "PackMismatchException", "path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/PackMismatchException.java", "snippet": "public class PackMismatchException extends IOException {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate boolean permanent;\n\n\t/**\n\t * Construct a pack modification error.\n\t *\n\t * @param why\n\t * description of the type of error.\n\t */\n\tpublic PackMismatchException(String why) {\n\t\tsuper(why);\n\t}\n\n\t/**\n\t * Set the type of the exception\n\t *\n\t * @param permanent\n\t * whether the exception is considered permanent\n\t * @since 5.9.1\n\t */\n\tpublic void setPermanent(boolean permanent) {\n\t\tthis.permanent = permanent;\n\t}\n\n\t/**\n\t * Check if this is a permanent problem\n\t *\n\t * @return if this is a permanent problem and repeatedly scanning the\n\t * packlist couldn't fix it\n\t * @since 5.9.1\n\t */\n\tpublic boolean isPermanent() {\n\t\treturn permanent;\n\t}\n}" }, { "identifier": "ObjectId", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectId.java", "snippet": "public class ObjectId extends AnyObjectId implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate static final ObjectId ZEROID;\n\n\tprivate static final String ZEROID_STR;\n\n\tstatic {\n\t\tZEROID = new ObjectId(0, 0, 0, 0, 0);\n\t\tZEROID_STR = ZEROID.name();\n\t}\n\n\t/**\n\t * Get the special all-null ObjectId.\n\t *\n\t * @return the all-null ObjectId, often used to stand-in for no object.\n\t */\n\tpublic static final ObjectId zeroId() {\n\t\treturn ZEROID;\n\t}\n\n\t/**\n\t * Test a string of characters to verify it is a hex format.\n\t * <p>\n\t * If true the string can be parsed with {@link #fromString(String)}.\n\t *\n\t * @param id\n\t * the string to test.\n\t * @return true if the string can converted into an ObjectId.\n\t */\n\tpublic static final boolean isId(@Nullable String id) {\n\t\tif (id == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (id.length() != Constants.OBJECT_ID_STRING_LENGTH)\n\t\t\treturn false;\n\t\ttry {\n\t\t\tfor (int i = 0; i < Constants.OBJECT_ID_STRING_LENGTH; i++) {\n\t\t\t\tRawParseUtils.parseHexInt4((byte) id.charAt(i));\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (ArrayIndexOutOfBoundsException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Convert an ObjectId into a hex string representation.\n\t *\n\t * @param i\n\t * the id to convert. May be null.\n\t * @return the hex string conversion of this id's content.\n\t */\n\tpublic static final String toString(ObjectId i) {\n\t\treturn i != null ? i.name() : ZEROID_STR;\n\t}\n\n\t/**\n\t * Compare two object identifier byte sequences for equality.\n\t *\n\t * @param firstBuffer\n\t * the first buffer to compare against. Must have at least 20\n\t * bytes from position fi through the end of the buffer.\n\t * @param fi\n\t * first offset within firstBuffer to begin testing.\n\t * @param secondBuffer\n\t * the second buffer to compare against. Must have at least 20\n\t * bytes from position si through the end of the buffer.\n\t * @param si\n\t * first offset within secondBuffer to begin testing.\n\t * @return true if the two identifiers are the same.\n\t */\n\tpublic static boolean equals(final byte[] firstBuffer, final int fi,\n\t\t\tfinal byte[] secondBuffer, final int si) {\n\t\treturn firstBuffer[fi] == secondBuffer[si]\n\t\t\t\t&& firstBuffer[fi + 1] == secondBuffer[si + 1]\n\t\t\t\t&& firstBuffer[fi + 2] == secondBuffer[si + 2]\n\t\t\t\t&& firstBuffer[fi + 3] == secondBuffer[si + 3]\n\t\t\t\t&& firstBuffer[fi + 4] == secondBuffer[si + 4]\n\t\t\t\t&& firstBuffer[fi + 5] == secondBuffer[si + 5]\n\t\t\t\t&& firstBuffer[fi + 6] == secondBuffer[si + 6]\n\t\t\t\t&& firstBuffer[fi + 7] == secondBuffer[si + 7]\n\t\t\t\t&& firstBuffer[fi + 8] == secondBuffer[si + 8]\n\t\t\t\t&& firstBuffer[fi + 9] == secondBuffer[si + 9]\n\t\t\t\t&& firstBuffer[fi + 10] == secondBuffer[si + 10]\n\t\t\t\t&& firstBuffer[fi + 11] == secondBuffer[si + 11]\n\t\t\t\t&& firstBuffer[fi + 12] == secondBuffer[si + 12]\n\t\t\t\t&& firstBuffer[fi + 13] == secondBuffer[si + 13]\n\t\t\t\t&& firstBuffer[fi + 14] == secondBuffer[si + 14]\n\t\t\t\t&& firstBuffer[fi + 15] == secondBuffer[si + 15]\n\t\t\t\t&& firstBuffer[fi + 16] == secondBuffer[si + 16]\n\t\t\t\t&& firstBuffer[fi + 17] == secondBuffer[si + 17]\n\t\t\t\t&& firstBuffer[fi + 18] == secondBuffer[si + 18]\n\t\t\t\t&& firstBuffer[fi + 19] == secondBuffer[si + 19];\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param bs\n\t * the raw byte buffer to read from. At least 20 bytes must be\n\t * available within this byte array.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(byte[] bs) {\n\t\treturn fromRaw(bs, 0);\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param bs\n\t * the raw byte buffer to read from. At least 20 bytes after p\n\t * must be available within this byte array.\n\t * @param p\n\t * position to read the first byte of data from.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(byte[] bs, int p) {\n\t\tfinal int a = NB.decodeInt32(bs, p);\n\t\tfinal int b = NB.decodeInt32(bs, p + 4);\n\t\tfinal int c = NB.decodeInt32(bs, p + 8);\n\t\tfinal int d = NB.decodeInt32(bs, p + 12);\n\t\tfinal int e = NB.decodeInt32(bs, p + 16);\n\t\treturn new ObjectId(a, b, c, d, e);\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param is\n\t * the raw integers buffer to read from. At least 5 integers must\n\t * be available within this int array.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(int[] is) {\n\t\treturn fromRaw(is, 0);\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param is\n\t * the raw integers buffer to read from. At least 5 integers\n\t * after p must be available within this int array.\n\t * @param p\n\t * position to read the first integer of data from.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(int[] is, int p) {\n\t\treturn new ObjectId(is[p], is[p + 1], is[p + 2], is[p + 3], is[p + 4]);\n\t}\n\n\t/**\n\t * Convert an ObjectId from hex characters (US-ASCII).\n\t *\n\t * @param buf\n\t * the US-ASCII buffer to read from. At least 40 bytes after\n\t * offset must be available within this byte array.\n\t * @param offset\n\t * position to read the first character from.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromString(byte[] buf, int offset) {\n\t\treturn fromHexString(buf, offset);\n\t}\n\n\t/**\n\t * Convert an ObjectId from hex characters.\n\t *\n\t * @param str\n\t * the string to read from. Must be 40 characters long.\n\t * @return the converted object id.\n\t */\n\tpublic static ObjectId fromString(String str) {\n\t\tif (str.length() != Constants.OBJECT_ID_STRING_LENGTH) {\n\t\t\tthrow new InvalidObjectIdException(str);\n\t\t}\n\t\treturn fromHexString(Constants.encodeASCII(str), 0);\n\t}\n\n\tprivate static final ObjectId fromHexString(byte[] bs, int p) {\n\t\ttry {\n\t\t\tfinal int a = RawParseUtils.parseHexInt32(bs, p);\n\t\t\tfinal int b = RawParseUtils.parseHexInt32(bs, p + 8);\n\t\t\tfinal int c = RawParseUtils.parseHexInt32(bs, p + 16);\n\t\t\tfinal int d = RawParseUtils.parseHexInt32(bs, p + 24);\n\t\t\tfinal int e = RawParseUtils.parseHexInt32(bs, p + 32);\n\t\t\treturn new ObjectId(a, b, c, d, e);\n\t\t} catch (ArrayIndexOutOfBoundsException e) {\n\t\t\tInvalidObjectIdException e1 = new InvalidObjectIdException(bs, p,\n\t\t\t\t\tConstants.OBJECT_ID_STRING_LENGTH);\n\t\t\te1.initCause(e);\n\t\t\tthrow e1;\n\t\t}\n\t}\n\n\t/**\n\t * Construct an ObjectId from 160 bits provided in 5 words.\n\t *\n\t * @param new_1\n\t * an int\n\t * @param new_2\n\t * an int\n\t * @param new_3\n\t * an int\n\t * @param new_4\n\t * an int\n\t * @param new_5\n\t * an int\n\t * @since 4.7\n\t */\n\tpublic ObjectId(int new_1, int new_2, int new_3, int new_4, int new_5) {\n\t\tw1 = new_1;\n\t\tw2 = new_2;\n\t\tw3 = new_3;\n\t\tw4 = new_4;\n\t\tw5 = new_5;\n\t}\n\n\t/**\n\t * Initialize this instance by copying another existing ObjectId.\n\t * <p>\n\t * This constructor is mostly useful for subclasses who want to extend an\n\t * ObjectId with more properties, but initialize from an existing ObjectId\n\t * instance acquired by other means.\n\t *\n\t * @param src\n\t * another already parsed ObjectId to copy the value out of.\n\t */\n\tprotected ObjectId(AnyObjectId src) {\n\t\tw1 = src.w1;\n\t\tw2 = src.w2;\n\t\tw3 = src.w3;\n\t\tw4 = src.w4;\n\t\tw5 = src.w5;\n\t}\n\n\t@Override\n\tpublic ObjectId toObjectId() {\n\t\treturn this;\n\t}\n\n\tprivate void writeObject(ObjectOutputStream os) throws IOException {\n\t\tos.writeInt(w1);\n\t\tos.writeInt(w2);\n\t\tos.writeInt(w3);\n\t\tos.writeInt(w4);\n\t\tos.writeInt(w5);\n\t}\n\n\tprivate void readObject(ObjectInputStream ois) throws IOException {\n\t\tw1 = ois.readInt();\n\t\tw2 = ois.readInt();\n\t\tw3 = ois.readInt();\n\t\tw4 = ois.readInt();\n\t\tw5 = ois.readInt();\n\t}\n}" } ]
import org.eclipse.jgit.errors.CorruptObjectException; import org.eclipse.jgit.errors.PackMismatchException; import org.eclipse.jgit.lib.ObjectId;
3,911
/* * Copyright (C) 2008, Marek Zawirski <[email protected]> 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.internal.storage.file; /** * <p> * Reverse index for forward pack index. Provides operations based on offset * instead of object id. Such offset-based reverse lookups are performed in * O(log n) time. * </p> * * @see PackIndex * @see Pack */ public interface PackReverseIndex { /** * Magic bytes that uniquely identify git reverse index files. */ byte[] MAGIC = { 'R', 'I', 'D', 'X' }; /** * The first reverse index file version. */ int VERSION_1 = 1; /** * Verify that the pack checksum found in the reverse index matches that * from the pack file. * * @param packFilePath * the path to display in event of a mismatch * @throws PackMismatchException * if the checksums do not match */ void verifyPackChecksum(String packFilePath) throws PackMismatchException; /** * Search for object id with the specified start offset in this pack * (reverse) index. * * @param offset * start offset of object to find. * @return object id for this offset, or null if no object was found. */
/* * Copyright (C) 2008, Marek Zawirski <[email protected]> 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.internal.storage.file; /** * <p> * Reverse index for forward pack index. Provides operations based on offset * instead of object id. Such offset-based reverse lookups are performed in * O(log n) time. * </p> * * @see PackIndex * @see Pack */ public interface PackReverseIndex { /** * Magic bytes that uniquely identify git reverse index files. */ byte[] MAGIC = { 'R', 'I', 'D', 'X' }; /** * The first reverse index file version. */ int VERSION_1 = 1; /** * Verify that the pack checksum found in the reverse index matches that * from the pack file. * * @param packFilePath * the path to display in event of a mismatch * @throws PackMismatchException * if the checksums do not match */ void verifyPackChecksum(String packFilePath) throws PackMismatchException; /** * Search for object id with the specified start offset in this pack * (reverse) index. * * @param offset * start offset of object to find. * @return object id for this offset, or null if no object was found. */
ObjectId findObject(long offset);
2
2023-10-20 15:09:17+00:00
8k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/client/model/HippoModel.java
[ { "identifier": "Naturalist", "path": "common/src/main/java/com/starfish_studios/naturalist/Naturalist.java", "snippet": "public class Naturalist {\n public static final String MOD_ID = \"naturalist\";\n public static final CreativeModeTab TAB = CommonPlatformHelper.registerCreativeModeTab(new ResourceLocation(MOD_ID, \"tab\"), () -> new ItemStack(NaturalistBlocks.TEDDY_BEAR.get()));\n public static final Logger LOGGER = LogManager.getLogger();\n\n public static void init() {\n GeckoLib.initialize();\n NaturalistBlocks.init();\n NaturalistItems.init();\n NaturalistBlockEntities.init();\n NaturalistSoundEvents.init();\n NaturalistEntityTypes.init();\n NaturalistPotions.init();\n }\n \n public static void registerBrewingRecipes() {\n CommonPlatformHelper.registerBrewingRecipe(Potions.AWKWARD, NaturalistItems.ANTLER.get(), NaturalistPotions.FOREST_DASHER.get());\n CommonPlatformHelper.registerBrewingRecipe(NaturalistPotions.FOREST_DASHER.get(), Items.REDSTONE, NaturalistPotions.LONG_FOREST_DASHER.get());\n CommonPlatformHelper.registerBrewingRecipe(NaturalistPotions.FOREST_DASHER.get(), Items.GLOWSTONE_DUST, NaturalistPotions.STRONG_FOREST_DASHER.get());\n }\n\n public static void registerSpawnPlacements() {\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.SNAIL.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Mob::checkMobSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BEAR.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BUTTERFLY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.FIREFLY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Firefly::checkFireflySpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.SNAKE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Snake::checkSnakeSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CORAL_SNAKE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Snake::checkSnakeSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.RATTLESNAKE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Snake::checkSnakeSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.DEER.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BLUEJAY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CANARY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CARDINAL.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ROBIN.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Bird::checkBirdSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.RHINO.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.LION.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ELEPHANT.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ZEBRA.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.GIRAFFE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.HIPPO.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Hippo::checkHippoSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.VULTURE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Vulture::checkVultureSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BOAR.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Animal::checkAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.DRAGONFLY.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING, Dragonfly::checkDragonflySpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.CATFISH.get(), SpawnPlacements.Type.IN_WATER, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, WaterAnimal::checkSurfaceWaterAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.ALLIGATOR.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Alligator::checkAlligatorSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.BASS.get(), SpawnPlacements.Type.IN_WATER, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, WaterAnimal::checkSurfaceWaterAnimalSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.LIZARD.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Mob::checkMobSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.TORTOISE.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Mob::checkMobSpawnRules);\n CommonPlatformHelper.registerSpawnPlacement(NaturalistEntityTypes.DUCK.get(), SpawnPlacements.Type.ON_GROUND, Heightmap.Types.MOTION_BLOCKING_NO_LEAVES, Duck::checkDuckSpawnRules);\n }\n\n\n public static void registerCompostables() {\n CommonPlatformHelper.registerCompostable(0.65F, NaturalistItems.SNAIL_SHELL.get());\n }\n}" }, { "identifier": "Hippo", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Hippo.java", "snippet": "public class Hippo extends Animal implements IAnimatable {\n private final AnimationFactory factory = GeckoLibUtil.createFactory(this);\n private static final Ingredient FOOD_ITEMS = Ingredient.of(Blocks.MELON.asItem());\n private int eatingTicks;\n\n public Hippo(EntityType<? extends Animal> entityType, Level level) {\n super(entityType, level);\n this.setPathfindingMalus(BlockPathTypes.WATER, 0.0f);\n this.maxUpStep = 1.0f;\n }\n\n public static AttributeSupplier.Builder createAttributes() {\n return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 40.0D).add(Attributes.FOLLOW_RANGE, 20.0D).add(Attributes.MOVEMENT_SPEED, 0.25D).add(Attributes.ATTACK_DAMAGE, 6.0D).add(Attributes.KNOCKBACK_RESISTANCE, 0.6D);\n }\n\n public static boolean checkHippoSpawnRules(EntityType<? extends Animal> entityType, LevelAccessor levelAccessor, MobSpawnType mobSpawnType, BlockPos blockPos, RandomSource randomSource) {\n /* if (levelAccessor.getBlockState(blockPos.below()).is(BlockTags.ANIMALS_SPAWNABLE_ON) && Animal.isBrightEnoughToSpawn(levelAccessor, blockPos)) {\n for (Direction direction : Direction.Plane.HORIZONTAL) {\n return levelAccessor.getFluidState(blockPos.below().relative(direction)).is(FluidTags.WATER);\n }\n }\n return false; */\n\n // THIS CRASHES\n\n BlockPos.MutableBlockPos mutableBlockPos = new BlockPos.MutableBlockPos();\n if (levelAccessor.getBlockState(blockPos.below()).is(BlockTags.ANIMALS_SPAWNABLE_ON) && Animal.isBrightEnoughToSpawn(levelAccessor, blockPos)) {\n for (int x = -16; x <= 16; x++) {\n for (int y = -1; y <= 1; y++) {\n for (int z = -16; z <= 16; z++) {\n mutableBlockPos.setWithOffset(blockPos, x, y, z);\n if (!levelAccessor.hasChunkAt(mutableBlockPos)) {\n continue;\n }\n if (levelAccessor.getFluidState(mutableBlockPos).is(FluidTags.WATER)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n }\n\n @Override\n public boolean isFood(ItemStack stack) {\n return FOOD_ITEMS.test(stack);\n }\n\n @Override\n public boolean canBreatheUnderwater() {\n return true;\n }\n\n @Override\n protected void registerGoals() {\n this.goalSelector.addGoal(0, new FloatGoal(this));\n this.goalSelector.addGoal(1, new BreedGoal(this, 1.0D));\n this.goalSelector.addGoal(2, new TemptGoal(this, 1.0D, FOOD_ITEMS, false));\n this.goalSelector.addGoal(3, new HippoAttackBoatsGoal(this, 1.25D));\n this.goalSelector.addGoal(4, new MeleeAttackGoal(this, 1.25D, true));\n this.goalSelector.addGoal(5, new BabyPanicGoal(this, 2.0D));\n this.goalSelector.addGoal(6, new FollowParentGoal(this, 1.25D));\n this.goalSelector.addGoal(7, new RandomSwimmingGoal(this, 1.0D, 10));\n this.goalSelector.addGoal(8, new LookAtPlayerGoal(this, Player.class, 6.0F));\n this.goalSelector.addGoal(9, new RandomLookAroundGoal(this));\n this.targetSelector.addGoal(1, new BabyHurtByTargetGoal(this));\n this.targetSelector.addGoal(2, new NearestAttackableTargetGoal<>(this, Player.class, 10, true, false, (entity) -> !this.isBaby() && entity.isInWater()));\n }\n\n @Override\n public InteractionResult mobInteract(Player player, InteractionHand hand) {\n ItemStack itemStack = player.getItemInHand(hand);\n if (this.isFood(itemStack)) {\n int age = this.getAge();\n if (!this.level.isClientSide && age == 0 && this.canFallInLove()) {\n this.eatingTicks = 10;\n this.setItemSlot(EquipmentSlot.MAINHAND, itemStack.copy());\n this.swing(InteractionHand.MAIN_HAND);\n float yRot = (this.getYRot() + 90) * Mth.DEG_TO_RAD;\n ((ServerLevel)level).sendParticles(new BlockParticleOption(ParticleTypes.BLOCK, Blocks.MELON.defaultBlockState()), this.getX() + Math.cos(yRot), this.getY() + 0.6, this.getZ() + Math.sin(yRot), 100, this.getBbWidth() / 4.0F, this.getBbHeight() / 4.0F, this.getBbWidth() / 4.0F, 0.05D);\n ((ServerLevel)level).sendParticles(new ItemParticleOption(ParticleTypes.ITEM, new ItemStack(Items.MELON_SLICE)), this.getX() + Math.cos(yRot), this.getY() + 0.6, this.getZ() + Math.sin(yRot), 100, this.getBbWidth() / 4.0F, this.getBbHeight() / 4.0F, this.getBbWidth() / 4.0F, 0.05D);\n this.playSound(SoundEvents.HORSE_EAT);\n this.playSound(SoundEvents.WOOD_BREAK);\n this.usePlayerItem(player, hand, itemStack);\n this.setInLove(player);\n return InteractionResult.SUCCESS;\n }\n if (this.isBaby()) {\n this.usePlayerItem(player, hand, itemStack);\n this.ageUp(Animal.getSpeedUpSecondsWhenFeeding(-age), true);\n return InteractionResult.sidedSuccess(this.level.isClientSide);\n }\n if (this.level.isClientSide) {\n return InteractionResult.CONSUME;\n }\n }\n return InteractionResult.PASS;\n }\n\n @Override\n public void aiStep() {\n super.aiStep();\n if (!this.level.isClientSide) {\n if (this.eatingTicks > 0) {\n this.eatingTicks--;\n } else {\n this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY);\n }\n }\n }\n\n @Override\n public double getFluidJumpThreshold() {\n return this.isBaby() ? super.getFluidJumpThreshold() : 1.25;\n }\n\n @Override\n protected float getWaterSlowDown() {\n return 0.98F;\n }\n\n @Override\n public boolean canMate(Animal otherAnimal) {\n return this.isInWater() && otherAnimal.isInWater() && super.canMate(otherAnimal);\n }\n\n @Nullable\n @Override\n public AgeableMob getBreedOffspring(ServerLevel serverLevel, AgeableMob ageableMob) {\n return NaturalistEntityTypes.HIPPO.get().create(serverLevel);\n }\n\n @Nullable\n @Override\n protected SoundEvent getHurtSound(DamageSource damageSource) {\n return NaturalistSoundEvents.HIPPO_HURT.get();\n }\n\n @Nullable\n @Override\n protected SoundEvent getAmbientSound() {\n return NaturalistSoundEvents.HIPPO_AMBIENT.get();\n }\n\n private <E extends IAnimatable> PlayState predicate(AnimationEvent<E> event) {\n if (this.getDeltaMovement().horizontalDistanceSqr() > 1.0E-6) {\n event.getController().setAnimation(new AnimationBuilder().loop(\"hippo.walk\"));\n event.getController().setAnimationSpeed(1.0D);\n } else {\n event.getController().setAnimation(new AnimationBuilder().loop(\"hippo.idle\"));\n event.getController().setAnimationSpeed(1.0D);\n }\n return PlayState.CONTINUE;\n }\n\n private <E extends IAnimatable> PlayState attackPredicate(AnimationEvent<E> event) {\n if (this.swinging && event.getController().getAnimationState().equals(AnimationState.Stopped)) {\n event.getController().markNeedsReload();\n event.getController().setAnimation(new AnimationBuilder().playOnce(\"hippo.bite\"));\n this.swinging = false;\n }\n return PlayState.CONTINUE;\n }\n\n @Override\n public void registerControllers(AnimationData data) {\n data.setResetSpeedInTicks(10);\n data.addAnimationController(new AnimationController<>(this, \"controller\", 10, this::predicate));\n data.addAnimationController(new AnimationController<>(this, \"attackController\", 0, this::attackPredicate));\n }\n\n @Override\n public AnimationFactory getFactory() {\n return factory;\n }\n\n static class HippoAttackBoatsGoal extends Goal {\n protected final PathfinderMob mob;\n private final double speedModifier;\n private Path path;\n private double pathedTargetX;\n private double pathedTargetY;\n private double pathedTargetZ;\n private int ticksUntilNextPathRecalculation;\n private int ticksUntilNextAttack;\n private long lastCanUseCheck;\n private Boat target;\n\n public HippoAttackBoatsGoal(PathfinderMob pathfinderMob, double speedModifier) {\n this.mob = pathfinderMob;\n this.speedModifier = speedModifier;\n this.setFlags(EnumSet.of(Flag.MOVE, Flag.LOOK, Flag.TARGET));\n }\n\n @Override\n public boolean canUse() {\n if (this.mob.isBaby()) {\n return false;\n }\n long gameTime = this.mob.level.getGameTime();\n if (gameTime - this.lastCanUseCheck < 20L) {\n return false;\n }\n this.lastCanUseCheck = gameTime;\n List<Boat> entities = this.mob.level.getEntitiesOfClass(Boat.class, this.mob.getBoundingBox().inflate(8, 4, 8));\n if (!entities.isEmpty()) {\n this.target = entities.get(0);\n }\n if (this.target == null) {\n return false;\n }\n if (this.target.isRemoved()) {\n return false;\n }\n this.path = this.mob.getNavigation().createPath(this.target, 0);\n if (this.path != null) {\n return true;\n }\n return this.getAttackReachSqr(this.target) >= this.mob.distanceToSqr(this.target.getX(), this.target.getY(), this.target.getZ());\n }\n\n @Override\n public boolean canContinueToUse() {\n if (this.target == null) {\n return false;\n }\n if (this.target.isRemoved()) {\n return false;\n }\n return !this.mob.getNavigation().isDone();\n }\n\n @Override\n public void start() {\n this.mob.getNavigation().moveTo(this.path, this.speedModifier);\n this.mob.setAggressive(true);\n this.ticksUntilNextPathRecalculation = 0;\n this.ticksUntilNextAttack = 0;\n }\n\n @Override\n public void stop() {\n LivingEntity livingEntity = this.mob.getTarget();\n if (!EntitySelector.NO_CREATIVE_OR_SPECTATOR.test(livingEntity)) {\n this.mob.setTarget(null);\n }\n this.mob.setAggressive(false);\n this.mob.getNavigation().stop();\n }\n\n @Override\n public boolean requiresUpdateEveryTick() {\n return true;\n }\n\n @Override\n public void tick() {\n if (this.target == null) {\n return;\n }\n this.mob.getLookControl().setLookAt(this.target, 30.0f, 30.0f);\n double d = this.mob.distanceToSqr(this.target.getX(), this.target.getY(), this.target.getZ());\n this.ticksUntilNextPathRecalculation = Math.max(this.ticksUntilNextPathRecalculation - 1, 0);\n if ((this.mob.getSensing().hasLineOfSight(this.target)) && this.ticksUntilNextPathRecalculation <= 0 && (this.pathedTargetX == 0.0 && this.pathedTargetY == 0.0 && this.pathedTargetZ == 0.0 || this.target.distanceToSqr(this.pathedTargetX, this.pathedTargetY, this.pathedTargetZ) >= 1.0 || this.mob.getRandom().nextFloat() < 0.05f)) {\n this.pathedTargetX = this.target.getX();\n this.pathedTargetY = this.target.getY();\n this.pathedTargetZ = this.target.getZ();\n this.ticksUntilNextPathRecalculation = 4 + this.mob.getRandom().nextInt(7);\n if (d > 1024.0) {\n this.ticksUntilNextPathRecalculation += 10;\n } else if (d > 256.0) {\n this.ticksUntilNextPathRecalculation += 5;\n }\n if (!this.mob.getNavigation().moveTo(this.target, this.speedModifier)) {\n this.ticksUntilNextPathRecalculation += 15;\n }\n this.ticksUntilNextPathRecalculation = this.adjustedTickDelay(this.ticksUntilNextPathRecalculation);\n }\n this.ticksUntilNextAttack = Math.max(this.ticksUntilNextAttack - 1, 0);\n this.checkAndPerformAttack(this.target, d);\n }\n\n protected void checkAndPerformAttack(Entity enemy, double distToEnemySqr) {\n double reach = this.getAttackReachSqr(enemy);\n if (distToEnemySqr <= reach && this.ticksUntilNextAttack <= 0) {\n this.resetAttackCooldown();\n this.mob.swing(InteractionHand.MAIN_HAND);\n this.mob.doHurtTarget(enemy);\n }\n }\n\n protected void resetAttackCooldown() {\n this.ticksUntilNextAttack = this.adjustedTickDelay(20);\n }\n\n protected double getAttackReachSqr(Entity attackTarget) {\n return Mth.square(this.mob.getBbWidth() * 1.2f) + attackTarget.getBbWidth();\n }\n }\n}" } ]
import com.starfish_studios.naturalist.Naturalist; import com.starfish_studios.naturalist.common.entity.Hippo; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.Mth; import org.jetbrains.annotations.Nullable; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.processor.IBone; import software.bernie.geckolib3.model.AnimatedGeoModel; import software.bernie.geckolib3.model.provider.data.EntityModelData; import java.util.List;
5,118
package com.starfish_studios.naturalist.client.model; @Environment(EnvType.CLIENT) public class HippoModel extends AnimatedGeoModel<Hippo> { @Override public ResourceLocation getModelResource(Hippo hippo) {
package com.starfish_studios.naturalist.client.model; @Environment(EnvType.CLIENT) public class HippoModel extends AnimatedGeoModel<Hippo> { @Override public ResourceLocation getModelResource(Hippo hippo) {
return new ResourceLocation(Naturalist.MOD_ID, "geo/hippo.geo.json");
0
2023-10-16 21:54:32+00:00
8k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/helper/IfwUtil.java
[ { "identifier": "BackupEntry", "path": "app/src/main/java/cn/wq/myandroidtoolspro/model/BackupEntry.java", "snippet": "public class BackupEntry extends ComponentEntry {\n public String appName;\n /**\n * @see cn.wq.myandroidtoolspro.helper.IfwUtil#COMPONENT_FLAG_ACTIVITY\n */\n public int cType;\n\n public boolean isSystem;\n}" }, { "identifier": "ComponentEntry", "path": "app/src/main/java/cn/wq/myandroidtoolspro/model/ComponentEntry.java", "snippet": "public class ComponentEntry extends ComponentModel {\r\n\tpublic boolean enabled;\r\n}\r" }, { "identifier": "AbstractComponentAdapter", "path": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/adapter/AbstractComponentAdapter.java", "snippet": "public abstract class AbstractComponentAdapter<T extends ComponentEntry>\r\n extends RecyclerView.Adapter\r\n implements Filterable{\r\n private List<T> list;\r\n private boolean isFullName;\r\n private ComponentFilter mFilter;\r\n private List<T> originalData;\r\n private final Object mLock = new Object();\r\n protected Context mContext;\r\n protected int primaryTextColor;\r\n protected int redTextColor;\r\n\r\n// public AbstractComponentAdapter() {\r\n// super();\r\n// this.list = new ArrayList<>();\r\n// }\r\n\r\n public AbstractComponentAdapter(Context context) {\r\n this.list = new ArrayList<>();\r\n mContext = context;\r\n primaryTextColor = Utils.getColorFromAttr(context, android.R.attr.textColorPrimary);\r\n redTextColor = ContextCompat.getColor(mContext, R.color.holo_red_light);\r\n }\r\n\r\n public T getItem(int position) {\r\n return list.get(position);\r\n }\r\n\r\n public void setData(List<T> list) {\r\n this.list.clear();\r\n if (list != null) {\r\n this.list.addAll(list);\r\n }\r\n\r\n //wq:搜索后禁用 刷新状态\r\n if(originalData!=null){\r\n originalData.clear();\r\n originalData=null;\r\n }\r\n\r\n notifyDataSetChanged();\r\n }\r\n\r\n @Override\r\n public int getItemCount() {\r\n return list.size();\r\n }\r\n\r\n public boolean toggleName() {\r\n isFullName = !isFullName;\r\n notifyDataSetChanged();\r\n return isFullName;\r\n }\r\n\r\n public boolean getIsFullName() {\r\n return isFullName;\r\n }\r\n\r\n @Override\r\n public Filter getFilter() {\r\n if (mFilter == null) {\r\n mFilter = new ComponentFilter();\r\n }\r\n return mFilter;\r\n }\r\n\r\n private class ComponentFilter extends Filter {\r\n @Override\r\n protected void publishResults(CharSequence constraint,\r\n FilterResults results) {\r\n list = (List<T>) results.values;\r\n notifyDataSetChanged();\r\n }\r\n\r\n @Override\r\n protected FilterResults performFiltering(CharSequence constraint) {\r\n final FilterResults results = new FilterResults();\r\n if (originalData == null) {\r\n synchronized (mLock) {\r\n originalData = new ArrayList<>(list);\r\n }\r\n }\r\n\r\n List<T> tempList;\r\n if (TextUtils.isEmpty(constraint)||constraint.toString().trim().length()==0) {\r\n synchronized (mLock) {\r\n tempList = new ArrayList<>(originalData);\r\n }\r\n results.values = tempList;\r\n results.count = tempList.size();\r\n } else {\r\n synchronized (mLock) {\r\n tempList = new ArrayList<>(originalData);\r\n }\r\n\r\n final List<T> newValues = new ArrayList<>();\r\n int type=-1;\r\n for (T entry : tempList) {\r\n if(type<0){\r\n type=0;\r\n if(entry instanceof ReceiverWithActionEntry){\r\n type=1;\r\n }\r\n }\r\n\r\n //最好trim一下\r\n String query=constraint.toString().trim().toLowerCase(Locale.getDefault());\r\n String lowerName=entry.className.toLowerCase(Locale.getDefault());\r\n if ((isFullName && lowerName.contains (query)\r\n || (!isFullName && lowerName.substring(lowerName.lastIndexOf(\".\")+1).contains(query)))){\r\n newValues.add(entry);\r\n }else if(type>0){\r\n ReceiverWithActionEntry receiverEntry= (ReceiverWithActionEntry) entry;\r\n if(receiverEntry.appName.toLowerCase(Locale.getDefault()).contains(query)){\r\n newValues.add(entry);\r\n }\r\n }\r\n }\r\n\r\n results.values = newValues;\r\n results.count = newValues.size();\r\n }\r\n\r\n return results;\r\n }\r\n }\r\n\r\n}\r" }, { "identifier": "AppInfoForManageFragment2", "path": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/AppInfoForManageFragment2.java", "snippet": "public class AppInfoForManageFragment2 extends BaseFragment {\r\n private static final String TAG = \"AppInfoForManageFrag\";\r\n private ViewPager mViewPager;\r\n private TabLayout mTabLayout;\r\n private String packageName;\r\n private CustomProgressDialogFragment dialog;\r\n private Context mContext;\r\n private CompositeDisposable compositeDisposable = new CompositeDisposable();\r\n public static IfwUtil.IfwEntry mIfwEntry;\r\n\r\n @Override\r\n public void onAttach(Context context) {\r\n super.onAttach(context);\r\n mContext = context;\r\n }\r\n\r\n public static AppInfoForManageFragment2 newInstance(Bundle args){\r\n AppInfoForManageFragment2 f=new AppInfoForManageFragment2();\r\n\t\tf.setArguments(args);\r\n\t\treturn f;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void onActivityCreated(Bundle savedInstanceState) {\r\n\t\tsuper.onActivityCreated(savedInstanceState);\r\n\t\tBundle data=getArguments();\r\n// packageName = data.getString(\"packageName\");\r\n\r\n initActionbar(2,data.getString(\"title\"));\r\n setToolbarLogo(packageName);\r\n\t}\r\n\r\n @Override\r\n public void onDestroy() {\r\n super.onDestroy();\r\n if (compositeDisposable != null) {\r\n compositeDisposable.clear();\r\n }\r\n if (mIfwEntry != null) {\r\n mIfwEntry.clear();\r\n }\r\n }\r\n\r\n @Override\r\n\tpublic View onCreateView(LayoutInflater inflater, ViewGroup container,\r\n\t\t\tBundle savedInstanceState) {\r\n setHasOptionsMenu(true);\r\n\r\n Bundle data=getArguments();\r\n if (data != null) {\r\n packageName = data.getString(\"packageName\");\r\n }\r\n\r\n final View root = inflater.inflate(R.layout.fragment_component_parent, container, false);\r\n if (!Utils.isPmByIfw(mContext)) {\r\n initViews(root);\r\n } else {\r\n Disposable disposable = Observable.create(new ObservableOnSubscribe<IfwUtil.IfwEntry>() {\r\n @Override\r\n public void subscribe(ObservableEmitter<IfwUtil.IfwEntry> emitter) throws Exception {\r\n IfwUtil.IfwEntry ifwEntry = IfwUtil.loadIfwFileForPkg(mContext, packageName, IfwUtil.COMPONENT_FLAG_ALL, false);\r\n emitter.onNext(ifwEntry);\r\n emitter.onComplete();\r\n }\r\n })\r\n .subscribeOn(Schedulers.io())\r\n .observeOn(AndroidSchedulers.mainThread())\r\n .doOnSubscribe(new Consumer<Disposable>() {\r\n @Override\r\n public void accept(Disposable disposable) {\r\n // TODO:wq 2019/4/17 最好是在布局中增加progressbar\r\n CustomProgressDialogFragment.showProgressDialog(\"loadIfw\", getFragmentManager());\r\n }\r\n })\r\n .doFinally(new Action() {\r\n @Override\r\n public void run() throws Exception {\r\n CustomProgressDialogFragment.hideProgressDialog(\"loadIfw\", getFragmentManager());\r\n }\r\n })\r\n .subscribe(new Consumer<IfwUtil.IfwEntry>() {\r\n @Override\r\n public void accept(IfwUtil.IfwEntry ifwEntry) throws Exception {\r\n mIfwEntry = ifwEntry;\r\n if (mIfwEntry == null) {\r\n Toast.makeText(mContext, R.string.load_ifw_by_root_failed, Toast.LENGTH_SHORT).show();\r\n return;\r\n } else if (mIfwEntry == IfwUtil.IfwEntry.ROOT_ERROR) {\r\n Toast.makeText(mContext, R.string.failed_to_gain_root, Toast.LENGTH_SHORT).show();\r\n return;\r\n }\r\n initViews(root);\r\n }\r\n }, new Consumer<Throwable>() {\r\n @Override\r\n public void accept(Throwable throwable) {\r\n throwable.printStackTrace();\r\n Log.e(TAG, \"loadIfwFileForPkg error\", throwable);\r\n Toast.makeText(mContext, R.string.load_ifw_by_root_failed, Toast.LENGTH_SHORT).show();\r\n }\r\n });\r\n\r\n compositeDisposable.add(disposable);\r\n }\r\n\t\treturn root;\r\n\t}\r\n\r\n private void initViews(View root) {\r\n mViewPager = (ViewPager) root.findViewById(R.id.view_pager);\r\n mViewPager.setAdapter(new MyPagerAdapter(this, getArguments()));\r\n mTabLayout = (TabLayout) root.findViewById(R.id.tab_layout);\r\n mTabLayout.setupWithViewPager(mViewPager);\r\n\r\n mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {\r\n private int pre_pos;\r\n\r\n @Override\r\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\r\n }\r\n\r\n @Override\r\n public void onPageSelected(int position) {\r\n if(pre_pos==position){\r\n return;\r\n }\r\n MultiSelectionRecyclerListFragment fragment=getFragment(pre_pos);\r\n if(fragment!=null){\r\n fragment.closeActionMode();\r\n }\r\n pre_pos = position;\r\n }\r\n\r\n @Override\r\n public void onPageScrollStateChanged(int state) {\r\n }\r\n });\r\n }\r\n\r\n @Override\r\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\r\n super.onCreateOptionsMenu(menu, inflater);\r\n\r\n if (!BuildConfig.isFree) {\r\n MenuItem manifest=menu.add(0, R.id.view_manifest, 0, R.string.view_manifest);\r\n MenuItemCompat.setShowAsAction(manifest,MenuItemCompat.SHOW_AS_ACTION_NEVER);\r\n\r\n MenuItem backup = menu.add(0, R.id.backup, 1, R.string.backup_disabled_of_an_app);\r\n MenuItemCompat.setShowAsAction(backup,MenuItemCompat.SHOW_AS_ACTION_NEVER);\r\n }\r\n\r\n }\r\n\r\n @Override\r\n public boolean onOptionsItemSelected(MenuItem item) {\r\n switch (item.getItemId()) {\r\n case R.id.view_manifest:\r\n Intent intent = new Intent(getContext(), ViewManifestActivity2.class);\r\n// Bundle args=getArguments();\r\n intent.putExtra(\"packageName\", packageName);\r\n// intent.putExtra(\"title\",args.getString(\"title\"));\r\n startActivity(intent);\r\n return true;\r\n case R.id.backup:\r\n backup();\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n private void backup() {\r\n setProgressDialogVisibility(true);\r\n\r\n StringBuilder sb = new StringBuilder();\r\n PackageManager pm = mContext.getPackageManager();\r\n\r\n List<ComponentModel> services= Utils.getComponentModels(mContext,packageName,4);\r\n for (ComponentModel s : services) {\r\n if (!Utils.isComponentEnabled(s, pm)) {\r\n sb.append(s.packageName)\r\n .append(\"/\")\r\n .append(s.className)\r\n .append(\"\\n\");\r\n }\r\n }\r\n\r\n String dirString= Environment.getExternalStorageDirectory() + \"/MyAndroidTools/\";\r\n File dir = new File(dirString);\r\n if (!dir.exists()) {\r\n dir.mkdirs();\r\n }\r\n\r\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyyMMdd_HHmm_SSS\", Locale.getDefault());\r\n String string= dirString+\"backup_\" + dateFormat.format(new Date());\r\n try {\r\n FileWriter writer = new FileWriter(new File(string));\r\n writer.write(sb.toString());\r\n writer.flush();\r\n writer.close();\r\n// Toast.makeText(mActivity, getString(R.string.backup_done, string), Toast.LENGTH_LONG).show();\r\n\r\n setProgressDialogVisibility(false);\r\n\r\n Bundle args = new Bundle();\r\n args.putString(\"path\",string);\r\n RenameDialogFragment renameDialog = new RenameDialogFragment();\r\n renameDialog.setArguments(args);\r\n renameDialog.show(getActivity().getSupportFragmentManager(),\"rename\");\r\n\r\n } catch (IOException e) {\r\n e.printStackTrace();\r\n setProgressDialogVisibility(false);\r\n Toast.makeText(mContext, R.string.operation_failed, Toast.LENGTH_SHORT).show();\r\n }\r\n\r\n }\r\n\r\n private void setProgressDialogVisibility(boolean visible) {\r\n if (visible) {\r\n if (dialog == null) {\r\n dialog = new CustomProgressDialogFragment();\r\n dialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0);\r\n dialog.setCancelable(false);\r\n }\r\n\r\n if (!dialog.isVisible() && getActivity() != null && !getActivity().isFinishing()) {\r\n try {\r\n dialog.show(getActivity().getSupportFragmentManager(), \"dialog\");\r\n } catch (Exception e) {\r\n }\r\n }\r\n } else {\r\n if (dialog != null && getFragmentManager()!=null) {\r\n dialog.dismissAllowingStateLoss();\r\n }\r\n }\r\n }\r\n\r\n private MultiSelectionRecyclerListFragment getFragment(int position){\r\n return (MultiSelectionRecyclerListFragment) getChildFragmentManager().findFragmentByTag(\"android:switcher:\" + mViewPager.getId() + \":\"\r\n + position);\r\n }\r\n\t\r\n\tprivate class MyPagerAdapter extends FragmentPagerAdapter {\r\n\t\tprivate String[] titles;\r\n\t\tprivate Bundle args;\r\n private int actionModeBackground = -1;\r\n private int defaultTabBackground = -1;\r\n\t\t\r\n MyPagerAdapter(Fragment fragment,Bundle bundle) {\r\n\t\t\tsuper(fragment.getChildFragmentManager());\r\n\t\t\targs=bundle;\r\n titles=new String[]{fragment.getString(R.string.service),\r\n fragment.getString(R.string.broadcast_receiver),\r\n fragment.getString(R.string.activity),\r\n fragment.getString(R.string.content_provider)};\r\n\r\n actionModeBackground = Utils.getColorFromAttr(mContext,R.attr.actionModeBackground);\r\n defaultTabBackground = Utils.getColorFromAttr(mContext, R.attr.colorPrimary);\r\n }\r\n\r\n\t\t@Override\r\n\t\tpublic Fragment getItem(int position) {\r\n args.putBoolean(\"ignoreToolbar\",true);\r\n args.putBoolean(\"useParentIfw\", true);\r\n\r\n MultiSelectionRecyclerListFragment f;\r\n\t\t\tswitch (position) {\r\n\t\t\tcase 0:\r\n\t\t\t\tf = ServiceRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\tcase 1:\r\n f = ReceiverRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\tcase 2:\r\n f = ActivityRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\tdefault:\r\n f = ProviderRecyclerListFragment.newInstance(args);\r\n break;\r\n\t\t\t}\r\n f.addActionModeLefecycleCallback(mActionModeLefecycleCallback);\r\n return f;\r\n\t\t}\r\n\r\n private MultiSelectionRecyclerListFragment.ActionModeLefecycleCallback mActionModeLefecycleCallback\r\n =new MultiSelectionRecyclerListFragment.ActionModeLefecycleCallback() {\r\n @Override\r\n public void onModeCreated() {\r\n// mTabLayout.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.blue_grey_500));\r\n mTabLayout.setBackgroundColor(actionModeBackground);\r\n }\r\n\r\n /**\r\n * onDestroyActionMode 将 statusbar 颜色置为透明了,在 AppInfoActivity 中会显示成灰白\r\n * @see cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionUtils.Controller#onDestroyActionMode(ActionMode)\r\n */\r\n @Override\r\n public void onModeDestroyed() {\r\n// mTabLayout.setBackgroundColor(ContextCompat.getColor(getActivity(),R.color.actionbar_color));\r\n mTabLayout.setBackgroundColor(defaultTabBackground);\r\n\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP\r\n && getActivity() != null\r\n && getActivity() instanceof AppInfoActivity) {\r\n getActivity().getWindow().setStatusBarColor(ContextCompat.getColor(getContext(),R.color.actionbar_color_dark));\r\n }\r\n }\r\n };\r\n\r\n\t\t@Override\r\n\t\tpublic int getCount() {\r\n\t\t\treturn titles.length;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic CharSequence getPageTitle(int position) {\r\n\t\t\treturn titles[position];\r\n\t\t}\r\n\t}\r\n\t\r\n}\r" } ]
import android.content.ComponentName; import android.content.Context; import android.os.Environment; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.util.ArrayMap; import android.text.TextUtils; import android.util.Xml; import com.tencent.mars.xlog.Log; import org.xmlpull.v1.XmlPullParser; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import cn.wq.myandroidtoolspro.model.BackupEntry; import cn.wq.myandroidtoolspro.model.ComponentEntry; import cn.wq.myandroidtoolspro.recyclerview.adapter.AbstractComponentAdapter; import cn.wq.myandroidtoolspro.recyclerview.fragment.AppInfoForManageFragment2;
4,091
package cn.wq.myandroidtoolspro.helper; public class IfwUtil { private static final String TAG = "IfwUtil"; private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled"; public static final int COMPONENT_FLAG_EMPTY = 0x00; public static final int COMPONENT_FLAG_ACTIVITY = 0x01; public static final int COMPONENT_FLAG_RECEIVER = 0x10; public static final int COMPONENT_FLAG_SERVICE = 0x100; public static final int COMPONENT_FLAG_ALL = 0x111; public static final String BACKUP_LOCAL_FILE_EXT = ".ifw"; public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀 public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀 /** * 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br> * 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容 * * @param positions 某一类component的位置 */ public static boolean saveComponentIfw(Context context, @NonNull String packageName, IfwEntry ifwEntry,
package cn.wq.myandroidtoolspro.helper; public class IfwUtil { private static final String TAG = "IfwUtil"; private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled"; public static final int COMPONENT_FLAG_EMPTY = 0x00; public static final int COMPONENT_FLAG_ACTIVITY = 0x01; public static final int COMPONENT_FLAG_RECEIVER = 0x10; public static final int COMPONENT_FLAG_SERVICE = 0x100; public static final int COMPONENT_FLAG_ALL = 0x111; public static final String BACKUP_LOCAL_FILE_EXT = ".ifw"; public static final String BACKUP_SYSTEM_FILE_EXT_OF_STANDARD = ".xml"; //标准ifw备份后缀 public static final String BACKUP_SYSTEM_FILE_EXT_OF_MINE = "$" + BACKUP_SYSTEM_FILE_EXT_OF_STANDARD; //本App备份ifw使用的后缀 /** * 组件列表中修改选中位置component的ifw状态,并保存所有component到ifw文件<br> * 每个类型的list中(例如ServiceRecyclerListFragment)的修改都需要完整保存整个ifw内容 * * @param positions 某一类component的位置 */ public static boolean saveComponentIfw(Context context, @NonNull String packageName, IfwEntry ifwEntry,
@NonNull AbstractComponentAdapter<? extends ComponentEntry> adapter,
1
2023-10-18 14:32:49+00:00
8k
instana/otel-dc
host/src/main/java/com/instana/dc/host/impl/SimpHostDc.java
[ { "identifier": "AbstractHostDc", "path": "host/src/main/java/com/instana/dc/host/AbstractHostDc.java", "snippet": "public abstract class AbstractHostDc extends AbstractDc implements IDc {\n private static final Logger logger = Logger.getLogger(AbstractHostDc.class.getName());\n\n private final String otelBackendUrl;\n private final boolean otelUsingHttp;\n private final int pollInterval;\n private final int callbackInterval;\n private final String serviceName;\n public final static String INSTRUMENTATION_SCOPE_PREFIX = \"otelcol/hostmetricsreceiver/\";\n\n private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();\n\n public AbstractHostDc(Map<String, String> properties, String hostSystem) {\n super(new HostRawMetricRegistry().getMap());\n\n String pollInt = properties.get(POLLING_INTERVAL);\n pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt);\n String callbackInt = properties.get(CALLBACK_INTERVAL);\n callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt);\n otelBackendUrl = properties.get(OTEL_BACKEND_URL);\n otelUsingHttp = \"true\".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP));\n String svcName = properties.get(OTEL_SERVICE_NAME);\n serviceName = svcName == null ? hostSystem : svcName;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n @Override\n public void initDC() throws Exception {\n Resource resource = getResourceAttributes();\n SdkMeterProvider sdkMeterProvider = this.getDefaultSdkMeterProvider(resource, otelBackendUrl, callbackInterval, otelUsingHttp, 10);\n OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(sdkMeterProvider).build();\n initMeters(openTelemetry);\n registerMetrics();\n }\n\n private void initMeter(OpenTelemetry openTelemetry, String name) {\n Meter meter1 = openTelemetry.meterBuilder(INSTRUMENTATION_SCOPE_PREFIX + name).setInstrumentationVersion(\"1.0.0\").build();\n getMeters().put(name, meter1);\n }\n\n /* The purpose to overwrite this method is to comply with the \"hostmetrics\" receiver of\n * OpenTelemetry Contrib Collector.\n **/\n @Override\n public void initMeters(OpenTelemetry openTelemetry) {\n initMeter(openTelemetry, HostDcUtil.MeterName.CPU);\n initMeter(openTelemetry, HostDcUtil.MeterName.MEMORY);\n initMeter(openTelemetry, HostDcUtil.MeterName.NETWORK);\n initMeter(openTelemetry, HostDcUtil.MeterName.LOAD);\n initMeter(openTelemetry, HostDcUtil.MeterName.DISK);\n initMeter(openTelemetry, HostDcUtil.MeterName.FILESYSTEM);\n initMeter(openTelemetry, HostDcUtil.MeterName.PROCESSES);\n initMeter(openTelemetry, HostDcUtil.MeterName.PAGING);\n }\n\n\n @Override\n public void start() {\n exec.scheduleWithFixedDelay(this::collectData, 1, pollInterval, TimeUnit.SECONDS);\n }\n}" }, { "identifier": "HostDcUtil", "path": "host/src/main/java/com/instana/dc/host/HostDcUtil.java", "snippet": "public class HostDcUtil {\n private static final Logger logger = Logger.getLogger(HostDcUtil.class.getName());\n\n public static class MeterName{\n public static final String CPU = \"cpu\";\n public static final String MEMORY = \"memory\";\n public static final String NETWORK = \"network\";\n public static final String LOAD = \"load\";\n public static final String DISK = \"disk\";\n public static final String FILESYSTEM = \"filesystem\";\n public static final String PROCESSES = \"processes\";\n public static final String PAGING = \"paging\";\n }\n\n /* Configurations for Metrics:\n */\n public static final String UNIT_S = \"s\";\n public static final String UNIT_BY = \"By\";\n public static final String UNIT_1 = \"1\";\n\n public static final String SYSTEM_CPU_TIME_NAME = \"system.cpu.time\";\n public static final String SYSTEM_CPU_TIME_DESC = \"Seconds each logical CPU spent on each mode\";\n public static final String SYSTEM_CPU_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_MEMORY_USAGE_NAME = \"system.memory.usage\";\n public static final String SYSTEM_MEMORY_USAGE_DESC = \"Bytes of memory in use\";\n public static final String SYSTEM_MEMORY_USAGE_UNIT = UNIT_BY;\n\n public static final String SYSTEM_CPU_LOAD1_NAME = \"system.cpu.load_average.1m\";\n public static final String SYSTEM_CPU_LOAD1_DESC = \"Average CPU Load over 1 minutes\";\n public static final String SYSTEM_CPU_LOAD1_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD5_NAME = \"system.cpu.load_average.5m\";\n public static final String SYSTEM_CPU_LOAD5_DESC = \"Average CPU Load over 5 minutes\";\n public static final String SYSTEM_CPU_LOAD5_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD15_NAME = \"system.cpu.load_average.15m\";\n public static final String SYSTEM_CPU_LOAD15_DESC = \"Average CPU Load over 15 minutes\";\n public static final String SYSTEM_CPU_LOAD15_UNIT = UNIT_1;\n\n public static final String SYSTEM_NETWORK_CONNECTIONS_NAME = \"system.network.connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_DESC = \"The number of connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_UNIT = \"{connections}\";\n\n public static final String SYSTEM_NETWORK_DROPPED_NAME = \"system.network.dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_DESC = \"The number of packets dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_UNIT = \"{packets}\";\n\n public static final String SYSTEM_NETWORK_ERRORS_NAME = \"system.network.errors\";\n public static final String SYSTEM_NETWORK_ERRORS_DESC = \"The number of errors encountered\";\n public static final String SYSTEM_NETWORK_ERRORS_UNIT = \"{errors}\";\n\n public static final String SYSTEM_NETWORK_IO_NAME = \"system.network.io\";\n public static final String SYSTEM_NETWORK_IO_DESC = \"The number of bytes transmitted and received\";\n public static final String SYSTEM_NETWORK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_NETWORK_PACKETS_NAME = \"system.network.packets\";\n public static final String SYSTEM_NETWORK_PACKETS_DESC = \"The number of packets transferred\";\n public static final String SYSTEM_NETWORK_PACKETS_UNIT = \"{packets}\";\n\n\n public static final String SYSTEM_DISK_IO_NAME = \"system.disk.io\";\n public static final String SYSTEM_DISK_IO_DESC = \"Disk bytes transferred\";\n public static final String SYSTEM_DISK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_DISK_IO_TIME_NAME = \"system.disk.io_time\";\n public static final String SYSTEM_DISK_IO_TIME_DESC = \"Time disk spent activated. On Windows, this is calculated as the inverse of disk idle time\";\n public static final String SYSTEM_DISK_IO_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_MERGED_NAME = \"system.disk.merged\";\n public static final String SYSTEM_DISK_MERGED_DESC = \"The number of disk reads/writes merged into single physical disk access operations\";\n public static final String SYSTEM_DISK_MERGED_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_OPERATION_TIME_NAME = \"system.disk.operation_time\";\n public static final String SYSTEM_DISK_OPERATION_TIME_DESC = \"Time spent in disk operations\";\n public static final String SYSTEM_DISK_OPERATION_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_OPERATIONS_NAME = \"system.disk.operations\";\n public static final String SYSTEM_DISK_OPERATIONS_DESC = \"Disk operations count\";\n public static final String SYSTEM_DISK_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_NAME = \"system.disk.pending_operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_DESC = \"The queue size of pending I/O operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_NAME = \"system.disk.weighted_io_time\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_DESC = \"Time disk spent activated multiplied by the queue length\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_UNIT = UNIT_S;\n\n\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_NAME = \"system.filesystem.inodes.usage\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_DESC = \"FileSystem inodes used\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_UNIT = \"{inodes}\";\n\n public static final String SYSTEM_FILESYSTEM_USAGE_NAME = \"system.filesystem.usage\";\n public static final String SYSTEM_FILESYSTEM_USAGE_DESC = \"Filesystem bytes used\";\n public static final String SYSTEM_FILESYSTEM_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PAGING_FAULTS_NAME = \"system.paging.faults\";\n public static final String SYSTEM_PAGING_FAULTS_DESC = \"The number of page faults\";\n public static final String SYSTEM_PAGING_FAULTS_UNIT = \"{faults}\";\n\n public static final String SYSTEM_PAGING_OPERATIONS_NAME = \"system.paging.operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_DESC = \"The number of paging operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_PAGING_USAGE_NAME = \"system.paging.usage\";\n public static final String SYSTEM_PAGING_USAGE_DESC = \"Swap (unix) or pagefile (windows) usage\";\n public static final String SYSTEM_PAGING_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PROCESSES_COUNT_NAME = \"system.processes.count\";\n public static final String SYSTEM_PROCESSES_COUNT_DESC = \"Total number of processes in each state\";\n public static final String SYSTEM_PROCESSES_COUNT_UNIT = \"{processes}\";\n\n public static final String SYSTEM_PROCESSES_CREATED_NAME = \"system.processes.created\";\n public static final String SYSTEM_PROCESSES_CREATED_DESC = \"Total number of created processes\";\n public static final String SYSTEM_PROCESSES_CREATED_UNIT = \"{processes}\";\n\n\n public static String readFileText(String filePath) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n int n = is.available();\n byte[] ba = new byte[n];\n is.read(ba);\n return new String(ba).trim();\n }\n }\n\n public static String readFileText(String filePath, int max) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n byte[] ba = new byte[max];\n int n = is.read(ba);\n return new String(ba, 0, n).trim();\n }\n }\n\n public static String readFileTextLine(String filePath) throws IOException {\n try (Reader rd = new FileReader(filePath)) {\n BufferedReader reader = new BufferedReader(rd);\n String line = reader.readLine();\n reader.close();\n return line;\n }\n }\n}" }, { "identifier": "mergeResourceAttributesFromEnv", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet": "public static Resource mergeResourceAttributesFromEnv(Resource resource) {\n String resAttrs = System.getenv(OTEL_RESOURCE_ATTRIBUTES);\n if (resAttrs != null) {\n for (String resAttr : resAttrs.split(\",\")) {\n String[] kv = resAttr.split(\"=\");\n if (kv.length != 2)\n continue;\n String key = kv[0].trim();\n String value = kv[1].trim();\n resource = resource.merge(Resource.create(Attributes.of(AttributeKey.stringKey(key), value)));\n }\n }\n return resource;\n}" }, { "identifier": "HostDcUtil", "path": "host/src/main/java/com/instana/dc/host/HostDcUtil.java", "snippet": "public class HostDcUtil {\n private static final Logger logger = Logger.getLogger(HostDcUtil.class.getName());\n\n public static class MeterName{\n public static final String CPU = \"cpu\";\n public static final String MEMORY = \"memory\";\n public static final String NETWORK = \"network\";\n public static final String LOAD = \"load\";\n public static final String DISK = \"disk\";\n public static final String FILESYSTEM = \"filesystem\";\n public static final String PROCESSES = \"processes\";\n public static final String PAGING = \"paging\";\n }\n\n /* Configurations for Metrics:\n */\n public static final String UNIT_S = \"s\";\n public static final String UNIT_BY = \"By\";\n public static final String UNIT_1 = \"1\";\n\n public static final String SYSTEM_CPU_TIME_NAME = \"system.cpu.time\";\n public static final String SYSTEM_CPU_TIME_DESC = \"Seconds each logical CPU spent on each mode\";\n public static final String SYSTEM_CPU_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_MEMORY_USAGE_NAME = \"system.memory.usage\";\n public static final String SYSTEM_MEMORY_USAGE_DESC = \"Bytes of memory in use\";\n public static final String SYSTEM_MEMORY_USAGE_UNIT = UNIT_BY;\n\n public static final String SYSTEM_CPU_LOAD1_NAME = \"system.cpu.load_average.1m\";\n public static final String SYSTEM_CPU_LOAD1_DESC = \"Average CPU Load over 1 minutes\";\n public static final String SYSTEM_CPU_LOAD1_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD5_NAME = \"system.cpu.load_average.5m\";\n public static final String SYSTEM_CPU_LOAD5_DESC = \"Average CPU Load over 5 minutes\";\n public static final String SYSTEM_CPU_LOAD5_UNIT = UNIT_1;\n\n public static final String SYSTEM_CPU_LOAD15_NAME = \"system.cpu.load_average.15m\";\n public static final String SYSTEM_CPU_LOAD15_DESC = \"Average CPU Load over 15 minutes\";\n public static final String SYSTEM_CPU_LOAD15_UNIT = UNIT_1;\n\n public static final String SYSTEM_NETWORK_CONNECTIONS_NAME = \"system.network.connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_DESC = \"The number of connections\";\n public static final String SYSTEM_NETWORK_CONNECTIONS_UNIT = \"{connections}\";\n\n public static final String SYSTEM_NETWORK_DROPPED_NAME = \"system.network.dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_DESC = \"The number of packets dropped\";\n public static final String SYSTEM_NETWORK_DROPPED_UNIT = \"{packets}\";\n\n public static final String SYSTEM_NETWORK_ERRORS_NAME = \"system.network.errors\";\n public static final String SYSTEM_NETWORK_ERRORS_DESC = \"The number of errors encountered\";\n public static final String SYSTEM_NETWORK_ERRORS_UNIT = \"{errors}\";\n\n public static final String SYSTEM_NETWORK_IO_NAME = \"system.network.io\";\n public static final String SYSTEM_NETWORK_IO_DESC = \"The number of bytes transmitted and received\";\n public static final String SYSTEM_NETWORK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_NETWORK_PACKETS_NAME = \"system.network.packets\";\n public static final String SYSTEM_NETWORK_PACKETS_DESC = \"The number of packets transferred\";\n public static final String SYSTEM_NETWORK_PACKETS_UNIT = \"{packets}\";\n\n\n public static final String SYSTEM_DISK_IO_NAME = \"system.disk.io\";\n public static final String SYSTEM_DISK_IO_DESC = \"Disk bytes transferred\";\n public static final String SYSTEM_DISK_IO_UNIT = UNIT_BY;\n\n public static final String SYSTEM_DISK_IO_TIME_NAME = \"system.disk.io_time\";\n public static final String SYSTEM_DISK_IO_TIME_DESC = \"Time disk spent activated. On Windows, this is calculated as the inverse of disk idle time\";\n public static final String SYSTEM_DISK_IO_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_MERGED_NAME = \"system.disk.merged\";\n public static final String SYSTEM_DISK_MERGED_DESC = \"The number of disk reads/writes merged into single physical disk access operations\";\n public static final String SYSTEM_DISK_MERGED_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_OPERATION_TIME_NAME = \"system.disk.operation_time\";\n public static final String SYSTEM_DISK_OPERATION_TIME_DESC = \"Time spent in disk operations\";\n public static final String SYSTEM_DISK_OPERATION_TIME_UNIT = UNIT_S;\n\n public static final String SYSTEM_DISK_OPERATIONS_NAME = \"system.disk.operations\";\n public static final String SYSTEM_DISK_OPERATIONS_DESC = \"Disk operations count\";\n public static final String SYSTEM_DISK_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_NAME = \"system.disk.pending_operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_DESC = \"The queue size of pending I/O operations\";\n public static final String SYSTEM_DISK_PENDING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_NAME = \"system.disk.weighted_io_time\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_DESC = \"Time disk spent activated multiplied by the queue length\";\n public static final String SYSTEM_DISK_WEIGHTED_IO_TIME_UNIT = UNIT_S;\n\n\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_NAME = \"system.filesystem.inodes.usage\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_DESC = \"FileSystem inodes used\";\n public static final String SYSTEM_FILESYSTEM_INODES_USAGE_UNIT = \"{inodes}\";\n\n public static final String SYSTEM_FILESYSTEM_USAGE_NAME = \"system.filesystem.usage\";\n public static final String SYSTEM_FILESYSTEM_USAGE_DESC = \"Filesystem bytes used\";\n public static final String SYSTEM_FILESYSTEM_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PAGING_FAULTS_NAME = \"system.paging.faults\";\n public static final String SYSTEM_PAGING_FAULTS_DESC = \"The number of page faults\";\n public static final String SYSTEM_PAGING_FAULTS_UNIT = \"{faults}\";\n\n public static final String SYSTEM_PAGING_OPERATIONS_NAME = \"system.paging.operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_DESC = \"The number of paging operations\";\n public static final String SYSTEM_PAGING_OPERATIONS_UNIT = \"{operations}\";\n\n public static final String SYSTEM_PAGING_USAGE_NAME = \"system.paging.usage\";\n public static final String SYSTEM_PAGING_USAGE_DESC = \"Swap (unix) or pagefile (windows) usage\";\n public static final String SYSTEM_PAGING_USAGE_UNIT = UNIT_BY;\n\n\n public static final String SYSTEM_PROCESSES_COUNT_NAME = \"system.processes.count\";\n public static final String SYSTEM_PROCESSES_COUNT_DESC = \"Total number of processes in each state\";\n public static final String SYSTEM_PROCESSES_COUNT_UNIT = \"{processes}\";\n\n public static final String SYSTEM_PROCESSES_CREATED_NAME = \"system.processes.created\";\n public static final String SYSTEM_PROCESSES_CREATED_DESC = \"Total number of created processes\";\n public static final String SYSTEM_PROCESSES_CREATED_UNIT = \"{processes}\";\n\n\n public static String readFileText(String filePath) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n int n = is.available();\n byte[] ba = new byte[n];\n is.read(ba);\n return new String(ba).trim();\n }\n }\n\n public static String readFileText(String filePath, int max) throws IOException {\n try (InputStream is = new FileInputStream(filePath)) {\n byte[] ba = new byte[max];\n int n = is.read(ba);\n return new String(ba, 0, n).trim();\n }\n }\n\n public static String readFileTextLine(String filePath) throws IOException {\n try (Reader rd = new FileReader(filePath)) {\n BufferedReader reader = new BufferedReader(rd);\n String line = reader.readLine();\n reader.close();\n return line;\n }\n }\n}" } ]
import com.instana.dc.host.AbstractHostDc; import com.instana.dc.host.HostDcUtil; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.ResourceAttributes; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.logging.Logger; import static com.instana.dc.DcUtil.mergeResourceAttributesFromEnv; import static com.instana.dc.host.HostDcUtil.*;
4,739
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class SimpHostDc extends AbstractHostDc { private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName()); public SimpHostDc(Map<String, String> properties, String hostSystem) { super(properties, hostSystem); } public String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "UnknownName"; } } public String getHostId() { try {
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class SimpHostDc extends AbstractHostDc { private static final Logger logger = Logger.getLogger(SimpHostDc.class.getName()); public SimpHostDc(Map<String, String> properties, String hostSystem) { super(properties, hostSystem); } public String getHostName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "UnknownName"; } } public String getHostId() { try {
return HostDcUtil.readFileText("/etc/machine-id");
3
2023-10-23 01:16:38+00:00
8k
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 getPageAlign();\n\n /**\n * trace memory read\n */\n TraceHook traceRead();\n TraceHook traceRead(long begin, long end);\n TraceHook traceRead(long begin, long end, TraceReadListener listener);\n\n /**\n * trace memory write\n */\n TraceHook traceWrite();\n TraceHook traceWrite(long begin, long end);\n TraceHook traceWrite(long begin, long end, TraceWriteListener listener);\n\n void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener);\n\n /**\n * trace instruction\n * note: low performance\n */\n TraceHook traceCode();\n TraceHook traceCode(long begin, long end);\n TraceHook traceCode(long begin, long end, TraceCodeListener listener);\n\n Number eFunc(long begin, Number... arguments);\n\n Number eEntry(long begin, long sp);\n\n /**\n * emulate signal handler\n * @param sig signal number\n * @return <code>true</code> means called handler function.\n */\n boolean emulateSignal(int sig);\n\n /**\n * 是否正在运行\n */\n boolean isRunning();\n\n /**\n * show all registers\n */\n void showRegs();\n\n /**\n * show registers\n */\n void showRegs(int... regs);\n\n Module loadLibrary(File libraryFile);\n Module loadLibrary(File libraryFile, boolean forceCallInit);\n\n Memory getMemory();\n\n Backend getBackend();\n\n int getPid();\n\n String getProcessName();\n\n Debugger attach();\n\n Debugger attach(DebuggerType type);\n\n FileSystem<T> getFileSystem();\n\n SvcMemory getSvcMemory();\n\n SyscallHandler<T> getSyscallHandler();\n\n Family getFamily();\n LibraryFile createURLibraryFile(URL url, String libName);\n\n Dlfcn getDlfcn();\n\n /**\n * @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.\n */\n void setTimeout(long timeout);\n\n <V extends RegisterContext> V getContext();\n\n Unwinder getUnwinder();\n\n void pushContext(int off);\n int popContext();\n\n ThreadDispatcher getThreadDispatcher();\n\n long getReturnAddress();\n\n void set(String key, Object value);\n <V> V get(String key);\n\n}" }, { "identifier": "Backend", "path": "unidbg-api/src/main/java/com/github/unidbg/arm/backend/Backend.java", "snippet": "public interface Backend {\n\n void onInitialize();\n\n void switchUserMode();\n void enableVFP();\n\n Number reg_read(int regId)throws BackendException;\n\n byte[] reg_read_vector(int regId) throws BackendException;\n void reg_write_vector(int regId, byte[] vector) throws BackendException;\n\n void reg_write(int regId, Number value) throws BackendException;\n\n byte[] mem_read(long address, long size) throws BackendException;\n\n void mem_write(long address, byte[] bytes) throws BackendException;\n\n void mem_map(long address, long size, int perms) throws BackendException;\n\n void mem_protect(long address, long size, int perms) throws BackendException;\n\n void mem_unmap(long address, long size) throws BackendException;\n\n BreakPoint addBreakPoint(long address, BreakPointCallback callback, boolean thumb);\n boolean removeBreakPoint(long address);\n void setSingleStep(int singleStep);\n void setFastDebug(boolean fastDebug);\n\n void hook_add_new(CodeHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void debugger_add(DebugHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void hook_add_new(ReadHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void hook_add_new(WriteHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void hook_add_new(EventMemHook callback, int type, Object user_data) throws BackendException;\n\n void hook_add_new(InterruptHook callback, Object user_data) throws BackendException;\n\n void hook_add_new(BlockHook callback, long begin, long end, Object user_data) throws BackendException;\n\n void emu_start(long begin, long until, long timeout, long count) throws BackendException;\n\n void emu_stop() throws BackendException;\n\n void destroy() throws BackendException;\n\n void context_restore(long context);\n void context_save(long context);\n long context_alloc();\n void context_free(long context);\n\n int getPageSize();\n\n void registerEmuCountHook(long emu_count);\n\n}" }, { "identifier": "BaseDarwinFileIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/file/ios/BaseDarwinFileIO.java", "snippet": "public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO {\n\n private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class);\n\n public static File createAttrFile(File dest) {\n if (!dest.exists()) {\n throw new IllegalStateException(\"dest=\" + dest);\n }\n\n File file;\n if (dest.isDirectory()) {\n file = new File(dest, UnidbgFileFilter.UNIDBG_PREFIX + \".json\");\n } else {\n file = new File(dest.getParentFile(), UnidbgFileFilter.UNIDBG_PREFIX + \"_\" + dest.getName() + \".json\");\n }\n return file;\n }\n\n public BaseDarwinFileIO(int oflags) {\n super(oflags);\n }\n\n public int fstat(Emulator<?> emulator, StatStructure stat) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n private int protectionClass;\n\n @Override\n public int fcntl(Emulator<?> emulator, int cmd, long arg) {\n if (cmd == F_NOCACHE) {\n return 0;\n }\n if (cmd == F_SETLK) {\n return 0;\n }\n if (cmd == F_SETLKW) {\n return 0;\n }\n if (cmd == F_SETPROTECTIONCLASS) {\n protectionClass = (int) arg;\n return 0;\n }\n if (cmd == F_GETPROTECTIONCLASS) {\n return protectionClass;\n }\n if(cmd == F_SINGLE_WRITER) {\n return 0;\n }\n if (cmd == F_PREALLOCATE) {\n return 0;\n }\n\n return super.fcntl(emulator, cmd, arg);\n }\n\n public int fstatfs(StatFS statFS) {\n throw new UnsupportedOperationException(getClass().getName() + \" path=\" + getPath());\n }\n\n @Override\n public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {\n if (attrList.bitmapcount != ATTR_BIT_MAP_COUNT) {\n throw new UnsupportedOperationException(\"bitmapcount=\" + attrList.bitmapcount);\n }\n AttributeSet attributeSet = attrList.attributeSet;\n Pointer pointer = attrBuf.share(4);\n List<UnidbgStructure> list = new ArrayList<>();\n List<AttrReference> attrReferenceList = new ArrayList<>();\n AttributeSet returnedAttributeSet = null;\n if ((attributeSet.commonattr & ATTR_CMN_RETURNED_ATTRS) != 0) {\n returnedAttributeSet = new AttributeSet(pointer);\n pointer = pointer.share(returnedAttributeSet.size());\n list.add(returnedAttributeSet);\n attributeSet.commonattr &= ~ATTR_CMN_RETURNED_ATTRS;\n }\n if((attributeSet.commonattr & ATTR_CMN_NAME) != 0) {\n String name = FilenameUtils.getName(getPath());\n byte[] bytes = name.getBytes(StandardCharsets.UTF_8);\n AttrReference attrReference = new AttrReference(pointer, bytes);\n attrReferenceList.add(attrReference);\n pointer = pointer.share(attrReference.size());\n list.add(attrReference);\n attributeSet.commonattr &= ~ATTR_CMN_NAME;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_NAME;\n }\n }\n if((attributeSet.commonattr & ATTR_CMN_DEVID) != 0) {\n Dev dev = new Dev(pointer);\n dev.dev = 1;\n pointer = pointer.share(dev.size());\n list.add(dev);\n attributeSet.commonattr &= ~ATTR_CMN_DEVID;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_DEVID;\n }\n }\n if((attributeSet.commonattr & ATTR_CMN_FSID) != 0) {\n Fsid fsid = new Fsid(pointer);\n fsid.val[0] = 0;\n fsid.val[1] = 0;\n pointer = pointer.share(fsid.size());\n list.add(fsid);\n attributeSet.commonattr &= ~ATTR_CMN_FSID;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_FSID;\n }\n }\n if((attributeSet.commonattr & ATTR_CMN_OBJTYPE) != 0) {\n ObjType objType = new ObjType(pointer);\n objType.type = this instanceof DirectoryFileIO ? vtype.VDIR.ordinal() : vtype.VREG.ordinal();\n pointer = pointer.share(objType.size());\n list.add(objType);\n attributeSet.commonattr &= ~ATTR_CMN_OBJTYPE;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_OBJTYPE;\n }\n }\n if((attributeSet.commonattr & ATTR_CMN_OBJID) != 0) {\n ObjId objId = new ObjId(pointer);\n objId.fid_objno = 0;\n objId.fid_generation = 0;\n pointer = pointer.share(objId.size());\n list.add(objId);\n attributeSet.commonattr &= ~ATTR_CMN_OBJID;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_OBJID;\n }\n }\n if((attributeSet.commonattr & ATTR_CMN_CRTIME) != 0) {\n TimeSpec32 timeSpec = new TimeSpec32(pointer);\n pointer = pointer.share(timeSpec.size());\n list.add(timeSpec);\n attributeSet.commonattr &= ~ATTR_CMN_CRTIME;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_CRTIME;\n }\n }\n if ((attributeSet.commonattr & ATTR_CMN_FNDRINFO) != 0) {\n FinderInfo finderInfo = new FinderInfo(pointer);\n pointer = pointer.share(finderInfo.size());\n list.add(finderInfo);\n attributeSet.commonattr &= ~ATTR_CMN_FNDRINFO;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_FNDRINFO;\n }\n }\n if ((attributeSet.commonattr & ATTR_CMN_USERACCESS) != 0) {\n UserAccess userAccess = new UserAccess(pointer);\n userAccess.mode = X_OK | W_OK | R_OK;\n// pointer = pointer.share(userAccess.size());\n list.add(userAccess);\n attributeSet.commonattr &= ~ATTR_CMN_USERACCESS;\n if (returnedAttributeSet != null) {\n returnedAttributeSet.commonattr |= ATTR_CMN_USERACCESS;\n }\n }\n if (attributeSet.commonattr != 0 || attributeSet.volattr != 0 ||\n attributeSet.dirattr != 0 || attributeSet.fileattr != 0 ||\n attributeSet.forkattr != 0) {\n if (returnedAttributeSet == null) {\n return -1;\n }\n }\n int len = 0;\n for (UnidbgStructure structure : list) {\n int size = structure.size();\n len += size;\n structure.pack();\n\n for (AttrReference attrReference : attrReferenceList) {\n attrReference.check(structure, size);\n }\n }\n attrBuf.setInt(0, len + 4);\n\n for (AttrReference attrReference : attrReferenceList) {\n pointer = attrBuf.share(attrReference.attr_dataoffset + 4);\n attrReference.writeAttr(pointer);\n }\n\n return 0;\n }\n\n @Override\n public int setattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) {\n if (attrList.bitmapcount != ATTR_BIT_MAP_COUNT) {\n throw new UnsupportedOperationException(\"bitmapcount=\" + attrList.bitmapcount);\n }\n AttributeSet attributeSet = attrList.attributeSet;\n Pointer pointer = attrBuf.share(4);\n if((attributeSet.commonattr & ATTR_CMN_CRTIME) != 0) {\n TimeSpec32 timeSpec = new TimeSpec32(pointer);\n pointer = pointer.share(timeSpec.size());\n if (log.isDebugEnabled()) {\n log.debug(\"setattrlist timeSpec=\" + timeSpec + \", pointer=\" + pointer);\n }\n attributeSet.commonattr &= ~ATTR_CMN_CRTIME;\n }\n if((attributeSet.commonattr & ATTR_CMN_MODTIME) != 0) {\n TimeSpec32 timeSpec = new TimeSpec32(pointer);\n pointer = pointer.share(timeSpec.size());\n if (log.isDebugEnabled()) {\n log.debug(\"setattrlist timeSpec=\" + timeSpec + \", pointer=\" + pointer);\n }\n attributeSet.commonattr &= ~ATTR_CMN_MODTIME;\n }\n if ((attributeSet.commonattr & ATTR_CMN_FNDRINFO) != 0) {\n FinderInfo finderInfo = new FinderInfo(pointer);\n pointer = pointer.share(finderInfo.size());\n if (log.isDebugEnabled()) {\n log.debug(\"setattrlist finderInfo=\" + finderInfo + \", pointer=\" + pointer);\n }\n attributeSet.commonattr &= ~ATTR_CMN_FNDRINFO;\n }\n if (attributeSet.commonattr != 0 || attributeSet.volattr != 0 ||\n attributeSet.dirattr != 0 || attributeSet.fileattr != 0 ||\n attributeSet.forkattr != 0) {\n return -1;\n }\n return 0;\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int listxattr(Pointer namebuf, int size, int options) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int removexattr(String name) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int setxattr(String name, byte[] data) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int getxattr(Emulator<?> emulator, String name, Pointer value, int size) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int chown(int uid, int gid) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int chmod(int mode) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n @Override\n public int chflags(int flags) {\n throw new UnsupportedOperationException(getClass().getName());\n }\n\n protected final int chflags(File dest, int flags) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n if (attr == null) {\n attr = new DarwinFileAttr();\n }\n attr.flags = flags;\n File file = createAttrFile(dest);\n FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8);\n return 0;\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n protected final int chmod(File dest, int mode) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n if (attr == null) {\n attr = new DarwinFileAttr();\n }\n attr.mode = mode;\n File file = createAttrFile(dest);\n FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8);\n return 0;\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n protected final int chown(File dest, int uid, int gid) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n if (attr == null) {\n attr = new DarwinFileAttr();\n }\n attr.uid = uid;\n attr.gid = gid;\n File file = createAttrFile(dest);\n FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8);\n return 0;\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n protected final DarwinFileAttr loadAttr(File dest) throws IOException {\n File file = createAttrFile(dest);\n if (file.exists()) {\n return JSON.parseObject(FileUtils.readFileToString(file, StandardCharsets.UTF_8), DarwinFileAttr.class);\n } else {\n return null;\n }\n }\n\n protected final int listxattr(File dest, Pointer namebuf, int size) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n if (attr == null || attr.xattr == null) {\n return 0;\n }\n int ret = 0;\n Pointer buffer = namebuf;\n for (String name : attr.xattr.keySet()) {\n byte[] data = name.getBytes(StandardCharsets.UTF_8);\n ret += (data.length + 1);\n\n if (buffer != null && ret <= size) {\n buffer.write(0, Arrays.copyOf(data, data.length + 1), 0, data.length + 1);\n buffer = buffer.share(data.length + 1);\n }\n }\n return ret;\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n protected final int getxattr(Emulator<?> emulator, File dest, String name, Pointer value, int size) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n byte[] data = attr == null || attr.xattr == null ? null : attr.xattr.get(name);\n if (data == null) {\n emulator.getMemory().setErrno(UnixEmulator.ENOATTR);\n return -1;\n }\n if (value == null) {\n return data.length;\n } else if (size >= data.length) {\n value.write(0, data, 0, data.length);\n return data.length;\n } else {\n value.write(0, data, 0, size);\n return size;\n }\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n protected final int setxattr(File dest, String name, byte[] data) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n if (attr == null) {\n attr = new DarwinFileAttr();\n }\n if (attr.xattr == null) {\n attr.xattr = new HashMap<>();\n }\n attr.xattr.put(name, data);\n File file = createAttrFile(dest);\n FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8);\n return 0;\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n protected final int removexattr(File dest, String name) {\n try {\n DarwinFileAttr attr = loadAttr(dest);\n if (attr == null) {\n attr = new DarwinFileAttr();\n }\n if (attr.xattr == null) {\n attr.xattr = new HashMap<>();\n }\n attr.xattr.remove(name);\n File file = createAttrFile(dest);\n FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8);\n return 0;\n } catch (IOException e) {\n throw new IllegalStateException(e);\n }\n }\n\n @Override\n protected void setFlags(long arg) {\n if ((IOConstants.O_APPEND & arg) != 0) {\n oflags |= IOConstants.O_APPEND;\n }\n if ((IOConstants.O_RDWR & arg) != 0) {\n oflags |= IOConstants.O_RDWR;\n }\n if ((IOConstants.O_NONBLOCK & arg) != 0) {\n oflags |= IOConstants.O_NONBLOCK;\n }\n }\n}" }, { "identifier": "StatStructure", "path": "unidbg-ios/src/main/java/com/github/unidbg/file/ios/StatStructure.java", "snippet": "public abstract class StatStructure extends UnidbgStructure {\n\n public StatStructure(Pointer p) {\n super(p);\n }\n\n public int st_dev; /* [XSI] ID of device containing file */\n public short st_mode; /* [XSI] Mode of file (see below) */\n public short st_nlink; /* [XSI] Number of hard links */\n public long st_ino; /* [XSI] File serial number */\n\n public int st_uid; /* [XSI] User ID of the file */\n public int st_gid; /* [XSI] Group ID of the file */\n public int st_rdev; /* [XSI] Device ID */\n\n public long st_size; /* [XSI] file size, in bytes */\n public long st_blocks; /* [XSI] blocks allocated for file */\n public int st_blksize; /* [XSI] optimal blocksize for I/O */\n\n public int st_flags; /* user defined flags for file */\n public int st_gen; /* file generation number */\n\n public void setSize(long size) {\n this.st_size = size;\n }\n\n public void setBlockCount(long count) {\n this.st_blocks = count;\n }\n\n public final void setLastModification(long lastModified) {\n long tv_sec = lastModified / 1000L;\n long tv_nsec = (lastModified % 1000) * 1000000L;\n setSt_atimespec(tv_sec, tv_nsec);\n setSt_mtimespec(tv_sec, tv_nsec);\n setSt_ctimespec(tv_sec, tv_nsec);\n setSt_birthtimespec(tv_sec, tv_nsec);\n }\n\n public abstract void setSt_atimespec(long tv_sec, long tv_nsec);\n\n public abstract void setSt_mtimespec(long tv_sec, long tv_nsec);\n\n public abstract void setSt_ctimespec(long tv_sec, long tv_nsec);\n\n public abstract void setSt_birthtimespec(long tv_sec, long tv_nsec);\n\n}" }, { "identifier": "StatFS", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/StatFS.java", "snippet": "public class StatFS extends UnidbgStructure {\n\n private static final int MFSTYPENAMELEN = 16; /* length of fs type name including null */\n private static final int MAXPATHLEN = 1024; /* max bytes in pathname */\n\n public StatFS(byte[] data) {\n super(data);\n }\n\n public StatFS(Pointer p) {\n super(p);\n }\n\n public int f_bsize; /* fundamental file system block size */\n public int f_iosize; /* optimal transfer block size */\n public long f_blocks; /* total data blocks in file system */\n public long f_bfree; /* free blocks in fs */\n public long f_bavail; /* free blocks avail to non-superuser */\n public long f_files; /* total file nodes in file system */\n public long f_ffree; /* free file nodes in fs */\n\n public long f_fsid; /* file system id */\n public int f_owner; /* user that mounted the filesystem */\n public int f_type; /* type of filesystem */\n public int f_flags; /* copy of mount exported flags */\n public int f_fssubtype; /* fs sub-type (flavor) */\n\n public byte[] f_fstypename = new byte[MFSTYPENAMELEN]; /* fs type name */\n public byte[] f_mntonname = new byte[MAXPATHLEN]; /* directory on which mounted */\n public byte[] f_mntfromname = new byte[MAXPATHLEN]; /* mounted filesystem */\n public int[] f_reserved = new int[8]; /* For future use */\n\n public void setFsTypeName(String fsTypeName) {\n if (fsTypeName == null) {\n throw new NullPointerException();\n }\n byte[] data = fsTypeName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MFSTYPENAMELEN) {\n throw new IllegalStateException(\"Invalid MFSTYPENAMELEN: \" + MFSTYPENAMELEN);\n }\n f_fstypename = Arrays.copyOf(data, MFSTYPENAMELEN);\n }\n\n public void setMntOnName(String mntOnName) {\n if (mntOnName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntOnName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntonname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n public void setMntFromName(String mntFromName) {\n if (mntFromName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntFromName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntfromname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"f_bsize\", \"f_iosize\", \"f_blocks\", \"f_bfree\", \"f_bavail\", \"f_files\", \"f_ffree\", \"f_fsid\", \"f_owner\",\n \"f_type\", \"f_flags\", \"f_fssubtype\", \"f_fstypename\", \"f_mntonname\", \"f_mntfromname\", \"f_reserved\");\n }\n\n}" }, { "identifier": "IO", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/IO.java", "snippet": "@SuppressWarnings(\"unused\")\npublic interface IO {\n\n String STDIN = \"stdin\";\n int FD_STDIN = 0;\n\n String STDOUT = \"stdout\";\n int FD_STDOUT = 1;\n\n String STDERR = \"stderr\";\n int FD_STDERR = 2;\n\n int S_IFREG = 0x8000; // regular file\n int S_IFDIR = 0x4000; // directory\n int S_IFCHR = 0x2000; // character device\n int S_IFLNK = 0xa000; // symbolic link\n int S_IFSOCK = 0xc000; // socket\n\n int AT_FDCWD = -100;\n\n}" } ]
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,158
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
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) {
0
2023-10-17 06:13:28+00:00
8k
EyeOfDarkness/FlameOut
src/flame/effects/Severation.java
[ { "identifier": "Utils", "path": "src/flame/Utils.java", "snippet": "public class Utils{\n public static Rect r = new Rect(), r2 = new Rect();\n static Vec2 v2 = new Vec2(), v3 = new Vec2(), v4 = new Vec2();\n static BasicPool<Hit> hpool = new BasicPool<>(Hit::new);\n static Seq<Hit> hseq = new Seq<>();\n static float ll = 0f;\n\n public static Vec2 v = new Vec2(), vv = new Vec2();\n public static Rand rand = new Rand(), rand2 = new Rand();\n\n public static float biasSlope(float fin, float bias){\n return (fin < bias ? (fin / bias) : 1f - (fin - bias) / (1f - bias));\n }\n\n public static float hitLaser(Team team, float width, float x1, float y1, float x2, float y2, Boolf<Healthc> within, Boolf<Healthc> stop, LineHitHandler<Healthc> cons){\n hseq.removeAll(h -> {\n hpool.free(h);\n return true;\n });\n ll = Mathf.dst(x1, y1, x2, y2);\n /*\n for(QuadTree<QuadTreeObject> tree : trees){\n //\n intersectLine(tree, width, x1, y1, x2, y2, (a, x, y) -> {\n Teamc t = (Teamc)a;\n if(within != null && !within.get(t)) return;\n Hit<Teamc> h = hpool.newObject();\n h.entity = t;\n h.x = x;\n h.y = y;\n hseq.add(h);\n });\n }\n */\n for(TeamData data : Vars.state.teams.present){\n if(data.team != team){\n if(data.unitTree != null){\n intersectLine(data.unitTree, width, x1, y1, x2, y2, (t, x, y) -> {\n if(within != null && !within.get(t)) return;\n Hit h = hpool.newObject();\n h.entity = t;\n h.x = x;\n h.y = y;\n hseq.add(h);\n });\n }\n if(data.buildingTree != null){\n intersectLine(data.buildingTree, width, x1, y1, x2, y2, (t, x, y) -> {\n if(within != null && !within.get(t)) return;\n Hit h = hpool.newObject();\n h.entity = t;\n h.x = x;\n h.y = y;\n hseq.add(h);\n });\n }\n }\n }\n hseq.sort(a -> a.entity.dst2(x1, y1));\n for(Hit hit : hseq){\n Healthc t = hit.entity;\n\n //cons.get(hit);\n cons.get(t, hit.x, hit.y);\n if(stop.get(t)){\n ll = Mathf.dst(x1, y1, hit.x, hit.y) - (t instanceof Sized s ? s.hitSize() / 4f : 0f);\n break;\n }\n }\n return ll;\n }\n\n public static <T extends QuadTreeObject> void intersectLine(QuadTree<T> tree, float width, float x1, float y1, float x2, float y2, LineHitHandler<T> cons){\n //intersectLine(tree, width, x1, y1, x2, y2, cons, 12);\n r.set(tree.bounds).grow(width);\n if(Intersector.intersectSegmentRectangle(x1, y1, x2, y2, r)){\n //\n for(T t : tree.objects){\n //cons.get(t);\n t.hitbox(r2);\n //float size = Math.max(r2.width, r2.height);\n r2.grow(width);\n /*\n Vec2 v = Geometry.raycastRect(x1, y1, x2, y2, r2);\n if(v != null){\n float size = Math.max(r2.width, r2.height);\n float mx = r2.x + r2.width / 2, my = r2.y + r2.height / 2;\n float scl = (size - width) / size;\n v.sub(mx, my).scl(scl).add(mx, my);\n\n cons.get(t, v.x, v.y);\n }\n */\n float cx = r2.x + r2.width / 2f, cy = r2.y + r2.height / 2f;\n float cr = Math.max(r2.width, r2.height);\n\n Vec2 v = intersectCircle(x1, y1, x2, y2, cx, cy, cr / 2f);\n if(v != null){\n float scl = (cr - width) / cr;\n v.sub(cx, cy).scl(scl).add(cx, cy);\n\n cons.get(t, v.x, v.y);\n }\n }\n\n if(!tree.leaf){\n intersectLine(tree.botLeft, width, x1, y1, x2, y2, cons);\n intersectLine(tree.botRight, width, x1, y1, x2, y2, cons);\n intersectLine(tree.topLeft, width, x1, y1, x2, y2, cons);\n intersectLine(tree.topRight, width, x1, y1, x2, y2, cons);\n }\n }\n }\n\n public static <T extends QuadTreeObject> void scanCone(QuadTree<T> tree, float x, float y, float rotation, float length, float spread, Cons<T> cons){\n scanCone(tree, x, y, rotation, length, spread, cons, true, false);\n }\n public static <T extends QuadTreeObject> void scanCone(QuadTree<T> tree, float x, float y, float rotation, float length, float spread, boolean accurate, Cons<T> cons){\n scanCone(tree, x, y, rotation, length, spread, cons, true, accurate);\n }\n public static <T extends QuadTreeObject> void scanCone(QuadTree<T> tree, float x, float y, float rotation, float length, float spread, Cons<T> cons, boolean source, boolean accurate){\n //\n if(source){\n v2.trns(rotation - spread, length).add(x, y);\n v3.trns(rotation + spread, length).add(x, y);\n }\n //r.set(tree.bounds).grow(width);\n Rect r = tree.bounds;\n boolean valid = false;\n if(Intersector.intersectSegmentRectangle(x, y, v2.x, v2.y, r) || Intersector.intersectSegmentRectangle(x, y, v3.x, v3.y, r) || r.contains(x, y)){\n valid = true;\n }\n float lenSqr = length * length;\n if(!valid){\n for(int i = 0; i < 4; i++){\n float mx = (r.x + r.width * (i % 2)) - x;\n float my = (r.y + (i >= 2 ? r.height : 0f)) - y;\n\n float dst2 = Mathf.dst2(mx, my);\n if(dst2 < lenSqr && Angles.within(rotation, Angles.angle(mx, my), spread)){\n valid = true;\n break;\n }\n }\n }\n if(valid){\n for(T t : tree.objects){\n Rect rr = r2;\n t.hitbox(rr);\n\n float mx = (rr.x + rr.width / 2) - x;\n float my = (rr.y + rr.height / 2) - y;\n float size = (Math.max(rr.width, rr.height) / 2f);\n float bounds = size + length;\n float at = accurate ? Mathf.angle(Mathf.sqrt(mx * mx + my * my), size) : 0f;\n if(mx * mx + my * my < (bounds * bounds) && Angles.within(rotation, Angles.angle(mx, my), spread + at)){\n cons.get(t);\n }\n }\n if(!tree.leaf){\n scanCone(tree.botLeft, x, y, rotation, length, spread, cons, false, accurate);\n scanCone(tree.botRight, x, y, rotation, length, spread, cons, false, accurate);\n scanCone(tree.topLeft, x, y, rotation, length, spread, cons, false, accurate);\n scanCone(tree.topRight, x, y, rotation, length, spread, cons, false, accurate);\n }\n }\n }\n\n /** code taken from BadWrong_ on the gamemaker subreddit */\n static Vec2 intersectCircle(float x1, float y1, float x2, float y2, float cx, float cy, float cr){\n if(!Intersector.nearestSegmentPoint(x1, y1, x2, y2, cx, cy, v4).within(cx, cy, cr)) return null;\n \n cx = x1 - cx;\n cy = y1 - cy;\n\n float vx = x2 - x1,\n vy = y2 - y1,\n a = vx * vx + vy * vy,\n b = 2 * (vx * cx + vy * cy),\n c = cx * cx + cy * cy - cr * cr,\n det = b * b - 4 * a * c;\n\n if(a <= Mathf.FLOAT_ROUNDING_ERROR || det < 0){\n return null;\n }else if(det == 0f){\n float t = -b / (2 * a);\n float ix = x1 + t * vx;\n float iy = y1 + t * vy;\n\n return v4.set(ix, iy);\n }else{\n det = Mathf.sqrt(det);\n float t1 = (-b - det) / (2 * a);\n\n return v4.set(x1 + t1 * vx, y1 + t1 * vy);\n }\n }\n\n public static float angleDistSigned(float a, float b){\n a += 360f;\n a %= 360f;\n b += 360f;\n b %= 360f;\n float d = Math.abs(a - b) % 360f;\n int sign = (a - b >= 0f && a - b <= 180f) || (a - b <= -180f && a - b >= -360f) ? 1 : -1;\n return (d > 180f ? 360f - d : d) * sign;\n }\n\n public static class BasicPool<T> extends Pool<T>{\n Prov<T> prov;\n\n public BasicPool(Prov<T> f){\n prov = f;\n }\n\n @Override\n protected T newObject(){\n return prov.get();\n }\n }\n\n public static class Hit{\n Healthc entity;\n float x;\n float y;\n }\n\n public interface LineHitHandler<T>{\n void get(T t, float x, float y);\n }\n}" }, { "identifier": "RenderGroupEntity", "path": "src/flame/entities/RenderGroupEntity.java", "snippet": "public class RenderGroupEntity extends DrawEntity implements Poolable{\n float bounds = 0f;\n Seq<DrawnRegion> regions = new Seq<>();\n\n static RenderGroupEntity active;\n static float minX, minY, maxX, maxY;\n static float[] tmpVert = new float[4 * 6];\n static Pool<DrawnRegion> regionPool = new BasicPool<>(DrawnRegion::new);\n\n public static void capture(){\n if(active != null) return;\n\n minX = 9999999f;\n minY = 9999999f;\n maxX = -9999999f;\n maxY = -9999999f;\n\n active = Pools.obtain(RenderGroupEntity.class, RenderGroupEntity::new);\n }\n public static void end(){\n if(active == null || active.regions.isEmpty()){\n active = null;\n return;\n }\n\n active.x = (minX + maxX) / 2;\n active.y = (minY + maxY) / 2;\n\n active.bounds = Math.max(maxX - minX, maxY - minY) * 2f;\n\n active.add();\n active = null;\n }\n static void updateBounds(float x, float y){\n minX = Math.min(x, minX);\n minY = Math.min(y, minY);\n\n maxX = Math.max(x, maxX);\n maxY = Math.max(y, maxY);\n }\n\n public static DrawnRegion draw(Blending blending, float z, Texture texture, float[] verticies, int offset){\n DrawnRegion r = regionPool.obtain();\n r.blending = blending;\n r.z = z;\n r.setVerticies(texture, verticies, offset);\n\n if(active != null){\n active.regions.add(r);\n }\n return r;\n }\n public static DrawnRegion draw(Blending blending, float z, TextureRegion region, float x, float y, float originX, float originY, float width, float height, float rotation, float color){\n DrawnRegion r = regionPool.obtain();\n r.blending = blending;\n r.z = z;\n r.setRegion(region, x, y, originX, originY, width, height, rotation, color);\n\n if(active != null){\n active.regions.add(r);\n }\n\n return r;\n }\n\n @Override\n public void update(){\n regions.removeAll(r -> {\n r.update();\n if(r.time >= r.lifetime){\n regionPool.free(r);\n }\n return r.time >= r.lifetime;\n });\n if(regions.isEmpty()){\n remove();\n }\n }\n\n @Override\n public float clipSize(){\n return bounds;\n }\n\n @Override\n public void draw(){\n for(DrawnRegion r : regions){\n r.draw();\n }\n }\n\n @Override\n protected void removeGroup(){\n super.removeGroup();\n Groups.queueFree(this);\n }\n\n @Override\n public void reset(){\n bounds = 0f;\n regions.clear();\n }\n\n public static class DrawnRegion implements Poolable{\n public float[] data = new float[4 * 6];\n public float z;\n public Texture texture;\n public Blending blending = Blending.normal;\n\n public float time, lifetime;\n public float fadeCurveIn = 0f, fadeCurveOut = 1f;\n\n void update(){\n time += Time.delta;\n }\n\n public void setVerticies(Texture texture, float[] verticies, int offset){\n this.texture = texture;\n System.arraycopy(verticies, offset, data, 0, data.length);\n if(active != null){\n for(int i = 0; i < 24; i += 6){\n updateBounds(data[i], data[i + 1]);\n\n data[i + 5] = Color.clearFloatBits;\n }\n }\n }\n\n public void setRegion(TextureRegion region, float x, float y, float originX, float originY, float width, float height, float rotation, float color){\n float[] vertices = data;\n\n float mixColor = Color.clearFloatBits;\n\n float worldOriginX = x + originX;\n float worldOriginY = y + originY;\n float fx = -originX;\n float fy = -originY;\n float fx2 = width - originX;\n float fy2 = height - originY;\n\n float cos = Mathf.cosDeg(rotation);\n float sin = Mathf.sinDeg(rotation);\n\n float x1 = cos * fx - sin * fy + worldOriginX;\n float y1 = sin * fx + cos * fy + worldOriginY;\n float x2 = cos * fx - sin * fy2 + worldOriginX;\n float y2 = sin * fx + cos * fy2 + worldOriginY;\n float x3 = cos * fx2 - sin * fy2 + worldOriginX;\n float y3 = sin * fx2 + cos * fy2 + worldOriginY;\n float x4 = x1 + (x3 - x2);\n float y4 = y3 - (y2 - y1);\n\n float u = region.u;\n float v = region.v2;\n float u2 = region.u2;\n float v2 = region.v;\n\n texture = region.texture;\n\n if(active != null){\n updateBounds(x1, y1);\n updateBounds(x2, y2);\n updateBounds(x3, y3);\n updateBounds(x4, y4);\n }\n\n vertices[0] = x1;\n vertices[1] = y1;\n vertices[2] = color;\n vertices[3] = u;\n vertices[4] = v;\n vertices[5] = mixColor;\n\n vertices[6] = x2;\n vertices[7] = y2;\n vertices[8] = color;\n vertices[9] = u;\n vertices[10] = v2;\n vertices[11] = mixColor;\n\n vertices[12] = x3;\n vertices[13] = y3;\n vertices[14] = color;\n vertices[15] = u2;\n vertices[16] = v2;\n vertices[17] = mixColor;\n\n vertices[18] = x4;\n vertices[19] = y4;\n vertices[20] = color;\n vertices[21] = u2;\n vertices[22] = v;\n vertices[23] = mixColor;\n }\n\n @Override\n public void reset(){\n time = 0f;\n lifetime = 0f;\n fadeCurveIn = 0f;\n fadeCurveOut = 1f;\n }\n\n void draw(){\n float fin = 1f - Mathf.curve(time / lifetime, fadeCurveIn, fadeCurveOut);\n\n Draw.z(z);\n Draw.blend(blending);\n\n System.arraycopy(data, 0, tmpVert, 0, 24);\n\n if(fin < 0.999f){\n for(int i = 0; i < 24; i += 6){\n float col = tmpVert[i + 2];\n Tmp.c1.abgr8888(col);\n Tmp.c1.a(Tmp.c1.a * fin);\n tmpVert[i + 2] = Tmp.c1.toFloatBits();\n }\n }\n Draw.vert(texture, tmpVert, 0, data.length);\n\n Draw.blend();\n }\n }\n}" } ]
import arc.*; import arc.func.*; import arc.graphics.*; import arc.graphics.g2d.*; import arc.math.*; import arc.math.geom.*; import arc.math.geom.QuadTree.*; import arc.struct.*; import arc.util.*; import arc.util.pooling.*; import arc.util.pooling.Pool.*; import flame.*; import flame.Utils.*; import flame.entities.*; import flame.entities.RenderGroupEntity.*; import mindustry.entities.*; import mindustry.game.*; import mindustry.game.EventType.*; import mindustry.graphics.*; import mindustry.type.*; import static arc.math.geom.Intersector.*; import static arc.math.geom.Geometry.*; import static mindustry.Vars.*;
7,171
/* float cwx = centerX * width, cwy = centerY * height; tmpVec.set(x1, y1).sub(x + cwx, y + cwy).rotate(-rotation); x1 = tmpVec.x / width; y1 = tmpVec.y / height; tmpVec.set(x2, y2).sub(x + cwx, y + cwy).rotate(-rotation); x2 = tmpVec.x / width; y2 = tmpVec.y / height; */ /* Effect eff = Fx.hitBulletColor; Color col = Tmp.c1.rand(); Vec2 v = unproject(x1, y1); eff.at(v.x, v.y, 0, col); unproject(x2, y2); eff.at(v.x, v.y, 0, col); col.rand(); eff.at(ox, oy, 0, col); */ /* Tmp.v1.set(v.x, v.y).sub(x, y).rotate(-rotation); float vx = Tmp.v1.x / width + centerX; float vy = Tmp.v1.y / height + centerY; unproject(vx, vy); eff.at(v.x, v.y, 0, col.rand()); */ Seq<Severation> s = cut(x1, y1, x2, y2); if(!s.isEmpty()){ for(Severation c : s){ //if(c.area < 4f * 4f) continue; c.explosionEffect = explosionEffect; float dx = c.centerX - centerX; float dy = c.centerY - centerY; tmpVec.set(dx, dy).scl(width, height).rotate(rotation).add(x, y); c.rotation = rotation; c.x = tmpVec.x; c.y = tmpVec.y; c.vx += vx; c.vy += vy; force.get(c); c.add(); } wasCut = true; remove(); } } @Override public void update(){ x += vx * Time.delta; y += vy * Time.delta; rotation += vr * Time.delta; zTime = Mathf.clamp(zTime + Time.delta / 40f); float drg = zTime < 1 ? drag : 0.2f; vx *= 1f - drg * Time.delta; vy *= 1f - drg * Time.delta; vr *= 1f - drg * Time.delta; if(time >= lifetime){ float b = Mathf.sqrt(area / 4f); explosionEffect.at(x, y, b); float shake = b / 3f; Effect.shake(shake, shake, x, y); remove(); } float speed = area < minArea ? 2f : 1f; time += Time.delta * speed; } @Override public void hitbox(Rect out){ out.setCentered(x, y, bounds); } Vec2 unproject(float x, float y){ return Tmp.v1.set((x - centerX) * width, (y - centerY) * height).rotate(rotation).add(this.x, this.y); } public void drawRender(){ //return tmpVerts; //return null; float sin = Mathf.sinDeg(rotation); float cos = Mathf.cosDeg(rotation); float col = color, mcol = Color.clearFloatBits; TextureRegion r = region; for(CutTri t : tris){ float[] pos = t.pos, verts = tmpVerts; int vertI = 0; for(int i = 0; i < 8; i += 2){ int mi = Math.min(i, 4); float vx = (pos[mi] - centerX) * width; float vy = (pos[mi + 1] - centerY) * height; float tx = (vx * cos - vy * sin) + x; float ty = (vx * sin + vy * cos) + y; verts[vertI] = tx; verts[vertI + 1] = ty; verts[vertI + 2] = col; verts[vertI + 3] = Mathf.lerp(r.u, r.u2, pos[mi]); verts[vertI + 4] = Mathf.lerp(r.v2, r.v, pos[mi + 1]); verts[vertI + 5] = mcol; vertI += 6; } //Draw.z(trueZ); //Draw.vert(region.texture, verts, 0, 24);
package flame.effects; /** * @author EyeOfDarkness */ public class Severation extends DrawEntity implements QuadTreeObject{ static FloatSeq intersections = new FloatSeq(), side1 = new FloatSeq(), side2 = new FloatSeq(); static Seq<CutTri> returnTri = new Seq<>(), tmpTris = new Seq<>(), tmpTris2 = new Seq<>(); static Seq<Severation> tmpCuts = new Seq<>(); static Vec2 tmpVec = new Vec2(), tmpVec2 = new Vec2(), tmpVec3 = new Vec2(); static float[] tmpVerts = new float[24]; static float minArea = 4f * 4f; static int slashIDs = 0; static QuadTree<Severation> cutTree; static Seq<Severation> cutsSeq = new Seq<>(); static Seq<Slash> slashes = new Seq<>(); static Pool<Slash> slashPool = new BasicPool<>(Slash::new); Seq<CutTri> tris = new Seq<>(); float bounds = 0f, area = 0f; float centerX, centerY; float rotation; float width, height; TextureRegion region; IntSet collided = new IntSet(); public float color = Color.whiteFloatBits; public float z = Layer.flyingUnit, shadowZ, zTime; public Effect explosionEffect = FlameFX.fragmentExplosion; float time = 0f, lifetime = 3f * 60f; public float vx, vy, vr; public float drag = 0.05f; public boolean wasCut = false; public static void init(){ Events.on(ResetEvent.class, e -> { slashes.clear(); cutsSeq.clear(); }); Events.on(EventType.WorldLoadEvent.class, e -> cutTree = new QuadTree<>(new Rect(-finalWorldBounds, -finalWorldBounds, world.width() * tilesize + finalWorldBounds * 2, world.height() * tilesize + finalWorldBounds * 2))); } public static void updateStatic(){ if(state.isGame()){ if(cutTree != null){ cutTree.clear(); for(Severation cuts : cutsSeq){ cutTree.insert(cuts); } } if(!slashes.isEmpty()){ slashes.removeAll(s -> { Utils.intersectLine(cutTree, 1f, s.x1, s.y1, s.x2, s.y2, (c, x, y) -> { Rect b = Tmp.r3; c.hitbox(b); if(!b.contains(s.x1, s.y1) && !b.contains(s.x2, s.y2) && c.collided.add(s.id)){ //float len = Mathf.random(0.8f, 1.2f); c.cutWorld(s.x1, s.y1, s.x2, s.y2, cc -> { Vec2 n = nearestSegmentPoint(s.x1, s.y1, s.x2, s.y2, cc.x, cc.y, tmpVec3); int side = pointLineSide(s.x1, s.y1, s.x2, s.y2, cc.x, cc.y); //float len = Mathf.rand //n.sub(cc.x, cc.y).nor().scl(-1.5f * len); float dst = n.dst(cc.x, cc.y); n.sub(cc.x, cc.y).scl((-2.5f) / 20f).limit(3f); cc.vx /= 1.5f; cc.vy /= 1.5f; cc.vr /= 1.5f; cc.vx += n.x; cc.vy += n.y; //cc.vr += -2f * side; cc.vr += (-5f * side) / (1f + dst / 5f); }); } }); s.time += Time.delta; if(s.time >= 4f) slashPool.free(s); return s.time >= 4f; }); } } } public static void slash(float x1, float y1, float x2, float y2){ Slash s = slashPool.obtain(); s.x1 = x1; s.y1 = y1; s.x2 = x2; s.y2 = y2; slashes.add(s); } public static Severation generate(TextureRegion region, float x, float y, float width, float height, float rotation){ Severation c = new Severation(); c.region = region; c.width = width; c.height = height; c.rotation = rotation; c.x = x; c.y = y; for(int i = 0; i < 2; i++){ CutTri tr = new CutTri(); float[] p = tr.pos; p[0] = i == 0 ? 0f : 1f; p[1] = i == 0 ? 0f : 1f; p[2] = 1f; p[3] = 0f; p[4] = 0f; p[5] = 1f; c.tris.add(tr); } c.updateBounds(); c.add(); return c; } public void cutWorld(float x1, float y1, float x2, float y2, Cons<Severation> force){ if(!added || area < minArea) return; if(force == null){ float fx1 = x1, fy1 = y1, fx2 = x2, fy2 = y2; force = cc -> { Vec2 n = nearestSegmentPoint(fx1, fy1, fx2, fy2, cc.x, cc.y, tmpVec2); int side = pointLineSide(fx1, fy1, fx2, fy2, cc.x, cc.y); //float len = Mathf.rand //n.sub(cc.x, cc.y).nor().scl(-1.5f * len); float dst = n.dst(cc.x, cc.y); n.sub(cc.x, cc.y).scl((-2.5f) / 20f).limit(3f); cc.vx /= 1.5f; cc.vy /= 1.5f; cc.vr /= 1.5f; cc.vx += n.x; cc.vy += n.y; //cc.vr += -2f * side; cc.vr += (-5f * side) / (1f + dst / 5f); }; } tmpVec.set(x1, y1).sub(x, y).rotate(-rotation); x1 = tmpVec.x / width + centerX; y1 = tmpVec.y / height + centerY; tmpVec.set(x2, y2).sub(x, y).rotate(-rotation); x2 = tmpVec.x / width + centerX; y2 = tmpVec.y / height + centerY; /* float cwx = centerX * width, cwy = centerY * height; tmpVec.set(x1, y1).sub(x + cwx, y + cwy).rotate(-rotation); x1 = tmpVec.x / width; y1 = tmpVec.y / height; tmpVec.set(x2, y2).sub(x + cwx, y + cwy).rotate(-rotation); x2 = tmpVec.x / width; y2 = tmpVec.y / height; */ /* Effect eff = Fx.hitBulletColor; Color col = Tmp.c1.rand(); Vec2 v = unproject(x1, y1); eff.at(v.x, v.y, 0, col); unproject(x2, y2); eff.at(v.x, v.y, 0, col); col.rand(); eff.at(ox, oy, 0, col); */ /* Tmp.v1.set(v.x, v.y).sub(x, y).rotate(-rotation); float vx = Tmp.v1.x / width + centerX; float vy = Tmp.v1.y / height + centerY; unproject(vx, vy); eff.at(v.x, v.y, 0, col.rand()); */ Seq<Severation> s = cut(x1, y1, x2, y2); if(!s.isEmpty()){ for(Severation c : s){ //if(c.area < 4f * 4f) continue; c.explosionEffect = explosionEffect; float dx = c.centerX - centerX; float dy = c.centerY - centerY; tmpVec.set(dx, dy).scl(width, height).rotate(rotation).add(x, y); c.rotation = rotation; c.x = tmpVec.x; c.y = tmpVec.y; c.vx += vx; c.vy += vy; force.get(c); c.add(); } wasCut = true; remove(); } } @Override public void update(){ x += vx * Time.delta; y += vy * Time.delta; rotation += vr * Time.delta; zTime = Mathf.clamp(zTime + Time.delta / 40f); float drg = zTime < 1 ? drag : 0.2f; vx *= 1f - drg * Time.delta; vy *= 1f - drg * Time.delta; vr *= 1f - drg * Time.delta; if(time >= lifetime){ float b = Mathf.sqrt(area / 4f); explosionEffect.at(x, y, b); float shake = b / 3f; Effect.shake(shake, shake, x, y); remove(); } float speed = area < minArea ? 2f : 1f; time += Time.delta * speed; } @Override public void hitbox(Rect out){ out.setCentered(x, y, bounds); } Vec2 unproject(float x, float y){ return Tmp.v1.set((x - centerX) * width, (y - centerY) * height).rotate(rotation).add(this.x, this.y); } public void drawRender(){ //return tmpVerts; //return null; float sin = Mathf.sinDeg(rotation); float cos = Mathf.cosDeg(rotation); float col = color, mcol = Color.clearFloatBits; TextureRegion r = region; for(CutTri t : tris){ float[] pos = t.pos, verts = tmpVerts; int vertI = 0; for(int i = 0; i < 8; i += 2){ int mi = Math.min(i, 4); float vx = (pos[mi] - centerX) * width; float vy = (pos[mi + 1] - centerY) * height; float tx = (vx * cos - vy * sin) + x; float ty = (vx * sin + vy * cos) + y; verts[vertI] = tx; verts[vertI + 1] = ty; verts[vertI + 2] = col; verts[vertI + 3] = Mathf.lerp(r.u, r.u2, pos[mi]); verts[vertI + 4] = Mathf.lerp(r.v2, r.v, pos[mi + 1]); verts[vertI + 5] = mcol; vertI += 6; } //Draw.z(trueZ); //Draw.vert(region.texture, verts, 0, 24);
DrawnRegion reg = RenderGroupEntity.draw(Blending.normal, z, r.texture, verts, 0);
1
2023-10-18 08:41:59+00:00
8k
ItzGreenCat/SkyImprover
src/main/java/me/greencat/skyimprover/SkyImprover.java
[ { "identifier": "Config", "path": "src/main/java/me/greencat/skyimprover/config/Config.java", "snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashEnable = true;\n @Entry(category = \"render\")\n public static boolean damageSplashCompact = true;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 5.0F)\n public static float damageSplashOffset = 2.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 10.0F)\n public static float damageSplashDuration = 3.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 2.0F)\n public static float damageSplashAnimationSpeed = 0.3F;\n\n @Comment(category = \"misc\")\n public static Comment rainTimer;\n @Entry(category = \"misc\")\n public static boolean rainTimerEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetY = 0.3F;\n @Comment(category = \"misc\")\n public static Comment ferocityCount;\n @Entry(category = \"misc\")\n public static boolean ferocityCountEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetY = 0.4F;\n\n @Comment(category = \"dungeon\")\n public static Comment m3FreezeHelper;\n @Entry(category = \"dungeon\")\n public static boolean m3FreezeHelperEnable = true;\n\n @Comment(category = \"dungeon\")\n public static Comment dungeonDeathMessage;\n @Entry(category = \"dungeon\")\n public static boolean dungeonDeathMessageEnable = true;\n @Entry(category = \"dungeon\")\n public static String dungeonDeathMessageContent = \"BOOM!\";\n @Comment(category = \"dungeon\")\n public static Comment kuudraHelper;\n @Entry(category = \"dungeon\")\n public static boolean kuudraHelperEnable = true;\n}" }, { "identifier": "FeatureLoader", "path": "src/main/java/me/greencat/skyimprover/feature/FeatureLoader.java", "snippet": "public class FeatureLoader {\n public static void load(Class<? extends Module> clazz){\n try {\n clazz.newInstance().registerEvent();\n LogUtils.getLogger().info(\"[SkyImprover] Registering Module:\" + clazz.getSimpleName());\n } catch(Exception e){\n throw new RuntimeException(e);\n }\n }\n public static void loadAll(String packa9e){\n ClassScanner.getClzFromPkg(packa9e).stream().filter(it -> Arrays.stream(it.getInterfaces()).anyMatch(in7erface -> in7erface.getName().equals(Module.class.getName()))).forEach(it -> load((Class<? extends Module>) it));\n }\n}" }, { "identifier": "DamageSplash", "path": "src/main/java/me/greencat/skyimprover/feature/damageSplash/DamageSplash.java", "snippet": "public class DamageSplash implements Module {\n private static final Pattern pattern = Pattern.compile(\"[✧✯]?(\\\\d{1,3}(?:,\\\\d{3})*[⚔+✧❤♞☄✷ﬗ✯]*)\");\n private static final Deque<RenderInformation> damages = new LinkedList<>();\n private static final DecimalFormat decimalFormat = new DecimalFormat(\"0.00\");\n private static final Random random = new Random();\n @Override\n public void registerEvent() {\n RenderLivingEntityPreEvent.EVENT.register(DamageSplash::onRenderEntity);\n WorldRenderEvents.LAST.register(DamageSplash::onRenderWorld);\n }\n public static boolean onRenderEntity(LivingEntity entity){\n if(!Config.damageSplashEnable){\n return true;\n }\n if(entity instanceof ArmorStandEntity && entity.hasCustomName()){\n String customName = entity.getCustomName().getString();\n Matcher matcher = pattern.matcher(customName == null ? \"\" : customName);\n if(matcher.matches() && customName != null){\n String damage = customName.replaceAll( \"[^\\\\d]\", \"\");\n if(Config.damageSplashCompact){\n try {\n int damageInteger = Integer.parseInt(damage);\n if (damageInteger >= 1000 && damageInteger < 1000000) {\n double damageDouble = damageInteger / 1000.0D;\n damage = decimalFormat.format(damageDouble) + \"K\";\n } else if (damageInteger >= 1000000 && damageInteger < 1000000000) {\n double damageDouble = damageInteger / 1000000.0D;\n damage = decimalFormat.format(damageDouble) + \"M\";\n } else if (damageInteger >= 1000000000) {\n double damageDouble = damageInteger / 1000000000.0D;\n damage = decimalFormat.format(damageDouble) + \"B\";\n }\n } catch(Exception ignored){}\n }\n damages.add(new RenderInformation(entity.getX() + random.nextDouble(Config.damageSplashOffset * 2.0D) - Config.damageSplashOffset, entity.getY() + random.nextDouble(Config.damageSplashOffset * 2.0D) - Config.damageSplashOffset, entity.getZ() + random.nextDouble(Config.damageSplashOffset * 2.0D) - Config.damageSplashOffset,damage,new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255))));\n if (MinecraftClient.getInstance().world != null) {\n MinecraftClient.getInstance().world.removeEntity(entity.getId(), Entity.RemovalReason.UNLOADED_WITH_PLAYER);\n }\n return false;\n }\n }\n return true;\n }\n public static void onRenderWorld(WorldRenderContext wrc){\n List<RenderInformation> removeList = new ArrayList<>();\n for(RenderInformation info : damages){\n Vec3d pos = new Vec3d(info.x, info.y,info.z);\n float scaling = (float)Math.max(2,Math.log(pos.distanceTo(MinecraftClient.getInstance().player.getPos()) * 3));\n TextRenderUtils.renderText(wrc,Text.literal(info.message).fillStyle(Style.EMPTY.withColor(info.color.getRGB())),pos,System.currentTimeMillis() - info.startTime <= Config.damageSplashAnimationSpeed * 1000 ? (System.currentTimeMillis() - info.startTime) / (Config.damageSplashAnimationSpeed * 1000) * scaling:scaling,true);\n if(System.currentTimeMillis() - info.startTime >= Config.damageSplashDuration * 1000){\n removeList.add(info);\n }\n }\n if(!removeList.isEmpty()) {\n damages.removeAll(removeList);\n }\n }\n static class RenderInformation{\n double x;\n double y;\n double z;\n String message;\n Color color;\n long startTime;\n public RenderInformation(double x,double y,double z,String message,Color color){\n this.x = x;\n this.y = y;\n this.z = z;\n this.message = message;\n this.startTime = System.currentTimeMillis();\n this.color = color;\n }\n }\n}" }, { "identifier": "DungeonDeathMessage", "path": "src/main/java/me/greencat/skyimprover/feature/dungeonDeathMessage/DungeonDeathMessage.java", "snippet": "public class DungeonDeathMessage implements Module {\n @Override\n public void registerEvent() {\n ClientReceiveMessageEvents.ALLOW_GAME.register(DungeonDeathMessage::onChat);\n }\n\n private static boolean onChat(Text text, boolean overlay) {\n if(!Config.dungeonDeathMessageEnable){\n return true;\n }\n LocationUtils.update();\n if(!LocationUtils.isInDungeons){\n return true;\n }\n String message = text.getString();\n if(message.contains(\"☠\") && !message.contains(\"Crit Damage\")){\n if (MinecraftClient.getInstance().player != null) {\n MinecraftClient.getInstance().player.networkHandler.sendChatMessage(Config.dungeonDeathMessageContent);\n }\n }\n return true;\n }\n}" }, { "identifier": "KuudraHelper", "path": "src/main/java/me/greencat/skyimprover/feature/kuudraHelper/KuudraHelper.java", "snippet": "public class KuudraHelper implements Module {\n public static long lastRefresh = 0L;\n @Override\n public void registerEvent() {\n //SUPPLIES\n //BRING SUPPLY CHEST HERE\n //SUPPLIES RECEIVED\n //SUPPLY PILE\n //PROGRESS:\n //FUEL CELL\n WorldRenderEvents.LAST.register(KuudraHelper::onRender);\n }\n\n private static void onRender(WorldRenderContext worldRenderContext) {\n if(System.currentTimeMillis() - lastRefresh >= 5000){\n lastRefresh = System.currentTimeMillis();\n LocationUtils.update();\n }\n if(!LocationUtils.isInKuudra){\n return;\n }\n if(!Config.kuudraHelperEnable){\n return;\n }\n MinecraftClient client = MinecraftClient.getInstance();\n ClientWorld world = client.world;\n ClientPlayerEntity player = MinecraftClient.getInstance().player;\n if(world == null || player == null){\n return;\n }\n for(Entity entity : world.getEntities()){\n if(!(entity instanceof ArmorStandEntity armorStand)){\n continue;\n }\n if(!armorStand.hasCustomName()){\n continue;\n }\n if(armorStand.getCustomName() != null) {\n String name = armorStand.getCustomName().getString();\n if(name.contains(\"SUPPLIES\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.RED);\n }\n if(name.contains(\"BRING SUPPLY CHEST HERE\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.WHITE);\n }\n if(name.contains(\"SUPPLIES RECEIVED\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.GREEN);\n }\n if(name.contains(\"PROGRESS:\")){\n float scaling = (float)Math.max(2,Math.log(armorStand.getPos().distanceTo(MinecraftClient.getInstance().player.getPos()) * 5));\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.CYAN);\n TextRenderUtils.renderText(worldRenderContext, Text.literal(name.replace(\"PROGRESS:\",\"\")).formatted(Formatting.AQUA),armorStand.getPos(),scaling,true);\n }\n if(name.contains(\"FUEL CELL\")){\n BeaconBeamUtils.renderBeaconBeam(worldRenderContext,armorStand.getBlockPos(),Color.YELLOW);\n }\n }\n }\n }\n\n}" }, { "identifier": "M3FreezeHelper", "path": "src/main/java/me/greencat/skyimprover/feature/m3Freeze/M3FreezeHelper.java", "snippet": "public class M3FreezeHelper implements Module {\n private static long lastReceiveTargetMessage = 0L;\n private static boolean isSend = true;\n @Override\n public void registerEvent() {\n ClientReceiveMessageEvents.ALLOW_GAME.register(M3FreezeHelper::onChat);\n ClientTickEvents.END_CLIENT_TICK.register(M3FreezeHelper::onTick);\n }\n\n private static void onTick(MinecraftClient client) {\n if(System.currentTimeMillis() - lastReceiveTargetMessage >= 5250 && !isSend){\n isSend = true;\n MinecraftClient.getInstance().inGameHud.setTitle(Text.literal(Formatting.RED + \"Freeze!\"));\n }\n }\n\n public static boolean onChat(Text text, boolean overlay){\n if(!Config.m3FreezeHelperEnable){\n return true;\n }\n String message = text.getString();\n if(message.contains(\"You found my Guardians' one weakness?\")){\n lastReceiveTargetMessage = System.currentTimeMillis();\n isSend = false;\n }\n return true;\n }\n\n}" }, { "identifier": "RainTimer", "path": "src/main/java/me/greencat/skyimprover/feature/rainTimer/RainTimer.java", "snippet": "public class RainTimer implements Module {\n private static final SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ssXXX\");\n private static long lastRefresh = 0L;\n\n private static final int cooldown = 2400;\n private static final int duration = 1200;\n private static final int thunderstormInterval = 3;\n\n private static String displayTimeLeft = secsToTime(0);\n private static String displayNextRain = secsToTime(0);\n\n private static boolean netxIsStormCache;\n private static boolean thunderStormNowCache;\n private static boolean rainNowCache;\n\n @Override\n public void registerEvent() {\n HudRenderCallback.EVENT.register(RainTimer::onOverlayRendering);\n }\n public static void onOverlayRendering(DrawContext context,float tick){\n if(!Config.rainTimerEnable){\n return;\n }\n Text displayText = null;\n if(netxIsStormCache){\n displayText = Text.translatable(\"rainTimer.hud.NextThunder\").append(Text.literal(\": \" + displayNextRain + \"⚡\")).fillStyle(Style.EMPTY.withColor(Formatting.GOLD));\n } else if(thunderStormNowCache){\n displayText = Text.translatable(\"rainTimer.hud.rainLeft\").append(Text.literal(\": \" + displayTimeLeft + \"⚡\")).fillStyle(Style.EMPTY.withColor(Formatting.GOLD));\n } else if(rainNowCache){\n displayText = Text.translatable(\"rainTimer.hud.rainLeft\").append(Text.literal(\": \" + displayTimeLeft)).fillStyle(Style.EMPTY.withColor(Formatting.AQUA));\n } else {\n displayText = Text.translatable(\"rainTimer.hud.NextRain\").append(Text.literal(\": \" + displayNextRain));\n }\n TextRenderUtils.renderHUDText(context,(int)(context.getScaledWindowWidth() * Config.rainTimerGuiOffsetX), (int)(context.getScaledWindowHeight() * Config.rainTimerGuiOffsetY),displayText);\n if(System.currentTimeMillis() - lastRefresh <= 1000L){\n return;\n }\n lastRefresh = System.currentTimeMillis();\n\n long timestamp = (long) Math.floor(System.currentTimeMillis() / 1000.0D);\n long skyblockAge = (timestamp - 1560275700);\n\n long thunderstorm = skyblockAge % ((cooldown + duration) * thunderstormInterval);\n long rain = skyblockAge % (cooldown + duration);\n\n boolean rainNow = false;\n if (cooldown <= rain) {\n rainNow = true;\n long timeLeft = (cooldown + duration) - rain;\n displayTimeLeft = secsToTime(timeLeft);\n displayNextRain = secsToTime(timeLeft + cooldown);\n } else {\n rainNow = false;\n displayNextRain = secsToTime(cooldown - rain);\n }\n boolean thunderStormNow = false;\n boolean netxIsStorm = false;\n if ((cooldown <= thunderstorm) && (thunderstorm < (cooldown + duration))) {\n thunderStormNow = true;\n long timeLeft = (cooldown + duration) - rain;\n displayTimeLeft = secsToTime(timeLeft);\n } else {\n thunderStormNow = false;\n long nextThunderstorm = 0;\n if (thunderstorm < cooldown) {\n nextThunderstorm = cooldown - thunderstorm;\n } else if ((cooldown + duration) <= thunderstorm) {\n nextThunderstorm = ((cooldown + duration) * thunderstormInterval) - thunderstorm + cooldown;\n }\n if(nextThunderstorm == cooldown - rain){\n netxIsStorm = true;\n displayNextRain = secsToTime(nextThunderstorm);\n } else {\n netxIsStorm = false;\n }\n }\n thunderStormNowCache = thunderStormNow;\n rainNowCache = rainNow;\n netxIsStormCache = netxIsStorm;\n }\n private static String secsToTime(long seconds) {\n return sdf.format(new Date(seconds * 1000)).substring(14, 19);\n }\n}" }, { "identifier": "LocationUtils", "path": "src/main/java/me/greencat/skyimprover/utils/LocationUtils.java", "snippet": "public class LocationUtils {\n public static boolean isOnSkyblock = false;\n public static boolean isInDungeons = false;\n public static boolean isInKuudra = false;\n public static final ObjectArrayList<String> STRING_SCOREBOARD = new ObjectArrayList<>();\n\n public static void update(){\n MinecraftClient minecraftClient = MinecraftClient.getInstance();\n updateScoreboard(minecraftClient);\n updatePlayerPresenceFromScoreboard(minecraftClient);\n }\n public static void updatePlayerPresenceFromScoreboard(MinecraftClient client) {\n List<String> sidebar = STRING_SCOREBOARD;\n\n FabricLoader fabricLoader = FabricLoader.getInstance();\n if (client.world == null || client.isInSingleplayer() || sidebar.isEmpty()) {\n isOnSkyblock = false;\n isInDungeons = false;\n isInKuudra = false;\n }\n\n if (sidebar.isEmpty() && !fabricLoader.isDevelopmentEnvironment()) return;\n String string = sidebar.toString();\n if(sidebar.isEmpty()){\n isInDungeons = false;\n isInKuudra = false;\n return;\n }\n if (sidebar.get(0).contains(\"SKYBLOCK\") || sidebar.get(0).contains(\"SKIBLOCK\")) {\n if (!isOnSkyblock) {\n isOnSkyblock = true;\n }\n } else {\n isOnSkyblock = false;\n }\n isInDungeons = isOnSkyblock && string.contains(\"The Catacombs\");\n isInKuudra = isOnSkyblock && string.contains(\"Kuudra\");\n }\n private static void updateScoreboard(MinecraftClient client) {\n try {\n STRING_SCOREBOARD.clear();\n\n ClientPlayerEntity player = client.player;\n if (player == null) return;\n\n Scoreboard scoreboard = player.getScoreboard();\n ScoreboardObjective objective = scoreboard.getObjectiveForSlot(1);\n ObjectArrayList<Text> textLines = new ObjectArrayList<>();\n ObjectArrayList<String> stringLines = new ObjectArrayList<>();\n\n for (ScoreboardPlayerScore score : scoreboard.getAllPlayerScores(objective)) {\n Team team = scoreboard.getPlayerTeam(score.getPlayerName());\n\n if (team != null) {\n Text textLine = Text.empty().append(team.getPrefix().copy()).append(team.getSuffix().copy());\n String strLine = team.getPrefix().getString() + team.getSuffix().getString();\n\n if (!strLine.trim().isEmpty()) {\n String formatted = Formatting.strip(strLine);\n\n textLines.add(textLine);\n stringLines.add(formatted);\n }\n }\n }\n\n if (objective != null) {\n stringLines.add(objective.getDisplayName().getString());\n textLines.add(Text.empty().append(objective.getDisplayName().copy()));\n\n Collections.reverse(stringLines);\n Collections.reverse(textLines);\n }\n STRING_SCOREBOARD.addAll(stringLines);\n } catch (NullPointerException ignored) {\n\n }\n }\n}" } ]
import eu.midnightdust.lib.config.MidnightConfig; import me.greencat.skyimprover.config.Config; import me.greencat.skyimprover.feature.FeatureLoader; import me.greencat.skyimprover.feature.damageSplash.DamageSplash; import me.greencat.skyimprover.feature.dungeonDeathMessage.DungeonDeathMessage; import me.greencat.skyimprover.feature.kuudraHelper.KuudraHelper; import me.greencat.skyimprover.feature.m3Freeze.M3FreezeHelper; import me.greencat.skyimprover.feature.rainTimer.RainTimer; import me.greencat.skyimprover.utils.LocationUtils; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
4,757
package me.greencat.skyimprover; public class SkyImprover implements ClientModInitializer { public static final String MODID = "skyimprover"; @Override public void onInitializeClient() {
package me.greencat.skyimprover; public class SkyImprover implements ClientModInitializer { public static final String MODID = "skyimprover"; @Override public void onInitializeClient() {
MidnightConfig.init(MODID, Config.class);
0
2023-10-19 09:19:09+00:00
8k
histevehu/12306
business/src/main/java/com/steve/train/business/mapper/StationMapper.java
[ { "identifier": "Station", "path": "business/src/main/java/com/steve/train/business/domain/Station.java", "snippet": "public class Station {\n private Long id;\n\n private String name;\n\n private String namePinyin;\n\n private String namePy;\n\n private Date createTime;\n\n private Date updateTime;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getNamePinyin() {\n return namePinyin;\n }\n\n public void setNamePinyin(String namePinyin) {\n this.namePinyin = namePinyin;\n }\n\n public String getNamePy() {\n return namePy;\n }\n\n public void setNamePy(String namePy) {\n this.namePy = namePy;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n\n public Date getUpdateTime() {\n return updateTime;\n }\n\n public void setUpdateTime(Date updateTime) {\n this.updateTime = updateTime;\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(getClass().getSimpleName());\n sb.append(\" [\");\n sb.append(\"Hash = \").append(hashCode());\n sb.append(\", id=\").append(id);\n sb.append(\", name=\").append(name);\n sb.append(\", namePinyin=\").append(namePinyin);\n sb.append(\", namePy=\").append(namePy);\n sb.append(\", createTime=\").append(createTime);\n sb.append(\", updateTime=\").append(updateTime);\n sb.append(\"]\");\n return sb.toString();\n }\n}" }, { "identifier": "StationExample", "path": "business/src/main/java/com/steve/train/business/domain/StationExample.java", "snippet": "public class StationExample {\n protected String orderByClause;\n\n protected boolean distinct;\n\n protected List<Criteria> oredCriteria;\n\n public StationExample() {\n oredCriteria = new ArrayList<>();\n }\n\n public void setOrderByClause(String orderByClause) {\n this.orderByClause = orderByClause;\n }\n\n public String getOrderByClause() {\n return orderByClause;\n }\n\n public void setDistinct(boolean distinct) {\n this.distinct = distinct;\n }\n\n public boolean isDistinct() {\n return distinct;\n }\n\n public List<Criteria> getOredCriteria() {\n return oredCriteria;\n }\n\n public void or(Criteria criteria) {\n oredCriteria.add(criteria);\n }\n\n public Criteria or() {\n Criteria criteria = createCriteriaInternal();\n oredCriteria.add(criteria);\n return criteria;\n }\n\n public Criteria createCriteria() {\n Criteria criteria = createCriteriaInternal();\n if (oredCriteria.size() == 0) {\n oredCriteria.add(criteria);\n }\n return criteria;\n }\n\n protected Criteria createCriteriaInternal() {\n Criteria criteria = new Criteria();\n return criteria;\n }\n\n public void clear() {\n oredCriteria.clear();\n orderByClause = null;\n distinct = false;\n }\n\n protected abstract static class GeneratedCriteria {\n protected List<Criterion> criteria;\n\n protected GeneratedCriteria() {\n super();\n criteria = new ArrayList<>();\n }\n\n public boolean isValid() {\n return criteria.size() > 0;\n }\n\n public List<Criterion> getAllCriteria() {\n return criteria;\n }\n\n public List<Criterion> getCriteria() {\n return criteria;\n }\n\n protected void addCriterion(String condition) {\n if (condition == null) {\n throw new RuntimeException(\"Value for condition cannot be null\");\n }\n criteria.add(new Criterion(condition));\n }\n\n protected void addCriterion(String condition, Object value, String property) {\n if (value == null) {\n throw new RuntimeException(\"Value for \" + property + \" cannot be null\");\n }\n criteria.add(new Criterion(condition, value));\n }\n\n protected void addCriterion(String condition, Object value1, Object value2, String property) {\n if (value1 == null || value2 == null) {\n throw new RuntimeException(\"Between values for \" + property + \" cannot be null\");\n }\n criteria.add(new Criterion(condition, value1, value2));\n }\n\n public Criteria andIdIsNull() {\n addCriterion(\"id is null\");\n return (Criteria) this;\n }\n\n public Criteria andIdIsNotNull() {\n addCriterion(\"id is not null\");\n return (Criteria) this;\n }\n\n public Criteria andIdEqualTo(Long value) {\n addCriterion(\"id =\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotEqualTo(Long value) {\n addCriterion(\"id <>\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdGreaterThan(Long value) {\n addCriterion(\"id >\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdGreaterThanOrEqualTo(Long value) {\n addCriterion(\"id >=\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdLessThan(Long value) {\n addCriterion(\"id <\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdLessThanOrEqualTo(Long value) {\n addCriterion(\"id <=\", value, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdIn(List<Long> values) {\n addCriterion(\"id in\", values, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotIn(List<Long> values) {\n addCriterion(\"id not in\", values, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdBetween(Long value1, Long value2) {\n addCriterion(\"id between\", value1, value2, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andIdNotBetween(Long value1, Long value2) {\n addCriterion(\"id not between\", value1, value2, \"id\");\n return (Criteria) this;\n }\n\n public Criteria andNameIsNull() {\n addCriterion(\"`name` is null\");\n return (Criteria) this;\n }\n\n public Criteria andNameIsNotNull() {\n addCriterion(\"`name` is not null\");\n return (Criteria) this;\n }\n\n public Criteria andNameEqualTo(String value) {\n addCriterion(\"`name` =\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotEqualTo(String value) {\n addCriterion(\"`name` <>\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameGreaterThan(String value) {\n addCriterion(\"`name` >\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameGreaterThanOrEqualTo(String value) {\n addCriterion(\"`name` >=\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameLessThan(String value) {\n addCriterion(\"`name` <\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameLessThanOrEqualTo(String value) {\n addCriterion(\"`name` <=\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameLike(String value) {\n addCriterion(\"`name` like\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotLike(String value) {\n addCriterion(\"`name` not like\", value, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameIn(List<String> values) {\n addCriterion(\"`name` in\", values, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotIn(List<String> values) {\n addCriterion(\"`name` not in\", values, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameBetween(String value1, String value2) {\n addCriterion(\"`name` between\", value1, value2, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNameNotBetween(String value1, String value2) {\n addCriterion(\"`name` not between\", value1, value2, \"name\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinIsNull() {\n addCriterion(\"name_pinyin is null\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinIsNotNull() {\n addCriterion(\"name_pinyin is not null\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinEqualTo(String value) {\n addCriterion(\"name_pinyin =\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinNotEqualTo(String value) {\n addCriterion(\"name_pinyin <>\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinGreaterThan(String value) {\n addCriterion(\"name_pinyin >\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinGreaterThanOrEqualTo(String value) {\n addCriterion(\"name_pinyin >=\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinLessThan(String value) {\n addCriterion(\"name_pinyin <\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinLessThanOrEqualTo(String value) {\n addCriterion(\"name_pinyin <=\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinLike(String value) {\n addCriterion(\"name_pinyin like\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinNotLike(String value) {\n addCriterion(\"name_pinyin not like\", value, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinIn(List<String> values) {\n addCriterion(\"name_pinyin in\", values, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinNotIn(List<String> values) {\n addCriterion(\"name_pinyin not in\", values, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinBetween(String value1, String value2) {\n addCriterion(\"name_pinyin between\", value1, value2, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePinyinNotBetween(String value1, String value2) {\n addCriterion(\"name_pinyin not between\", value1, value2, \"namePinyin\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyIsNull() {\n addCriterion(\"name_py is null\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyIsNotNull() {\n addCriterion(\"name_py is not null\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyEqualTo(String value) {\n addCriterion(\"name_py =\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyNotEqualTo(String value) {\n addCriterion(\"name_py <>\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyGreaterThan(String value) {\n addCriterion(\"name_py >\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyGreaterThanOrEqualTo(String value) {\n addCriterion(\"name_py >=\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyLessThan(String value) {\n addCriterion(\"name_py <\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyLessThanOrEqualTo(String value) {\n addCriterion(\"name_py <=\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyLike(String value) {\n addCriterion(\"name_py like\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyNotLike(String value) {\n addCriterion(\"name_py not like\", value, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyIn(List<String> values) {\n addCriterion(\"name_py in\", values, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyNotIn(List<String> values) {\n addCriterion(\"name_py not in\", values, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyBetween(String value1, String value2) {\n addCriterion(\"name_py between\", value1, value2, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andNamePyNotBetween(String value1, String value2) {\n addCriterion(\"name_py not between\", value1, value2, \"namePy\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIsNull() {\n addCriterion(\"create_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIsNotNull() {\n addCriterion(\"create_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeEqualTo(Date value) {\n addCriterion(\"create_time =\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotEqualTo(Date value) {\n addCriterion(\"create_time <>\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeGreaterThan(Date value) {\n addCriterion(\"create_time >\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {\n addCriterion(\"create_time >=\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeLessThan(Date value) {\n addCriterion(\"create_time <\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeLessThanOrEqualTo(Date value) {\n addCriterion(\"create_time <=\", value, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeIn(List<Date> values) {\n addCriterion(\"create_time in\", values, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotIn(List<Date> values) {\n addCriterion(\"create_time not in\", values, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeBetween(Date value1, Date value2) {\n addCriterion(\"create_time between\", value1, value2, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andCreateTimeNotBetween(Date value1, Date value2) {\n addCriterion(\"create_time not between\", value1, value2, \"createTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeIsNull() {\n addCriterion(\"update_time is null\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeIsNotNull() {\n addCriterion(\"update_time is not null\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeEqualTo(Date value) {\n addCriterion(\"update_time =\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeNotEqualTo(Date value) {\n addCriterion(\"update_time <>\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeGreaterThan(Date value) {\n addCriterion(\"update_time >\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {\n addCriterion(\"update_time >=\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeLessThan(Date value) {\n addCriterion(\"update_time <\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {\n addCriterion(\"update_time <=\", value, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeIn(List<Date> values) {\n addCriterion(\"update_time in\", values, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeNotIn(List<Date> values) {\n addCriterion(\"update_time not in\", values, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeBetween(Date value1, Date value2) {\n addCriterion(\"update_time between\", value1, value2, \"updateTime\");\n return (Criteria) this;\n }\n\n public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {\n addCriterion(\"update_time not between\", value1, value2, \"updateTime\");\n return (Criteria) this;\n }\n }\n\n public static class Criteria extends GeneratedCriteria {\n protected Criteria() {\n super();\n }\n }\n\n public static class Criterion {\n private String condition;\n\n private Object value;\n\n private Object secondValue;\n\n private boolean noValue;\n\n private boolean singleValue;\n\n private boolean betweenValue;\n\n private boolean listValue;\n\n private String typeHandler;\n\n public String getCondition() {\n return condition;\n }\n\n public Object getValue() {\n return value;\n }\n\n public Object getSecondValue() {\n return secondValue;\n }\n\n public boolean isNoValue() {\n return noValue;\n }\n\n public boolean isSingleValue() {\n return singleValue;\n }\n\n public boolean isBetweenValue() {\n return betweenValue;\n }\n\n public boolean isListValue() {\n return listValue;\n }\n\n public String getTypeHandler() {\n return typeHandler;\n }\n\n protected Criterion(String condition) {\n super();\n this.condition = condition;\n this.typeHandler = null;\n this.noValue = true;\n }\n\n protected Criterion(String condition, Object value, String typeHandler) {\n super();\n this.condition = condition;\n this.value = value;\n this.typeHandler = typeHandler;\n if (value instanceof List<?>) {\n this.listValue = true;\n } else {\n this.singleValue = true;\n }\n }\n\n protected Criterion(String condition, Object value) {\n this(condition, value, null);\n }\n\n protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {\n super();\n this.condition = condition;\n this.value = value;\n this.secondValue = secondValue;\n this.typeHandler = typeHandler;\n this.betweenValue = true;\n }\n\n protected Criterion(String condition, Object value, Object secondValue) {\n this(condition, value, secondValue, null);\n }\n }\n}" } ]
import com.steve.train.business.domain.Station; import com.steve.train.business.domain.StationExample; import org.apache.ibatis.annotations.Param; import java.util.List;
4,788
package com.steve.train.business.mapper; public interface StationMapper { long countByExample(StationExample example); int deleteByExample(StationExample example); int deleteByPrimaryKey(Long id);
package com.steve.train.business.mapper; public interface StationMapper { long countByExample(StationExample example); int deleteByExample(StationExample example); int deleteByPrimaryKey(Long id);
int insert(Station record);
0
2023-10-23 01:20:56+00:00
8k
team-moabam/moabam-BE
src/test/java/com/moabam/api/domain/coupon/repository/CouponWalletSearchRepositoryTest.java
[ { "identifier": "CouponFixture", "path": "src/test/java/com/moabam/support/fixture/CouponFixture.java", "snippet": "public final class CouponFixture {\n\n\tpublic static final String DISCOUNT_1000_COUPON_NAME = \"황금벌레 1000원 할인\";\n\tpublic static final String DISCOUNT_10000_COUPON_NAME = \"황금벌레 10000원 할인\";\n\n\tpublic static Coupon coupon() {\n\t\treturn Coupon.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.point(1000)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(String name, int startAt) {\n\t\treturn Coupon.builder()\n\t\t\t.name(name)\n\t\t\t.point(10)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, startAt, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(int point, int maxCount) {\n\t\treturn Coupon.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.point(point)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(maxCount)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(CouponType couponType, int point) {\n\t\treturn Coupon.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.point(point)\n\t\t\t.type(couponType)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(String name, int startMonth, int openMonth) {\n\t\treturn Coupon.builder()\n\t\t\t.name(name)\n\t\t\t.point(10)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, startMonth, 1))\n\t\t\t.openAt(LocalDate.of(2023, openMonth, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon discount1000Coupon() {\n\t\treturn Coupon.builder()\n\t\t\t.name(DISCOUNT_1000_COUPON_NAME)\n\t\t\t.point(1000)\n\t\t\t.type(CouponType.DISCOUNT)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon discount10000Coupon() {\n\t\treturn Coupon.builder()\n\t\t\t.name(DISCOUNT_10000_COUPON_NAME)\n\t\t\t.point(10000)\n\t\t\t.type(CouponType.DISCOUNT)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 2, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static CreateCouponRequest createCouponRequest() {\n\t\treturn CreateCouponRequest.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.description(\"coupon description\")\n\t\t\t.point(10)\n\t\t\t.type(CouponType.GOLDEN.getName())\n\t\t\t.maxCount(10)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.build();\n\t}\n\n\tpublic static CreateCouponRequest createCouponRequest(String couponType, int startMonth, int openMonth) {\n\t\treturn CreateCouponRequest.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.description(\"coupon description\")\n\t\t\t.point(10)\n\t\t\t.type(couponType)\n\t\t\t.maxCount(10)\n\t\t\t.startAt(LocalDate.of(2023, startMonth, 1))\n\t\t\t.openAt(LocalDate.of(2023, openMonth, 1))\n\t\t\t.build();\n\t}\n\n\tpublic static CouponStatusRequest couponStatusRequest(boolean ongoing, boolean ended) {\n\t\treturn CouponStatusRequest.builder()\n\t\t\t.opened(ongoing)\n\t\t\t.ended(ended)\n\t\t\t.build();\n\t}\n\n\tpublic static Stream<Arguments> provideCoupons() {\n\t\treturn Stream.of(Arguments.of(\n\t\t\tList.of(\n\t\t\t\tcoupon(\"coupon1\", 3, 1),\n\t\t\t\tcoupon(\"coupon2\", 4, 2),\n\t\t\t\tcoupon(\"coupon3\", 5, 3),\n\t\t\t\tcoupon(\"coupon4\", 6, 4),\n\t\t\t\tcoupon(\"coupon5\", 7, 5),\n\t\t\t\tcoupon(\"coupon6\", 8, 6),\n\t\t\t\tcoupon(\"coupon7\", 9, 7),\n\t\t\t\tcoupon(\"coupon8\", 10, 8),\n\t\t\t\tcoupon(\"coupon9\", 11, 9),\n\t\t\t\tcoupon(\"coupon10\", 12, 10)\n\t\t\t))\n\t\t);\n\t}\n\n\tpublic static Stream<Arguments> provideValues_Object() {\n\t\tSet<Object> values = new HashSet<>();\n\t\tvalues.add(2L);\n\t\tvalues.add(3L);\n\t\tvalues.add(4L);\n\t\tvalues.add(1L);\n\t\tvalues.add(5L);\n\t\tvalues.add(6L);\n\t\tvalues.add(7L);\n\t\tvalues.add(8L);\n\t\tvalues.add(9L);\n\t\tvalues.add(10L);\n\n\t\treturn Stream.of(Arguments.of(values));\n\t}\n\n\tpublic static Stream<Arguments> provideValues_Long() {\n\t\tSet<Object> values = new HashSet<>();\n\t\tvalues.add(2L);\n\t\tvalues.add(3L);\n\t\tvalues.add(4L);\n\t\tvalues.add(1L);\n\t\tvalues.add(5L);\n\t\tvalues.add(6L);\n\t\tvalues.add(7L);\n\t\tvalues.add(8L);\n\t\tvalues.add(9L);\n\t\tvalues.add(10L);\n\n\t\treturn Stream.of(Arguments.of(values));\n\t}\n}" }, { "identifier": "Coupon", "path": "src/main/java/com/moabam/api/domain/coupon/Coupon.java", "snippet": "@Entity\n@Getter\n@Table(name = \"coupon\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Coupon extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"name\", nullable = false, unique = true, length = 20)\n\tprivate String name;\n\n\t@ColumnDefault(\"1\")\n\t@Column(name = \"point\", nullable = false)\n\tprivate int point;\n\n\t@ColumnDefault(\"1\")\n\t@Column(name = \"max_count\", nullable = false)\n\tprivate int maxCount;\n\n\t@ColumnDefault(\"''\")\n\t@Column(name = \"description\", length = 50)\n\tprivate String description;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"type\", nullable = false)\n\tprivate CouponType type;\n\n\t@Column(name = \"start_at\", unique = true, nullable = false)\n\tprivate LocalDate startAt;\n\n\t@Column(name = \"open_at\", nullable = false)\n\tprivate LocalDate openAt;\n\n\t@Column(name = \"admin_id\", updatable = false, nullable = false)\n\tprivate Long adminId;\n\n\t@Builder\n\tprivate Coupon(String name, String description, int point, int maxCount, CouponType type, LocalDate startAt,\n\t\tLocalDate openAt, Long adminId) {\n\t\tthis.name = requireNonNull(name);\n\t\tthis.point = validatePoint(point);\n\t\tthis.maxCount = validateStock(maxCount);\n\t\tthis.description = Optional.ofNullable(description).orElse(BLANK);\n\t\tthis.type = requireNonNull(type);\n\t\tthis.startAt = requireNonNull(startAt);\n\t\tthis.openAt = requireNonNull(openAt);\n\t\tthis.adminId = requireNonNull(adminId);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Coupon{startAt=%s, openAt=%s}\", startAt, openAt);\n\t}\n\n\tprivate int validatePoint(int point) {\n\t\tif (point < 1) {\n\t\t\tthrow new BadRequestException(INVALID_COUPON_POINT);\n\t\t}\n\n\t\treturn point;\n\t}\n\n\tprivate int validateStock(int stock) {\n\t\tif (stock < 1) {\n\t\t\tthrow new BadRequestException(INVALID_COUPON_STOCK);\n\t\t}\n\n\t\treturn stock;\n\t}\n}" }, { "identifier": "CouponWallet", "path": "src/main/java/com/moabam/api/domain/coupon/CouponWallet.java", "snippet": "@Entity\n@Getter\n@Table(name = \"coupon_wallet\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class CouponWallet extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"member_id\", updatable = false, nullable = false)\n\tprivate Long memberId;\n\n\t@JoinColumn(name = \"coupon_id\", nullable = false)\n\t@ManyToOne(fetch = FetchType.LAZY)\n\tprivate Coupon coupon;\n\n\tprivate CouponWallet(Long memberId, Coupon coupon) {\n\t\tthis.memberId = memberId;\n\t\tthis.coupon = coupon;\n\t}\n\n\tpublic static CouponWallet create(Long memberId, Coupon coupon) {\n\t\treturn new CouponWallet(memberId, coupon);\n\t}\n}" }, { "identifier": "NotFoundException", "path": "src/main/java/com/moabam/global/error/exception/NotFoundException.java", "snippet": "@Getter\npublic class NotFoundException extends MoabamException {\n\n\tpublic NotFoundException(ErrorMessage errorMessage) {\n\t\tsuper(errorMessage);\n\t}\n}" }, { "identifier": "ErrorMessage", "path": "src/main/java/com/moabam/global/error/model/ErrorMessage.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum ErrorMessage {\n\n\tFAILED_MOABAM(\"모아밤 서버 실행 중 오류가 발생했습니다.\"),\n\tINVALID_REQUEST_FIELD(\"올바른 요청 정보가 아닙니다.\"),\n\tINVALID_REQUEST_VALUE_TYPE_FORMAT(\"'%s' 값은 유효한 %s 값이 아닙니다.\"),\n\tNOT_FOUND_AVAILABLE_PORT(\"사용 가능한 포트를 찾을 수 없습니다. (10000 ~ 65535)\"),\n\tERROR_EXECUTING_EMBEDDED_REDIS(\"Embedded Redis 실행 중 오류가 발생했습니다.\"),\n\tINVALID_REQUEST_ROLE(\"회원은 회원에, 어드민은 어드민에 연결해야 합니다.\"),\n\n\tREPORT_REQUEST_ERROR(\"신고 요청하고자 하는 방이나 대상이 존재하지 않습니다.\"),\n\n\tROOM_NOT_FOUND(\"존재하지 않는 방 입니다.\"),\n\tROOM_MAX_USER_COUNT_MODIFY_FAIL(\"잘못된 최대 인원수 설정입니다.\"),\n\tROOM_MODIFY_UNAUTHORIZED_REQUEST(\"방장이 아닌 사용자는 방을 수정할 수 없습니다.\"),\n\tROOM_EXIT_MANAGER_FAIL(\"인원수가 2명 이상일 때는 방장을 위임해야 합니다.\"),\n\tPARTICIPANT_NOT_FOUND(\"방에 대한 참여자의 정보가 없습니다.\"),\n\tWRONG_ROOM_PASSWORD(\"방의 비밀번호가 일치하지 않습니다.\"),\n\tROOM_MAX_USER_REACHED(\"방의 인원수가 찼습니다.\"),\n\tROOM_DETAILS_ERROR(\"방 정보를 불러오는데 실패했습니다.\"),\n\tROUTINE_LENGTH_ERROR(\"루틴의 길이가 잘못 되었습니다.\"),\n\tDUPLICATED_DAILY_MEMBER_CERTIFICATION(\"이미 오늘의 인증을 완료하였습니다.\"),\n\tROUTINE_NOT_FOUND(\"루틴을 찾을 수 없습니다\"),\n\tINVALID_REQUEST_URL(\"잘못된 URL 요청입니다.\"),\n\tINVALID_CERTIFY_TIME(\"현재 인증 시간이 아닙니다.\"),\n\tCERTIFICATION_NOT_FOUND(\"인증 정보가 없습니다.\"),\n\tNEED_TO_EXIT_ALL_ROOMS(\"모든 방에서 나가야 회원 탈퇴가 가능합니다.\"),\n\tPARTICIPANT_DEPORT_ERROR(\"방장은 자신을 추방할 수 없습니다.\"),\n\tIMAGE_CONVERT_FAIL(\"이미지 변환을 실패했습니다.\"),\n\tUNAVAILABLE_TO_CHANGE_CERTIFY_TIME(\"이미 한명 이상이 인증을 하면 인증 시간을 바꿀 수 없습니다.\"),\n\tCERTIFIED_ROOM_EXIT_FAILED(\"오늘 인증한 방은 나갈 수 없습니다.\"),\n\tROOM_ENTER_FAILED(\"해당 방의 인증 시간에는 입장할 수 없습니다.\"),\n\n\tLOGIN_FAILED(\"로그인에 실패했습니다.\"),\n\tLOGIN_FAILED_ADMIN_KEY(\"어드민키가 달라요\"),\n\tREQUEST_FAILED(\"네트워크 접근 실패입니다.\"),\n\tTOKEN_TYPE_FAILED(\"토큰 타일이 일치하지 않습니다.\"),\n\tGRANT_FAILED(\"인가 코드 실패\"),\n\tTOKEN_EXPIRE(\"토큰이 만료되었습니다.\"),\n\tAUTHENTICATE_FAIL(\"인증 실패\"),\n\tTOKEN_NOT_FOUND(\"토큰이 존재하지 않습니다.\"),\n\tCOOKIE_NOT_FOUND(\"쿠키가 없습니다\"),\n\tMEMBER_NOT_FOUND(\"존재하지 않는 회원입니다.\"),\n\tMEMBER_NOT_FOUND_BY_MANAGER_OR_NULL(\"방의 매니저거나 회원이 존재하지 않습니다.\"),\n\tMEMBER_ROOM_EXCEED(\"참여할 수 있는 방의 개수가 모두 찼습니다.\"),\n\tUNLINK_REQUEST_FAIL_ROLLBACK_SUCCESS(\"카카오 연결 요청 실패로 Rollback하였습니다.\"),\n\tNICKNAME_CONFLICT(\"이미 존재하는 닉네임입니다.\"),\n\n\tBASIC_SKIN_NOT_FOUND(\"기본 스킨 오류 발생, 관리자에게 문의하세요\"),\n\tINVALID_DEFAULT_SKIN_SIZE(\"기본 스킨은 2개여야 합니다. 관리자에게 문의하세요\"),\n\tSKIN_TYPE_NOT_FOUND(\"스킨 타입이 없습니다. 관리자에게 문의하세요\"),\n\n\tBUG_NOT_ENOUGH(\"보유한 벌레가 부족합니다.\"),\n\n\tITEM_NOT_FOUND(\"존재하지 않는 아이템입니다.\"),\n\tITEM_UNLOCK_LEVEL_HIGH(\"아이템 해금 레벨이 높습니다.\"),\n\tITEM_NOT_PURCHASABLE_BY_BUG_TYPE(\"해당 벌레 타입으로는 구매할 수 없는 아이템입니다.\"),\n\tINVENTORY_NOT_FOUND(\"구매하지 않은 아이템은 적용할 수 없습니다.\"),\n\tDEFAULT_INVENTORY_NOT_FOUND(\"현재 적용된 아이템이 없습니다.\"),\n\tINVENTORY_CONFLICT(\"이미 구매한 아이템입니다.\"),\n\n\tINVALID_BUG_COUNT(\"벌레 개수는 0 이상이어야 합니다.\"),\n\tINVALID_PRICE(\"가격은 0 이상이어야 합니다.\"),\n\tINVALID_QUANTITY(\"수량은 1 이상이어야 합니다.\"),\n\tINVALID_LEVEL(\"레벨은 1 이상이어야 합니다.\"),\n\tINVALID_PAYMENT_AMOUNT(\"결제 금액은 0 이상이어야 합니다.\"),\n\n\tPRODUCT_NOT_FOUND(\"존재하지 않는 상품입니다.\"),\n\n\tPAYMENT_NOT_FOUND(\"존재하지 않는 결제 정보입니다.\"),\n\tINVALID_MEMBER_PAYMENT(\"해당 회원의 결제 정보가 아닙니다.\"),\n\tINVALID_PAYMENT_INFO(\"결제 정보가 일치하지 않습니다.\"),\n\n\tFAILED_FCM_INIT(\"파이어베이스 설정을 실패했습니다.\"),\n\tNOT_FOUND_FCM_TOKEN(\"해당 유저는 접속 중이 아닙니다.\"),\n\tCONFLICT_KNOCK(\"이미 콕 알림을 보낸 대상입니다.\"),\n\n\tINVALID_COUPON_POINT(\"쿠폰의 보너스 포인트는 0 이상이어야 합니다.\"),\n\tINVALID_COUPON_STOCK(\"쿠폰의 재고는 0 이상이어야 합니다.\"),\n\tINVALID_COUPON_STOCK_END(\"쿠폰 발급 선착순이 마감되었습니다.\"),\n\tINVALID_COUPON_START_AT_PERIOD(\"쿠폰 발급 시작 날짜는 현재 날짜보다 이전이거나 같을 수 없습니다.\"),\n\tINVALID_COUPON_OPEN_AT_PERIOD(\"쿠폰 정보 오픈 날짜는 시작 날짜보다 이전이여야 합니다.\"),\n\tINVALID_COUPON_PERIOD(\"쿠폰 발급 가능 기간이 아닙니다.\"),\n\tINVALID_DISCOUNT_COUPON(\"할인 쿠폰은 결제 시, 사용할 수 있습니다.\"),\n\tINVALID_BUG_COUPON(\"벌레 쿠폰은 보관함에서 사용할 수 있습니다.\"),\n\tCONFLICT_COUPON_NAME(\"쿠폰의 이름이 중복되었습니다.\"),\n\tCONFLICT_COUPON_START_AT(\"쿠폰 발급 가능 날짜가 중복되었습니다.\"),\n\tCONFLICT_COUPON_ISSUE(\"이미 쿠폰 발급에 성공했습니다!\"),\n\tNOT_FOUND_COUPON_TYPE(\"존재하지 않는 쿠폰 종류입니다.\"),\n\tNOT_FOUND_COUPON(\"존재하지 않는 쿠폰입니다.\"),\n\tNOT_FOUND_COUPON_WALLET(\"보유하지 않은 쿠폰입니다.\"),\n\n\tS3_UPLOAD_FAIL(\"S3 업로드를 실패했습니다.\"),\n\tS3_INVALID_IMAGE(\"올바른 이미지(파일) 형식이 아닙니다.\"),\n\tS3_INVALID_IMAGE_SIZE(\"파일의 용량이 너무 큽니다.\"),\n\tS3_RESIZE_ERROR(\"이미지 리사이징에서 에러가 발생했습니다.\");\n\n\tprivate final String message;\n}" }, { "identifier": "CouponFixture", "path": "src/test/java/com/moabam/support/fixture/CouponFixture.java", "snippet": "public final class CouponFixture {\n\n\tpublic static final String DISCOUNT_1000_COUPON_NAME = \"황금벌레 1000원 할인\";\n\tpublic static final String DISCOUNT_10000_COUPON_NAME = \"황금벌레 10000원 할인\";\n\n\tpublic static Coupon coupon() {\n\t\treturn Coupon.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.point(1000)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(String name, int startAt) {\n\t\treturn Coupon.builder()\n\t\t\t.name(name)\n\t\t\t.point(10)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, startAt, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(int point, int maxCount) {\n\t\treturn Coupon.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.point(point)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(maxCount)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(CouponType couponType, int point) {\n\t\treturn Coupon.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.point(point)\n\t\t\t.type(couponType)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon coupon(String name, int startMonth, int openMonth) {\n\t\treturn Coupon.builder()\n\t\t\t.name(name)\n\t\t\t.point(10)\n\t\t\t.type(CouponType.MORNING)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, startMonth, 1))\n\t\t\t.openAt(LocalDate.of(2023, openMonth, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon discount1000Coupon() {\n\t\treturn Coupon.builder()\n\t\t\t.name(DISCOUNT_1000_COUPON_NAME)\n\t\t\t.point(1000)\n\t\t\t.type(CouponType.DISCOUNT)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static Coupon discount10000Coupon() {\n\t\treturn Coupon.builder()\n\t\t\t.name(DISCOUNT_10000_COUPON_NAME)\n\t\t\t.point(10000)\n\t\t\t.type(CouponType.DISCOUNT)\n\t\t\t.maxCount(100)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 2, 1))\n\t\t\t.adminId(1L)\n\t\t\t.build();\n\t}\n\n\tpublic static CreateCouponRequest createCouponRequest() {\n\t\treturn CreateCouponRequest.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.description(\"coupon description\")\n\t\t\t.point(10)\n\t\t\t.type(CouponType.GOLDEN.getName())\n\t\t\t.maxCount(10)\n\t\t\t.startAt(LocalDate.of(2023, 2, 1))\n\t\t\t.openAt(LocalDate.of(2023, 1, 1))\n\t\t\t.build();\n\t}\n\n\tpublic static CreateCouponRequest createCouponRequest(String couponType, int startMonth, int openMonth) {\n\t\treturn CreateCouponRequest.builder()\n\t\t\t.name(\"couponName\")\n\t\t\t.description(\"coupon description\")\n\t\t\t.point(10)\n\t\t\t.type(couponType)\n\t\t\t.maxCount(10)\n\t\t\t.startAt(LocalDate.of(2023, startMonth, 1))\n\t\t\t.openAt(LocalDate.of(2023, openMonth, 1))\n\t\t\t.build();\n\t}\n\n\tpublic static CouponStatusRequest couponStatusRequest(boolean ongoing, boolean ended) {\n\t\treturn CouponStatusRequest.builder()\n\t\t\t.opened(ongoing)\n\t\t\t.ended(ended)\n\t\t\t.build();\n\t}\n\n\tpublic static Stream<Arguments> provideCoupons() {\n\t\treturn Stream.of(Arguments.of(\n\t\t\tList.of(\n\t\t\t\tcoupon(\"coupon1\", 3, 1),\n\t\t\t\tcoupon(\"coupon2\", 4, 2),\n\t\t\t\tcoupon(\"coupon3\", 5, 3),\n\t\t\t\tcoupon(\"coupon4\", 6, 4),\n\t\t\t\tcoupon(\"coupon5\", 7, 5),\n\t\t\t\tcoupon(\"coupon6\", 8, 6),\n\t\t\t\tcoupon(\"coupon7\", 9, 7),\n\t\t\t\tcoupon(\"coupon8\", 10, 8),\n\t\t\t\tcoupon(\"coupon9\", 11, 9),\n\t\t\t\tcoupon(\"coupon10\", 12, 10)\n\t\t\t))\n\t\t);\n\t}\n\n\tpublic static Stream<Arguments> provideValues_Object() {\n\t\tSet<Object> values = new HashSet<>();\n\t\tvalues.add(2L);\n\t\tvalues.add(3L);\n\t\tvalues.add(4L);\n\t\tvalues.add(1L);\n\t\tvalues.add(5L);\n\t\tvalues.add(6L);\n\t\tvalues.add(7L);\n\t\tvalues.add(8L);\n\t\tvalues.add(9L);\n\t\tvalues.add(10L);\n\n\t\treturn Stream.of(Arguments.of(values));\n\t}\n\n\tpublic static Stream<Arguments> provideValues_Long() {\n\t\tSet<Object> values = new HashSet<>();\n\t\tvalues.add(2L);\n\t\tvalues.add(3L);\n\t\tvalues.add(4L);\n\t\tvalues.add(1L);\n\t\tvalues.add(5L);\n\t\tvalues.add(6L);\n\t\tvalues.add(7L);\n\t\tvalues.add(8L);\n\t\tvalues.add(9L);\n\t\tvalues.add(10L);\n\n\t\treturn Stream.of(Arguments.of(values));\n\t}\n}" } ]
import static com.moabam.support.fixture.CouponFixture.*; import static org.assertj.core.api.Assertions.*; import java.util.List; import java.util.Optional; 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 com.moabam.api.domain.coupon.Coupon; import com.moabam.api.domain.coupon.CouponWallet; import com.moabam.global.error.exception.NotFoundException; import com.moabam.global.error.model.ErrorMessage; import com.moabam.support.annotation.QuerydslRepositoryTest; import com.moabam.support.fixture.CouponFixture;
6,338
package com.moabam.api.domain.coupon.repository; @QuerydslRepositoryTest class CouponWalletSearchRepositoryTest { @Autowired private CouponRepository couponRepository; @Autowired private CouponWalletRepository couponWalletRepository; @Autowired private CouponWalletSearchRepository couponWalletSearchRepository; @DisplayName("나의 쿠폰함의 특정 쿠폰을 조회한다. - List<CouponWallet>") @Test void findAllByIdAndMemberId_success() { // Given Coupon coupon = couponRepository.save(CouponFixture.coupon());
package com.moabam.api.domain.coupon.repository; @QuerydslRepositoryTest class CouponWalletSearchRepositoryTest { @Autowired private CouponRepository couponRepository; @Autowired private CouponWalletRepository couponWalletRepository; @Autowired private CouponWalletSearchRepository couponWalletSearchRepository; @DisplayName("나의 쿠폰함의 특정 쿠폰을 조회한다. - List<CouponWallet>") @Test void findAllByIdAndMemberId_success() { // Given Coupon coupon = couponRepository.save(CouponFixture.coupon());
CouponWallet couponWallet = couponWalletRepository.save(CouponWallet.create(1L, coupon));
2
2023-10-20 06:15:43+00:00
8k
liukanshan1/PrivateTrace-Core
src/main/java/Priloc/protocol/TestEncode.java
[ { "identifier": "TimeLocationData", "path": "src/main/java/Priloc/data/TimeLocationData.java", "snippet": "public class TimeLocationData implements Serializable {\n private Location loc;\n private Date date;\n private double accuracy = Constant.RADIUS;\n private TimeLocationData nTLD = null;\n private TimeLocationData pTLD = null;\n\n public TimeLocationData(Location loc, Date date) {\n this.loc = loc;\n this.date = date;\n }\n\n public TimeLocationData(Location loc, Date date, TimeLocationData nTLD) {\n this.loc = loc;\n this.date = date;\n this.nTLD = nTLD;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public void setNext(TimeLocationData nTLD) {\n this.nTLD = nTLD;\n }\n\n public void setPrevious(TimeLocationData pTLD) {\n this.pTLD = pTLD;\n }\n\n @Override\n public String toString() {\n return \"TrajectoryData{\" +\n \"loc=\" + loc +\n \", date=\" + date +\n '}';\n }\n\n public Location getLoc() {\n return loc;\n }\n\n public Date getDate() {\n return date;\n }\n\n public double getAccuracy() {\n return accuracy;\n }\n\n public boolean hasNext() {\n return nTLD != null;\n }\n\n public TimeLocationData next() {\n return nTLD;\n }\n\n public boolean hasPrevious() {\n return pTLD != null;\n }\n\n public TimeLocationData previous() {\n return pTLD;\n }\n\n public EncTmLocData encrypt(){\n return new EncTmLocData(this);\n }\n\n public Circle getCircle() {\n return new Circle(new Point(loc), accuracy);\n }\n}" }, { "identifier": "Trajectory", "path": "src/main/java/Priloc/data/Trajectory.java", "snippet": "public class Trajectory implements Callable<EncTrajectory>, Serializable {\n private List<TimeLocationData> TLDs;\n private String name;\n\n public Trajectory(List<TimeLocationData> tlds, String name) {\n this.TLDs = tlds;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n return \"Trajectory{\" +\n \"name='\" + name + '\\'' +\n \"size='\" + TLDs.size() + '\\'' +\n '}';\n }\n\n public List<TimeLocationData> getTLDs() {\n return TLDs;\n }\n\n public Date getStartDate() {\n return this.TLDs.get(0).getDate();\n }\n\n public Date getEndDate() {\n return this.TLDs.get(TLDs.size() - 1).getDate();\n }\n\n public EncTrajectory encrypt() {\n return new EncTrajectory(this);\n }\n\n public static boolean isIntersect(Trajectory t1, Trajectory t2) {\n // 判断时间重合\n Map<Date, List<Circle>> positiveCircles = new HashMap<>();\n for (TimeLocationData tld : t1.TLDs) {\n Date startDate = tld.getDate();\n List<Circle> circles = positiveCircles.get(startDate);\n if (circles == null) {\n circles = new ArrayList<>();\n }\n circles.add(tld.getCircle());\n positiveCircles.put(startDate, circles);\n }\n for (TimeLocationData tld : t2.TLDs) {\n Date startDate = tld.getDate();\n List<Circle> circles = positiveCircles.get(startDate);\n if (circles == null) {\n continue;\n }\n if (tld.getCircle().isIntersect(circles)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public EncTrajectory call() {\n return encrypt();\n }\n\n// /**\n// * 自定义序列化 搭配transist使用\n// */\n// private void writeObject(ObjectOutputStream out) throws IOException {\n// //只序列化以下3个成员变量\n// out.writeObject(this.TLDs);\n// out.writeObject(this.name);\n// }\n//\n// private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n// //注意:read()的顺序要和write()的顺序一致。\n// this.TLDs = (List<TimeLocationData>) in.readObject();\n// this.name = (String) in.readObject();\n// TimeLocationData prev = null;\n// for (TimeLocationData curr : TLDs) {\n// curr.setPrevious(prev);\n// if (prev != null) {\n// prev.setNext(curr);\n// }\n// prev = curr;\n// }\n// }\n}" }, { "identifier": "TrajectoryReader", "path": "src/main/java/Priloc/data/TrajectoryReader.java", "snippet": "public class TrajectoryReader {\n private String path;\n private File pltFile;\n private Scanner scn;\n\n public TrajectoryReader(String path) throws FileNotFoundException {\n this.path = path;\n pltFile = new File(path);\n scn = new Scanner(pltFile);\n for (int i = 0; i < 6; i++) {\n scn.nextLine();\n }\n }\n\n public TrajectoryReader(File file) throws FileNotFoundException {\n pltFile = file;\n scn = new Scanner(pltFile);\n for (int i = 0; i < 6; i++) {\n scn.nextLine();\n }\n }\n\n public File getPltFile() {\n return pltFile;\n }\n\n private boolean hasNext() {\n return scn.hasNext();\n }\n\n private TimeLocationData next() throws ParseException {\n String[] tokens = scn.next().split(\",\");\n double lat = Double.parseDouble(tokens[0]);\n double lon = Double.parseDouble(tokens[1]);\n // 未引入高度\n double altitude = Double.parseDouble(tokens[3]); // Altitude in feet\n String time = tokens[5] + ' ' + tokens[6];\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n Date date = dateFormat.parse(time);\n if (Constant.IGNORE_DATE) {\n date.setYear(2008);\n date.setMonth(Calendar.JUNE);\n date.setDate(24);\n }\n return new TimeLocationData(new Location(lat, lon), date);\n }\n\n public Trajectory load() throws ParseException {\n List<TimeLocationData> tlds = new ArrayList<>();\n TimeLocationData pTLD = null;\n Date previousDate = null;\n double rad = 0;\n while (this.hasNext()) {\n TimeLocationData cTLD = this.next();\n Date currentDate = Utils.getStart(cTLD.getDate());\n if (currentDate.equals(previousDate)) {\n // distance\n rad = Math.max(rad, cTLD.getLoc().distance(pTLD.getLoc()));\n if (rad < Constant.RADIUS * 1.5) {\n continue;\n }\n }\n if (rad > Constant.RADIUS * 2) {\n // TODO 补充rad/2r个园\n TimeLocationData mTLD = new TimeLocationData(new Location(\n (cTLD.getLoc().getLatitude() + pTLD.getLoc().getLatitude()) / 2.0,\n (cTLD.getLoc().getLongitude() + pTLD.getLoc().getLongitude()) / 2.0\n ), currentDate);\n // 连接双向链表\n mTLD.setPrevious(pTLD);\n mTLD.setNext(cTLD);\n // 将节点加入到轨迹中\n tlds.add(mTLD);\n // 设置当前节点为Previous\n pTLD = mTLD;\n }\n rad = 0;\n // 设置时间为标准间隔\n cTLD.setDate(currentDate);\n // 连接双向链表\n cTLD.setPrevious(pTLD);\n if (pTLD != null) {\n pTLD.setNext(cTLD);\n }\n // 将节点加入到轨迹中\n tlds.add(cTLD);\n // 设置当前节点为Previous\n pTLD = cTLD;\n previousDate = currentDate;\n }\n return new Trajectory(tlds, pltFile.getName());\n }\n\n public static boolean check(Trajectory t) {\n Circle pc = null;\n for (TimeLocationData tld : t.getTLDs()) {\n Circle cc = tld.getCircle();\n if (pc != null) {\n if (Point.distance(cc.getCenter(), pc.getCenter()) > Constant.RADIUS * 3) {\n // System.out.println(Point.distance(cc.getCenter(), pc.getCenter()) + \"\" + tld.getDate());\n return false;\n }\n }\n pc = cc;\n }\n return true;\n }\n\n public static void main(String[] args) {\n try {\n TrajectoryReader pltReader = new TrajectoryReader(\"./GeoLife Trajectories 1.3/data by person/000/Trajectory/20081023025304.plt\");\n while (pltReader.hasNext()) {\n System.out.println(pltReader.next());\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n}" }, { "identifier": "Location", "path": "src/main/java/Priloc/geo/Location.java", "snippet": "public class Location implements Serializable {\n private double latitude;\n private double longitude;\n private double altitude = 0.0;\n\n public Location(double latitude, double longitude, double altitude) {\n this(latitude, longitude);\n this.altitude = altitude;\n }\n\n public Location(double latitude, double longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n @Override\n public String toString() {\n return \"PlainLocation{\" +\n \"latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", altitude=\" + altitude +\n //\", XYZ=\" + toXYZ() +\n '}';\n }\n\n public Turple<Double, Double, Double> toXYZ() {\n return Utils.gcj02ToXYZ(longitude, latitude, altitude);\n }\n\n public EncryptedPoint encrypt() {\n Turple<Double, Double, Double> xyz = toXYZ();\n return new EncryptedPoint(xyz.first, xyz.second, xyz.third);\n }\n\n public double squareDistance(Location other) {\n// Turple<Double, Double, Double> xyz1 = toXYZ();\n// Turple<Double, Double, Double> xyz2 = other.toXYZ();\n// return Math.pow(xyz1.first - xyz2.first, 2) + Math.pow(xyz1.second - xyz2.second, 2) + Math.pow(xyz1.third - xyz2.third, 2);\n return Math.pow(distance(other), 2);\n }\n\n public double distance(Location other) {\n// return Math.sqrt(squareDistance(other));\n GlobalCoordinates source = new GlobalCoordinates(latitude, longitude);\n GlobalCoordinates target = new GlobalCoordinates(other.latitude, other.longitude);\n return new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.WGS84, source, target).getEllipsoidalDistance();\n }\n\n public double encodeDistance(Location other) {\n Turple<Double, Double, Double> xyz1 = toXYZ();\n Turple<Double, Double, Double> xyz2 = other.toXYZ();\n double squareDist = Math.pow(xyz1.first - xyz2.first, 2) + Math.pow(xyz1.second - xyz2.second, 2) + Math.pow(xyz1.third - xyz2.third, 2);\n return Math.sqrt(squareDist);\n }\n}" }, { "identifier": "Constant", "path": "src/main/java/Priloc/utils/Constant.java", "snippet": "public class Constant {\n public static final int FIXED_POINT = 8;\n public static final int THREAD = 12;\n public static final int KEY_LEN = 512;\n public static final int[] REDUCE = new int[]{2160000, 1820000, -5690000};\n\n public static final boolean IGNORE_DATE = true;\n public static final boolean REJECT_R_LESS_P5 = true;\n\n // 时间段大小\n public final static int INTERVAL = 10;\n // 每个时间段的移动最大距离\n public static final double RADIUS = 200.0;\n // TODO 优化 不同时间段的活跃距离\n public static final double[] COMPARE_DISTANCE = new double[]{1200 * 1200.0};\n public static final int[] PRUNE_NUM = new int[]{0, 2};\n // 控制形状拟合效果\n public static final int TRIANGLE_NUM = 100;\n public static final Circle.circleFilter FILTER = new Circle.distantFilter(); //new Circle.areaFilter();\n\n public static String toStr() {\n return \"Constant{\" +\n \"INTERVAL=\" + INTERVAL +\n \", RADIUS=\" + RADIUS +\n \", IGNORE_DATE=\" + IGNORE_DATE +\n \", REJECT_R_LESS_P5=\" + REJECT_R_LESS_P5 +\n \", COMPARE_DISTANCE=\" + Arrays.toString(COMPARE_DISTANCE) +\n \", PRUNE_NUM=\" + Arrays.toString(PRUNE_NUM) +\n \", TRIANGLE_NUM=\" + TRIANGLE_NUM +\n \", FILTER=\" + FILTER +\n '}';\n }\n}" } ]
import Priloc.data.TimeLocationData; import Priloc.data.Trajectory; import Priloc.data.TrajectoryReader; import Priloc.geo.Location; import Priloc.utils.Constant; import java.util.List; import static java.lang.System.exit;
3,969
package Priloc.protocol; public class TestEncode { // public static void main(String[] args) throws Exception { // String[] negativePath = new String[]{ // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt", // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt" // }; // TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeReaders[i] = new TrajectoryReader(negativePath[i]); // } // Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeTrajectories[i] = negativeReaders[i].load(); // } // double maxError = 0; // for (int i = 0; i < negativeTrajectories.length; i++) { // List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); // for(int j = 0; j < tlds.size() - 1; j++) { // Location l1 = tlds.get(j).getLoc(); // Location l2 = tlds.get(j + 1).getLoc(); // double expect = l1.distance(l2); // if (expect > 2 * Constant.RADIUS) { // continue; // } // double actual = l1.encodeDistance(l2); // //System.out.println(Math.abs(expect - actual)); // if (Math.abs(expect - actual) > maxError) { // maxError = Math.abs(expect - actual); // System.out.println(maxError); // } //// if (Math.abs(expect - actual) > 1) { //// System.out.println(l1); //// System.out.println(l2); //// System.out.println(expect); //// System.out.println(actual); //// } // } // } // } public static void main(String[] args) throws Exception { String[] negativePath = new String[]{ "./C++/dataset", }; TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeReaders[i] = new TrajectoryReader(negativePath[i]); } Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeTrajectories[i] = negativeReaders[i].load(); } double maxError = 0; for (int i = 0; i < negativeTrajectories.length; i++) {
package Priloc.protocol; public class TestEncode { // public static void main(String[] args) throws Exception { // String[] negativePath = new String[]{ // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090503033926.plt", // "./Geolife Trajectories 1.3/Data/000/Trajectory/20090705025307.plt" // }; // TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeReaders[i] = new TrajectoryReader(negativePath[i]); // } // Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; // for (int i = 0; i < negativePath.length; i++) { // negativeTrajectories[i] = negativeReaders[i].load(); // } // double maxError = 0; // for (int i = 0; i < negativeTrajectories.length; i++) { // List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs(); // for(int j = 0; j < tlds.size() - 1; j++) { // Location l1 = tlds.get(j).getLoc(); // Location l2 = tlds.get(j + 1).getLoc(); // double expect = l1.distance(l2); // if (expect > 2 * Constant.RADIUS) { // continue; // } // double actual = l1.encodeDistance(l2); // //System.out.println(Math.abs(expect - actual)); // if (Math.abs(expect - actual) > maxError) { // maxError = Math.abs(expect - actual); // System.out.println(maxError); // } //// if (Math.abs(expect - actual) > 1) { //// System.out.println(l1); //// System.out.println(l2); //// System.out.println(expect); //// System.out.println(actual); //// } // } // } // } public static void main(String[] args) throws Exception { String[] negativePath = new String[]{ "./C++/dataset", }; TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeReaders[i] = new TrajectoryReader(negativePath[i]); } Trajectory[] negativeTrajectories = new Trajectory[negativePath.length]; for (int i = 0; i < negativePath.length; i++) { negativeTrajectories[i] = negativeReaders[i].load(); } double maxError = 0; for (int i = 0; i < negativeTrajectories.length; i++) {
List<TimeLocationData> tlds = negativeTrajectories[i].getTLDs();
0
2023-10-22 06:28:51+00:00
8k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/listview/XmCheckBoxListCell.java
[ { "identifier": "ColorType", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/ColorType.java", "snippet": "public class ColorType {\n /**\n * 主要颜色\n */\n public static String PRIMARY = \"#4c14c1ff\";\n public static String SECONDARY=\"#585858ff\";\n public static String DANGER=\"#ff4d4fff\";\n public static String WARNING=\"#fc9e1bff\";\n public static String SUCCESS=\"#49c31bff\";\n public static String OTHER=\"\";\n\n public static ColorType other(String color){\n return new ColorType(color, \"other\");\n }\n public static ColorType other(Paint color){\n return new ColorType(color);\n }\n public static ColorType primary(){\n return new ColorType(PRIMARY, \"primary\");\n }\n public static ColorType secondary(){\n return new ColorType(SECONDARY, \"secondary\");\n }\n public static ColorType danger(){\n return new ColorType(DANGER, \"danger\");\n }\n public static ColorType warning(){\n return new ColorType(WARNING, \"warning\");\n }\n public static ColorType success(){\n return new ColorType(SUCCESS, \"success\");\n }\n\n public ColorType(String color) {\n this.color = color;\n }\n public ColorType(Paint color) {\n this.paint = color;\n }\n\n public ColorType(String color, String label) {\n this.color = color;\n this.label = label;\n }\n\n public static ColorType get(String value){\n if(value == null || value.isEmpty()){\n return null;\n }\n\n value = value.toLowerCase();\n if(value.equals(\"primary\")){\n return primary();\n }else if(value.equals(\"secondary\")){\n return secondary();\n }else if(value.equals(\"danger\")){\n return danger();\n }else if(value.equals(\"warning\")){\n return warning();\n }else if(value.equals(\"success\")){\n return success();\n }else{\n return other(value);\n }\n }\n\n private String color;\n private Paint paint;\n private Color fxColor;\n //颜色名\n private String label;\n\n public String getColor() {\n if(color == null){\n if(paint instanceof Color){\n color = FxKit.formatHexString((Color) paint);\n }else{\n color = paint.toString();\n }\n }\n return color;\n }\n\n public ColorType clone(){\n return new ColorType(this.color, this.label);\n }\n\n public String getLabel() {\n return label;\n }\n\n public Paint getPaint(){\n if(paint == null){\n //TODO 这里支持渐变色的转换\n if(color.toLowerCase().startsWith(\"linear-gradient\")){\n paint = LinearGradient.valueOf(color);\n }else if(color.toLowerCase().startsWith(\"radial-gradient\")){\n paint = RadialGradient.valueOf(color);\n }else{\n paint = Color.web(color);\n }\n }\n return paint;\n }\n\n public Color getFxColor(){\n if(fxColor == null){\n //TODO 这里支持渐变色的转换\n if(color.toLowerCase().startsWith(\"linear-gradient\")){\n LinearGradient lg = LinearGradient.valueOf(color);\n paint = lg;\n fxColor = lg.getStops().get(0).getColor();\n }else if(color.toLowerCase().startsWith(\"radial-gradient\")){\n RadialGradient rg = RadialGradient.valueOf(color);\n paint = rg;\n fxColor = rg.getStops().get(0).getColor();\n }else{\n paint = Color.web(color);\n fxColor = (Color) paint;\n }\n }\n return fxColor;\n }\n\n public void setColor(String color) {\n this.color = color;\n }\n\n @Override\n public boolean equals(Object o) {\n// if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n ColorType that = (ColorType) o;\n return Objects.equals(color, that.color);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(color);\n }\n\n @Override\n public String toString() {\n\n if(\"primary\".equals(label) || \"secondary\".equals(label) || \"danger\".equals(label) || \"warning\".equals(label) || \"success\".equals(label) )\n return label;\n\n return getColor();\n }\n}" }, { "identifier": "XmCheckBox", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/checkbox/XmCheckBox.java", "snippet": "public class XmCheckBox<T> extends SelectableText implements XmToggle<T>{\n\n /* *************************************************************************\n * *\n * Constructors *\n * *\n **************************************************************************/\n\n /**\n * Creates a check box with an empty string for its label.\n */\n public XmCheckBox() {\n initialize();\n }\n\n /**\n * Creates a check box with the specified text as its label.\n *\n * @param text A text string for its label.\n */\n public XmCheckBox(String text) {\n setText(text);\n initialize();\n }\n\n public XmCheckBox(T t){\n setValue(t);\n initialize();\n }\n\n private void initialize() {\n getStyleClass().setAll(DEFAULT_STYLE_CLASS);\n setAccessibleRole(AccessibleRole.CHECK_BOX);\n\n // initialize pseudo-class state\n pseudoClassStateChanged(PSEUDO_CLASS_DETERMINATE, true);\n }\n\n /* *************************************************************************\n * *\n * Properties *\n * *\n **************************************************************************/\n\n /**\n * 是否radiobutton,如果是radioButton,这不能使用第三状态\n */\n private BooleanProperty radioButton;\n public boolean isRadioButton() {\n return radioButtonProperty().get();\n }\n public BooleanProperty radioButtonProperty() {\n if(radioButton == null){\n radioButton = new BooleanPropertyBase(false) {\n @Override protected void invalidated() {\n final boolean isRadio = get();\n if(isRadio){\n indeterminateProperty().set(false);\n allowIndeterminateProperty().set(false);\n roundTypeProperty().set(RoundType.CIRCLE);\n }\n }\n\n @Override\n public Object getBean() {\n return XmCheckBox.this;\n }\n\n @Override\n public String getName() {\n return \"radioButton\";\n }\n };\n }\n return radioButton;\n }\n public void setRadioButton(boolean radioButton) {\n this.radioButtonProperty().set(radioButton);\n }\n\n /**\n * 高亮显示,默认是灰色在失去焦点以后\n */\n private BooleanProperty selectedHighLight;\n\n public boolean isSelectedHighLight() {\n return selectedHighLightProperty().get();\n }\n\n public BooleanProperty selectedHighLightProperty() {\n if(selectedHighLight == null){\n selectedHighLight = new SimpleBooleanProperty(false);\n }\n return selectedHighLight;\n }\n\n public void setSelectedHightLight(boolean selectedHightLight) {\n this.selectedHighLightProperty().set(selectedHightLight);\n }\n\n @Override\n public void setRoundType(RoundType roundType) {\n if(this.isRadioButton()) return;\n super.setRoundType(roundType);\n }\n\n /**\n * Determines whether the XmCheckBox is in the indeterminate state.\n * 如果是RadioButton,则不能使用第三状态\n */\n private BooleanProperty indeterminate;\n public final void setIndeterminate(boolean value) {\n if(isRadioButton() && value) return;\n indeterminateProperty().set(value);\n }\n\n public final boolean isIndeterminate() {\n return indeterminate != null && indeterminate.get();\n }\n\n public final BooleanProperty indeterminateProperty() {\n if (indeterminate == null) {\n indeterminate = new BooleanPropertyBase(false) {\n @Override protected void invalidated() {\n final boolean active = get();\n pseudoClassStateChanged(PSEUDO_CLASS_DETERMINATE, !active);\n pseudoClassStateChanged(PSEUDO_CLASS_INDETERMINATE, active);\n notifyAccessibleAttributeChanged(AccessibleAttribute.INDETERMINATE);\n// System.out.println(getText()+\":\"+active);\n }\n @Override\n public Object getBean() {\n return XmCheckBox.this;\n }\n\n @Override\n public String getName() {\n return \"indeterminate\";\n }\n };\n }\n return indeterminate;\n }\n /**\n * Indicates whether this XmCheckBox is checked.\n */\n private BooleanProperty selected;\n public final void setSelected(boolean value) {\n selectedProperty().set(value);\n }\n public final boolean isSelected() {\n return selected == null ? false : selected.get();\n }\n\n public final BooleanProperty selectedProperty() {\n if (selected == null) {\n selected = new BooleanPropertyBase() {\n @Override protected void invalidated() {\n final Boolean selected = get();\n pseudoClassStateChanged(PSEUDO_CLASS_SELECTED, selected);\n notifyAccessibleAttributeChanged(AccessibleAttribute.SELECTED);\n\n final XmToggleGroup<T> tg = getToggleGroup();\n if (tg != null) {\n if (selected) {\n tg.selectToggle(XmCheckBox.this);\n } else if (tg.getSelectedToggle() == XmCheckBox.this) {\n\n if (!tg.getSelectedToggle().isSelected()) {\n for (XmToggle<T> toggle: tg.getToggles()) {\n if (toggle.isSelected()) {\n return;\n }\n }\n }\n tg.selectToggle(null);\n }\n }\n }\n\n @Override\n public Object getBean() {\n return XmCheckBox.this;\n }\n\n @Override\n public String getName() {\n return \"selected\";\n }\n };\n }\n return selected;\n }\n\n private ObjectProperty<XmToggleGroup<T>> toggleGroup;\n public final void setToggleGroup(XmToggleGroup<T> value) {\n toggleGroupProperty().set(value);\n }\n\n public final XmToggleGroup<T> getToggleGroup() {\n return toggleGroup == null ? null : toggleGroup.get();\n }\n\n public final ObjectProperty<XmToggleGroup<T>> toggleGroupProperty() {\n if (toggleGroup == null) {\n final XmCheckBox<T> that = this;\n toggleGroup = new ObjectPropertyBase<>() {\n private XmToggleGroup<T> old;\n// private ChangeListener<XmToggle<T>> listener = (o, oV, nV) ->{\n// XmCheckBox.this.setFocusTraversable(true);\n// };\n\n @Override protected void invalidated() {\n final XmToggleGroup<T> tg = get();\n if (tg != null && !tg.getToggles().contains(that)) {\n if (old != null) {\n old.getToggles().remove(that);\n }\n// XmCheckBox.this.setFocusTraversable(true);\n tg.getToggles().add(that);\n// tg.selectedToggleProperty().addListener(listener);\n } else if (tg == null) {\n// old.selectedToggleProperty().removeListener(listener);\n old.getToggles().remove(that);\n// XmCheckBox.this.setFocusTraversable(false);\n }\n\n old = tg;\n }\n\n @Override\n public Object getBean() {\n return that;\n }\n\n @Override\n public String getName() {\n return \"toggleGroup\";\n }\n };\n }\n return toggleGroup;\n }\n\n // --- string converter\n public ObjectProperty<XmStringConverter<T>> converterProperty() { return converter; }\n private ObjectProperty<XmStringConverter<T>> converter =\n new SimpleObjectProperty<XmStringConverter<T>>(this, \"converter\", defaultStringConverter());\n public final void setConverter(XmStringConverter<T> value) { converterProperty().set(value); }\n public final XmStringConverter<T> getConverter() {return converterProperty().get(); }\n private static <T> XmStringConverter<T> defaultStringConverter() {\n return new XmStringConverter<T>() {\n @Override public String toString(T t) {\n return t == null ? null : t.toString();\n }\n };\n }\n\n /**\n * 支持设置一个默认值,当选中的时候可以获取到这个默认值,\n * 如果设置了这个默认值,checkbox显示的文本,将会使用value的toString()方法,\n * 所以如果设置了value, 请根据需要自己设置converter,\n */\n private ObjectProperty<T> value = new SimpleObjectProperty<>();\n public T getValue() {\n return value.get();\n }\n\n public ObjectProperty<T> valueProperty() {\n return value;\n }\n\n public void setValue(T value) {\n this.value.set(value);\n }\n\n @Override\n public ObservableMap<Object, T> getXmProperties() {\n return toggleGroupProperty().get().getProperties();\n }\n\n /**\n * Determines whether the user toggling the XmCheckBox should cycle through\n * all three states: <em>checked</em>, <em>unchecked</em>, and\n * <em>undefined</em>. If {@code true} then all three states will be\n * cycled through; if {@code false} then only <em>checked</em> and\n * <em>unchecked</em> will be cycled.\n */\n private BooleanProperty allowIndeterminate;\n\n public final void setAllowIndeterminate(boolean value) {\n if(isRadioButton() && value)\n return;\n allowIndeterminateProperty().set(value);\n }\n\n public final boolean isAllowIndeterminate() {\n return allowIndeterminateProperty().get();\n }\n\n public final BooleanProperty allowIndeterminateProperty() {\n if (allowIndeterminate == null) {\n allowIndeterminate =\n new SimpleBooleanProperty(this, \"allowIndeterminate\");\n }\n return allowIndeterminate;\n }\n\n private ObjectProperty<Paint> selectedColor = new SimpleObjectProperty<>();\n public Paint getSelectedColor() {\n return selectedColor.get();\n }\n public ObjectProperty<Paint> selectedColorProperty() {\n return selectedColor;\n }\n public void setSelectedColor(Paint selectedColor) {\n this.selectedColor.set(selectedColor);\n }\n /* *************************************************************************\n * *\n * Methods *\n * *\n **************************************************************************/\n\n /**\n * Toggles the state of the {@code XmCheckBox}. If allowIndeterminate is\n * true, then each invocation of this function will advance the XmCheckBox\n * through the states checked, unchecked, and undefined. If\n * allowIndeterminate is false, then the XmCheckBox will only cycle through\n * the checked and unchecked states, and forcing indeterminate to equal to\n * false.\n */\n public void fire() {\n if (!isDisabled()) {\n if (isAllowIndeterminate()) {\n if (!isSelected() && !isIndeterminate()) {\n setIndeterminate(true);\n } else if (isSelected() && !isIndeterminate()) {\n setSelected(false);\n } else if (isIndeterminate()) {\n setSelected(true);\n setIndeterminate(false);\n }\n } else {\n setSelected(!isSelected());\n setIndeterminate(false);\n }\n// fireEvent(new ActionEvent());\n }\n }\n\n /** {@inheritDoc} */\n @Override protected Skin<?> createDefaultSkin() {\n return new XmCheckBoxSkin(this);\n }\n\n /* *************************************************************************\n * *\n * Stylesheet Handling *\n * *\n **************************************************************************/\n\n private static final String DEFAULT_STYLE_CLASS = \"xm-check-box\";\n private static final PseudoClass PSEUDO_CLASS_DETERMINATE =\n PseudoClass.getPseudoClass(\"determinate\");\n private static final PseudoClass PSEUDO_CLASS_INDETERMINATE =\n PseudoClass.getPseudoClass(\"indeterminate\");\n private static final PseudoClass PSEUDO_CLASS_SELECTED =\n PseudoClass.getPseudoClass(\"selected\");\n\n\n /* *************************************************************************\n * *\n * Accessibility handling *\n * *\n **************************************************************************/\n\n /** {@inheritDoc} */\n @Override\n public Object queryAccessibleAttribute(AccessibleAttribute attribute, Object... parameters) {\n switch (attribute) {\n case SELECTED: return isSelected();\n case INDETERMINATE: return isIndeterminate();\n default: return super.queryAccessibleAttribute(attribute, parameters);\n }\n }\n}" }, { "identifier": "CellUtils", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/CellUtils.java", "snippet": "public class CellUtils {\n private final static StringConverter<?> defaultTreeItemStringConverter =\n new StringConverter<TreeItem<?>>() {\n @Override public String toString(TreeItem<?> treeItem) {\n return (treeItem == null || treeItem.getValue() == null) ?\n \"\" : treeItem.getValue().toString();\n }\n\n @Override public TreeItem<?> fromString(String string) {\n return new TreeItem<>(string);\n }\n };\n\n private final static StringConverter<?> defaultStringConverter = new StringConverter<Object>() {\n @Override public String toString(Object t) {\n return t == null ? null : t.toString();\n }\n\n @Override public Object fromString(String string) {\n return (Object) string;\n }\n };\n\n @SuppressWarnings(\"unchecked\")\n public static <T> StringConverter<TreeItem<T>> defaultTreeItemStringConverter() {\n return (StringConverter<TreeItem<T>>) defaultTreeItemStringConverter;\n }\n\n public static <T> StringConverter<T> defaultStringConverter() {\n return (StringConverter<T>) defaultStringConverter;\n }\n\n public static <T> String getItemText(Cell<T> cell, StringConverter<T> converter) {\n return converter == null ?\n cell.getItem() == null ? \"\" : cell.getItem().toString() :\n converter.toString(cell.getItem());\n }\n\n public static <T> XmSimpleTextField createTextField(final Cell<T> cell, final StringConverter<T> converter) {\n final XmSimpleTextField textField = new XmSimpleTextField(getItemText(cell, converter));\n\n // Use onAction here rather than onKeyReleased (with check for Enter),\n // as otherwise we encounter RT-34685\n textField.setOnAction(event -> {\n if (converter == null) {\n throw new IllegalStateException(\n \"Attempting to convert text input into Object, but provided \"\n + \"StringConverter is null. Be sure to set a StringConverter \"\n + \"in your cell factory.\");\n }\n cell.commitEdit(converter.fromString(textField.getText()));\n event.consume();\n });\n textField.setOnKeyReleased(t -> {\n if (t.getCode() == KeyCode.ESCAPE) {\n cell.cancelEdit();\n t.consume();\n }\n });\n return textField;\n }\n\n public static <T> void startEdit(final Cell<T> cell,\n final StringConverter<T> converter,\n final HBox hbox,\n final Node graphic,\n final TextField textField) {\n if (textField != null) {\n textField.setText(getItemText(cell, converter));\n }\n cell.setText(null);\n\n if (graphic != null) {\n hbox.getChildren().setAll(graphic, textField);\n cell.setGraphic(hbox);\n } else {\n cell.setGraphic(textField);\n }\n\n textField.selectAll();\n\n // requesting focus so that key input can immediately go into the\n // TextField (see RT-28132)\n textField.requestFocus();\n }\n\n}" } ]
import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ObservableValue; import javafx.collections.SetChangeListener; import javafx.css.PseudoClass; import javafx.geometry.Pos; import javafx.scene.control.CheckBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.util.Callback; import javafx.util.StringConverter; import com.xm2013.jfx.control.base.ColorType; import com.xm2013.jfx.control.checkbox.XmCheckBox; import com.xm2013.jfx.control.base.CellUtils; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleBooleanProperty;
6,822
/* * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.xm2013.jfx.control.listview; /** * A class containing a {@link ListCell} implementation that draws a * {@link CheckBox} node inside the cell, optionally with a label to indicate * what the checkbox represents. * * <p>The CheckBoxListCell is rendered with a CheckBox on the left-hand side of * the {@link ListView}, and the text related to the list item taking up all * remaining horizontal space. * * <p>To construct an instance of this class, it is necessary to provide a * {@link Callback} that, given an object of type T, will return a * {@code ObservableValue<Boolean>} that represents whether the given item is * selected or not. This ObservableValue will be bound bidirectionally (meaning * that the CheckBox in the cell will set/unset this property based on user * interactions, and the CheckBox will reflect the state of the * {@code ObservableValue<Boolean>}, if it changes externally). * * <p>Note that the CheckBoxListCell renders the CheckBox 'live', meaning that * the CheckBox is always interactive and can be directly toggled by the user. * This means that it is not necessary that the cell enter its * {@link #editingProperty() editing state} (usually by the user double-clicking * on the cell). A side-effect of this is that the usual editing callbacks * (such as {@link ListView#onEditCommitProperty() on edit commit}) * will <strong>not</strong> be called. If you want to be notified of changes, * it is recommended to directly observe the boolean properties that are * manipulated by the CheckBox.</p> * * @see CheckBox * @see ListCell * @param <T> The type of the elements contained within the ListView. * @since JavaFX 2.2 */ public class XmCheckBoxListCell<T> extends XmListCell<T> { /* ************************************************************************* * * * Static cell factories * * * **************************************************************************/ /** * Creates a cell factory for use in ListView controls. When used in a * ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the * left-hand side of the ListView, with the text related to the list item * taking up all remaining horizontal space. * * @param <T> The type of the elements contained within the ListView. * @param getSelectedProperty A {@link Callback} that, given an object of * type T (which is a value taken out of the * {@code ListView<T>.items} list), * will return an {@code ObservableValue<Boolean>} that represents * whether the given item is selected or not. This ObservableValue will * be bound bidirectionally (meaning that the CheckBox in the cell will * set/unset this property based on user interactions, and the CheckBox * will reflect the state of the ObservableValue, if it changes * externally). * @return A {@link Callback} that will return a ListCell that is able to * work on the type of element contained within the ListView items list. */ public static <T> Callback<ListView<T>, ListCell<T>> forListView( final Callback<T, ObservableValue<Boolean>> getSelectedProperty) { return forListView(getSelectedProperty, CellUtils.<T>defaultStringConverter()); } /** * Creates a cell factory for use in ListView controls. When used in a * ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the * left-hand side of the ListView, with the text related to the list item * taking up all remaining horizontal space. * * @param <T> The type of the elements contained within the ListView. * @param getSelectedProperty A {@link Callback} that, given an object * of type T (which is a value taken out of the * {@code ListView<T>.items} list), * will return an {@code ObservableValue<Boolean>} that represents * whether the given item is selected or not. This ObservableValue will * be bound bidirectionally (meaning that the CheckBox in the cell will * set/unset this property based on user interactions, and the CheckBox * will reflect the state of the ObservableValue, if it changes * externally). * @param converter A StringConverter that, give an object of type T, will * return a String that can be used to represent the object visually. * @return A {@link Callback} that will return a ListCell that is able to * work on the type of element contained within the ListView. */ public static <T> Callback<ListView<T>, ListCell<T>> forListView( final Callback<T, ObservableValue<Boolean>> getSelectedProperty, final StringConverter<T> converter) { return list -> new XmCheckBoxListCell<T>(getSelectedProperty, converter); } /* ************************************************************************* * * * Fields * * * **************************************************************************/ private final XmCheckBox checkBox; private static PseudoClass selected = PseudoClass.getPseudoClass("selected"); private ObservableValue<Boolean> booleanProperty = new SimpleBooleanProperty(); /* ************************************************************************* * * * Constructors * * * **************************************************************************/ /** * Creates a default CheckBoxListCell. */ public XmCheckBoxListCell() { this(null); } /** * Creates a default CheckBoxListCell. * * @param getSelectedProperty A {@link Callback} that will return an * {@code ObservableValue<Boolean>} given an item from the ListView. */ public XmCheckBoxListCell( final Callback<T, ObservableValue<Boolean>> getSelectedProperty) { this(getSelectedProperty, CellUtils.<T>defaultStringConverter()); } /** * Creates a CheckBoxListCell with a custom string converter. * * @param getSelectedProperty A {@link Callback} that will return an * {@code ObservableValue<Boolean>} given an item from the ListView. * @param converter A StringConverter that, given an object of type T, will * return a String that can be used to represent the object visually. */ public XmCheckBoxListCell( Callback<T, ObservableValue<Boolean>> getSelectedProperty, final StringConverter<T> converter) { this.getStyleClass().add("check-box-list-cell"); setSelectedStateCallback(getSelectedProperty); setConverter(converter); this.checkBox = new XmCheckBox(); this.checkBox.setMouseTransparent(true); setAlignment(Pos.CENTER_LEFT); setContentDisplay(ContentDisplay.LEFT); addEventFilter(MouseEvent.MOUSE_CLICKED, e -> { checkBox.setSelected(!checkBox.isSelected()); }); checkBox.selectedProperty().addListener((ob, ov, nv)->{ T item = getItem(); XmListView listView = (XmListView) getListView(); if(nv){ boolean contains = listView.getCheckedValues().contains(item); if(!contains){ listView.addCheckedValue(item); } }else{ listView.getCheckedValues().remove(item); } }); getPseudoClassStates().addListener((SetChangeListener<PseudoClass>) change -> setCheckBoxColor()); listViewProperty().addListener((observable, oldValue, newValue) -> setCheckBoxColor()); itemProperty().addListener((observable, oldValue, newValue) -> { boolean checked = ((XmListView)getListView()).getCheckedValues().contains(newValue); if(checked){ checkBox.setSelected(true); }else{ checkBox.setSelected(false); } }); // by default the graphic is null until the cell stops being empty setGraphic(null); } private void setCheckBoxColor(){ if(getPseudoClassStates().contains(selected)){
/* * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.xm2013.jfx.control.listview; /** * A class containing a {@link ListCell} implementation that draws a * {@link CheckBox} node inside the cell, optionally with a label to indicate * what the checkbox represents. * * <p>The CheckBoxListCell is rendered with a CheckBox on the left-hand side of * the {@link ListView}, and the text related to the list item taking up all * remaining horizontal space. * * <p>To construct an instance of this class, it is necessary to provide a * {@link Callback} that, given an object of type T, will return a * {@code ObservableValue<Boolean>} that represents whether the given item is * selected or not. This ObservableValue will be bound bidirectionally (meaning * that the CheckBox in the cell will set/unset this property based on user * interactions, and the CheckBox will reflect the state of the * {@code ObservableValue<Boolean>}, if it changes externally). * * <p>Note that the CheckBoxListCell renders the CheckBox 'live', meaning that * the CheckBox is always interactive and can be directly toggled by the user. * This means that it is not necessary that the cell enter its * {@link #editingProperty() editing state} (usually by the user double-clicking * on the cell). A side-effect of this is that the usual editing callbacks * (such as {@link ListView#onEditCommitProperty() on edit commit}) * will <strong>not</strong> be called. If you want to be notified of changes, * it is recommended to directly observe the boolean properties that are * manipulated by the CheckBox.</p> * * @see CheckBox * @see ListCell * @param <T> The type of the elements contained within the ListView. * @since JavaFX 2.2 */ public class XmCheckBoxListCell<T> extends XmListCell<T> { /* ************************************************************************* * * * Static cell factories * * * **************************************************************************/ /** * Creates a cell factory for use in ListView controls. When used in a * ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the * left-hand side of the ListView, with the text related to the list item * taking up all remaining horizontal space. * * @param <T> The type of the elements contained within the ListView. * @param getSelectedProperty A {@link Callback} that, given an object of * type T (which is a value taken out of the * {@code ListView<T>.items} list), * will return an {@code ObservableValue<Boolean>} that represents * whether the given item is selected or not. This ObservableValue will * be bound bidirectionally (meaning that the CheckBox in the cell will * set/unset this property based on user interactions, and the CheckBox * will reflect the state of the ObservableValue, if it changes * externally). * @return A {@link Callback} that will return a ListCell that is able to * work on the type of element contained within the ListView items list. */ public static <T> Callback<ListView<T>, ListCell<T>> forListView( final Callback<T, ObservableValue<Boolean>> getSelectedProperty) { return forListView(getSelectedProperty, CellUtils.<T>defaultStringConverter()); } /** * Creates a cell factory for use in ListView controls. When used in a * ListView, the {@link XmCheckBoxListCell} is rendered with a CheckBox on the * left-hand side of the ListView, with the text related to the list item * taking up all remaining horizontal space. * * @param <T> The type of the elements contained within the ListView. * @param getSelectedProperty A {@link Callback} that, given an object * of type T (which is a value taken out of the * {@code ListView<T>.items} list), * will return an {@code ObservableValue<Boolean>} that represents * whether the given item is selected or not. This ObservableValue will * be bound bidirectionally (meaning that the CheckBox in the cell will * set/unset this property based on user interactions, and the CheckBox * will reflect the state of the ObservableValue, if it changes * externally). * @param converter A StringConverter that, give an object of type T, will * return a String that can be used to represent the object visually. * @return A {@link Callback} that will return a ListCell that is able to * work on the type of element contained within the ListView. */ public static <T> Callback<ListView<T>, ListCell<T>> forListView( final Callback<T, ObservableValue<Boolean>> getSelectedProperty, final StringConverter<T> converter) { return list -> new XmCheckBoxListCell<T>(getSelectedProperty, converter); } /* ************************************************************************* * * * Fields * * * **************************************************************************/ private final XmCheckBox checkBox; private static PseudoClass selected = PseudoClass.getPseudoClass("selected"); private ObservableValue<Boolean> booleanProperty = new SimpleBooleanProperty(); /* ************************************************************************* * * * Constructors * * * **************************************************************************/ /** * Creates a default CheckBoxListCell. */ public XmCheckBoxListCell() { this(null); } /** * Creates a default CheckBoxListCell. * * @param getSelectedProperty A {@link Callback} that will return an * {@code ObservableValue<Boolean>} given an item from the ListView. */ public XmCheckBoxListCell( final Callback<T, ObservableValue<Boolean>> getSelectedProperty) { this(getSelectedProperty, CellUtils.<T>defaultStringConverter()); } /** * Creates a CheckBoxListCell with a custom string converter. * * @param getSelectedProperty A {@link Callback} that will return an * {@code ObservableValue<Boolean>} given an item from the ListView. * @param converter A StringConverter that, given an object of type T, will * return a String that can be used to represent the object visually. */ public XmCheckBoxListCell( Callback<T, ObservableValue<Boolean>> getSelectedProperty, final StringConverter<T> converter) { this.getStyleClass().add("check-box-list-cell"); setSelectedStateCallback(getSelectedProperty); setConverter(converter); this.checkBox = new XmCheckBox(); this.checkBox.setMouseTransparent(true); setAlignment(Pos.CENTER_LEFT); setContentDisplay(ContentDisplay.LEFT); addEventFilter(MouseEvent.MOUSE_CLICKED, e -> { checkBox.setSelected(!checkBox.isSelected()); }); checkBox.selectedProperty().addListener((ob, ov, nv)->{ T item = getItem(); XmListView listView = (XmListView) getListView(); if(nv){ boolean contains = listView.getCheckedValues().contains(item); if(!contains){ listView.addCheckedValue(item); } }else{ listView.getCheckedValues().remove(item); } }); getPseudoClassStates().addListener((SetChangeListener<PseudoClass>) change -> setCheckBoxColor()); listViewProperty().addListener((observable, oldValue, newValue) -> setCheckBoxColor()); itemProperty().addListener((observable, oldValue, newValue) -> { boolean checked = ((XmListView)getListView()).getCheckedValues().contains(newValue); if(checked){ checkBox.setSelected(true); }else{ checkBox.setSelected(false); } }); // by default the graphic is null until the cell stops being empty setGraphic(null); } private void setCheckBoxColor(){ if(getPseudoClassStates().contains(selected)){
checkBox.setColorType(ColorType.other(Color.WHITE));
0
2023-10-17 08:57:08+00:00
8k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/asm/inst/STRExecutor.java
[ { "identifier": "DataMode", "path": "src/main/java/fr/dwightstudio/jarmemu/asm/DataMode.java", "snippet": "public enum DataMode {\n HALF_WORD,\n BYTE;\n\n @Override\n public String toString() {\n return name().substring(0,1);\n }\n\n public static DataMode customValueOf(String name) {\n if (name == null) {\n throw new IllegalArgumentException();\n } else if (name.equalsIgnoreCase(\"H\")) {\n return HALF_WORD;\n } else if (name.equalsIgnoreCase(\"B\")) {\n return BYTE;\n } else {\n throw new IllegalArgumentException();\n }\n }\n}" }, { "identifier": "UpdateMode", "path": "src/main/java/fr/dwightstudio/jarmemu/asm/UpdateMode.java", "snippet": "public enum UpdateMode {\n\n FA, IB,\n EA, IA,\n FD, DB,\n ED, DA\n\n}" }, { "identifier": "IllegalDataWritingASMException", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/exceptions/IllegalDataWritingASMException.java", "snippet": "public class IllegalDataWritingASMException extends ExecutionASMException{\n}" }, { "identifier": "MemoryAccessMisalignedASMException", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/exceptions/MemoryAccessMisalignedASMException.java", "snippet": "public class MemoryAccessMisalignedASMException extends ExecutionASMException {\n}" }, { "identifier": "Register", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/obj/Register.java", "snippet": "public class Register {\n\n private final IntegerProperty dataProperty;\n\n public Register() {\n this.dataProperty = new SimpleIntegerProperty(0);\n }\n\n public int getData() {\n return dataProperty.get();\n }\n\n public void setData(int data) throws IllegalArgumentException {\n this.dataProperty.set(data);\n }\n\n public boolean get(int index) throws IllegalArgumentException {\n if (index >= 32) throw new IllegalArgumentException(\"Invalid index: \" + index);\n\n int data = dataProperty.get();\n\n return ((data >> index) & 1) == 1;\n }\n\n public void set(int index, boolean value) {\n if (index >= 32) throw new IllegalArgumentException(\"Invalid index: \" + index);\n\n int data = dataProperty.get();\n\n if (value) {\n data |= (1 << index); // set a bit to 1\n } else {\n data &= ~(1 << index); // set a bit to 0\n }\n\n dataProperty.set(data);\n }\n\n public void add(int value) {\n dataProperty.set(dataProperty.get() + value);\n }\n\n public boolean isPSR() {\n return false;\n }\n\n public IntegerProperty getDataProperty() {\n return dataProperty;\n }\n}" }, { "identifier": "StateContainer", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/obj/StateContainer.java", "snippet": "public class StateContainer {\n\n public static final int DEFAULT_STACK_ADDRESS = 65536;\n public static final int DEFAULT_SYMBOLS_ADDRESS = 0;\n public static final int MAX_NESTING_COUNT = 1024;\n private static final Pattern SPECIAL_VALUE_PATTERN = Pattern.compile(\n \"(?i)\"\n + \"(?<VALUE>\"\n + \"\\\\b0B\\\\w+\"\n + \"|\\\\b0X\\\\w+\"\n + \"|\\\\b00\\\\w+\"\n + \"|'.'\"\n + \")\" +\n \"(?-i)\"\n );\n\n // ASM\n private final ArrayList<HashMap<String, Integer>> consts; // Indice de fichier -> Nom -> Constantes\n private final ArrayList<HashMap<String, Integer>> data; // Indice de fichier -> Nom -> Données ajoutées dans la mémoire par directive\n private final HashMap<String, Integer> pseudoData; // Code -> Données ajoutées dans la mémoire par pseudo-op\n private final ArrayList<HashMap<String, Integer>> labels; // Indice de fichier -> Label -> Position dans la mémoire\n private final HashMap<String, Integer> globals; // Symbols globaux -> Indice de fichier\n private int nestingCount;\n private int lastAddressROData;\n private int currentfileIndex;\n\n // Registers\n public static final int REGISTER_NUMBER = 16;\n private final Register[] registers;\n private final PSR cpsr;\n private final PSR spsr;\n\n // Memory\n private final MemoryAccessor memory;\n private final int stackAddress;\n private final int symbolsAddress;\n\n public StateContainer(int stackAddress, int symbolsAddress) {\n this.stackAddress = stackAddress;\n this.symbolsAddress = symbolsAddress;\n\n // ASM\n labels = new ArrayList<>();\n consts = new ArrayList<>();\n data = new ArrayList<>();\n pseudoData = new HashMap<>();\n globals = new HashMap<>();\n nestingCount = 0;\n lastAddressROData = 0;\n currentfileIndex = 0;\n\n // Initializing registers\n cpsr = new PSR();\n spsr = new PSR();\n\n this.registers = new Register[REGISTER_NUMBER];\n clearRegisters();\n clearAndInitFiles(1);\n\n // Initializing memory\n this.memory = new MemoryAccessor();\n }\n\n public StateContainer() {\n this(DEFAULT_STACK_ADDRESS,DEFAULT_SYMBOLS_ADDRESS);\n }\n\n public StateContainer(StateContainer stateContainer) {\n this(stateContainer.getStackAddress(), stateContainer.getSymbolsAddress());\n\n clearAndInitFiles(0);\n\n stateContainer.consts.forEach(map -> this.consts.add(new HashMap<>(map)));\n stateContainer.labels.forEach(map -> this.labels.add(new HashMap<>(map)));\n stateContainer.data.forEach(map -> this.data.add(new HashMap<>(map)));\n\n this.pseudoData.putAll(stateContainer.pseudoData);\n this.globals.putAll(stateContainer.globals);\n this.currentfileIndex = stateContainer.currentfileIndex;\n\n for (int i = 0; i < REGISTER_NUMBER; i++) {\n registers[i].setData(stateContainer.getRegister(i).getData());\n }\n\n cpsr.setData(stateContainer.getCPSR().getData());\n spsr.setData(stateContainer.spsr.getData());\n }\n\n public void clearRegisters() {\n for (int i = 0; i < REGISTER_NUMBER; i++) {\n if (registers[i] != null) {\n registers[i].setData(0);\n } else {\n registers[i] = new Register();\n }\n\n if (i == RegisterUtils.SP.getN()) {\n registers[i].setData(stackAddress);\n }\n }\n\n cpsr.setData(0);\n spsr.setData(0);\n }\n\n public int evalWithAccessibleConsts(String expString) {\n try {\n ExpressionBuilder builder = new ExpressionBuilder(preEval(expString));\n\n consts.forEach(map -> builder.variables(map.keySet()));\n\n Expression exp = builder.build();\n\n for (Map.Entry<String, Integer> entry : consts.get(currentfileIndex).entrySet()) {\n exp.setVariable(entry.getKey(), (double) entry.getValue());\n }\n\n return (int) exp.evaluate();\n } catch (IllegalArgumentException exception) {\n throw new SyntaxASMException(\"Malformed math expression '\" + expString + \"'\");\n }\n }\n\n public int evalWithAll(String expString) {\n try {\n ExpressionBuilder builder = new ExpressionBuilder(preEval(expString));\n\n consts.forEach(map -> builder.variables(map.keySet()));\n data.forEach(map -> builder.variables(map.keySet()));\n\n Expression exp = builder.build();\n\n for (int i = 0 ; i < consts.size() ; i++) {\n for (Map.Entry<String, Integer> entry : consts.get(i).entrySet()) {\n exp.setVariable(entry.getKey(), (double) entry.getValue());\n }\n\n for (Map.Entry<String, Integer> entry : data.get(i).entrySet()) {\n exp.setVariable(entry.getKey(), (double) entry.getValue());\n }\n }\n\n return (int) Math.floor(exp.evaluate());\n } catch (IllegalArgumentException exception) {\n throw new SyntaxASMException(\"Malformed math expression '\" + expString + \"' (\" + exception.getMessage() + \")\");\n }\n }\n\n public int evalWithAccessible(String expString) {\n try {\n ExpressionBuilder builder = new ExpressionBuilder(preEval(expString));\n\n builder.variables(getAccessibleConsts().keySet());\n builder.variables(getAccessibleData().keySet());\n\n Expression exp = builder.build();\n\n for (Map.Entry<String, Integer> entry : getAccessibleConsts().entrySet()) {\n exp.setVariable(entry.getKey(), (double) entry.getValue());\n }\n\n for (Map.Entry<String, Integer> entry : getAccessibleData().entrySet()) {\n exp.setVariable(entry.getKey(), (double) entry.getValue());\n }\n\n return (int) Math.floor(exp.evaluate());\n } catch (IllegalArgumentException exception) {\n throw new SyntaxASMException(\"Malformed math expression '\" + expString + \"' (\" + exception.getMessage() + \")\");\n }\n }\n\n private String preEval(String s) {\n\n if (s.startsWith(\"=\") || s.startsWith(\"#\")) s = s.substring(1);\n\n return SPECIAL_VALUE_PATTERN.matcher(s).replaceAll(matchResult -> {\n String valueString = matchResult.group(\"VALUE\").toUpperCase();\n try {\n if (valueString.startsWith(\"0B\")) {\n valueString = valueString.substring(2).strip();\n\n return String.valueOf(Integer.parseUnsignedInt(valueString, 2));\n } else if (valueString.startsWith(\"0X\")) {\n valueString = valueString.substring(2).strip();\n\n return String.valueOf(Integer.parseUnsignedInt(valueString, 16));\n } else if (valueString.startsWith(\"00\")) {\n valueString = valueString.substring(2).strip();\n\n return String.valueOf(Integer.parseUnsignedInt(valueString, 8));\n } else if (valueString.startsWith(\"'\")) {\n return String.valueOf((int) matchResult.group(\"VALUE\").charAt(1));\n }\n } catch (NumberFormatException exception) {\n throw new SyntaxASMException(\"Malformed math expression '\" + valueString + \"' (\" + exception.getMessage() + \")\");\n }\n return valueString;\n }).toUpperCase();\n\n }\n\n public int getStackAddress() {\n return stackAddress;\n }\n\n public int getSymbolsAddress() {\n return symbolsAddress;\n }\n\n /**\n * @return une liste non modifiable des variables globales.\n */\n public List<String> getGlobals() {\n return globals.keySet().stream().toList();\n }\n\n /**\n * Ajoute une variable globale.\n *\n * @param global la variable globale\n * @param fileIndex l'indice du fichier de la variable globale\n */\n public void addGlobal(String global, int fileIndex) {\n this.globals.put(global, fileIndex);\n }\n\n /**\n * @param global le nom de la variable globale\n * @return l'indice du fichier de la variable globale\n */\n public int getGlobal(String global) {\n return globals.get(global);\n }\n\n public void clearGlobals() {\n this.globals.clear();\n }\n\n public Register[] getAllRegisters() {\n return new Register[] {\n registers[0],\n registers[1],\n registers[2],\n registers[3],\n registers[4],\n registers[5],\n registers[6],\n registers[7],\n registers[8],\n registers[9],\n registers[10],\n registers[11],\n registers[12],\n registers[13],\n registers[14],\n registers[15],\n cpsr,\n spsr\n };\n }\n\n /**\n * @return le nombre de branches actives\n */\n public int getNestingCount() {\n return nestingCount;\n }\n\n /**\n * Met à jour le compteur de branche en ajoutant 1\n */\n public void branch() {\n this.nestingCount++;\n }\n\n /**\n * Met à jour le compteur de branche en retirant 1\n */\n public void merge() {\n this.nestingCount--;\n if (this.nestingCount < 0) this.nestingCount = 0;\n }\n\n public int getLastAddressROData() {\n return lastAddressROData;\n }\n\n public void setLastAddressROData(int lastAddressROData) {\n this.lastAddressROData = lastAddressROData;\n }\n\n /**\n * @return les constantes accessibles dans le fichier actuel\n */\n public AccessibleValueMap getAccessibleConsts() {\n return new AccessibleValueMap(consts, globals, currentfileIndex);\n }\n\n /**\n * @return les données accessibles dans le fichier actuel\n */\n public AccessibleValueMap getAccessibleData() {\n return new AccessibleValueMap(data, globals, currentfileIndex);\n }\n\n /**\n * @return les données définies dans le fichier actuel (exclusion des globals)\n */\n public HashMap<String, Integer> getRestrainedData() {\n return data.get(currentfileIndex);\n }\n\n /**\n * @return les pseudo données générées par directive (tous fichiers confondus)\n */\n public HashMap<String, Integer> getPseudoData() {\n return pseudoData;\n }\n\n /**\n * @return les labels accessibles dans le fichier actuel\n */\n public AccessibleValueMap getAccessibleLabels() {\n return new AccessibleValueMap(labels, globals, currentfileIndex);\n }\n\n /**\n * @return les labels définis dans le fichier actuel (exclusion des globals)\n */\n public HashMap<String, Integer> getRestrainedLabels() {\n return labels.get(currentfileIndex);\n }\n\n /**\n * @return les labels répartis dans les fichiers\n */\n public ArrayList<HashMap<String, Integer>> getLabelsInFiles() {\n return labels;\n }\n\n /**\n * @return tous les labels (tous fichiers confondus)\n */\n public MultiValuedMap<String, FilePos> getAllLabels() {\n return new AllLabelsMap(labels);\n }\n\n /**\n * Initialise les variables pour un nombre de fichiers spécifique.\n *\n * @param size le nombre de fichiers\n */\n public void clearAndInitFiles(int size) {\n labels.clear();\n consts.clear();\n data.clear();\n\n for (int i = 0 ; i < size ; i++) {\n labels.add(new HashMap<>());\n consts.add(new HashMap<>());\n data.add(new HashMap<>());\n }\n }\n\n /**\n * Modifie le fichier courant.\n *\n * @param i l'indice du fichier courant\n */\n public void setFileIndex(int i) {\n currentfileIndex = i;\n }\n\n /**\n * @return l'indice du fichier courant\n */\n public int getCurrentFileIndex() {\n return currentfileIndex;\n }\n\n public Register getRegister(int i) {\n return registers[i];\n }\n\n public Register getFP() {\n return registers[RegisterUtils.FP.getN()];\n }\n\n public Register getIP() {\n return registers[RegisterUtils.IP.getN()];\n }\n\n public Register getSP() {\n return registers[RegisterUtils.SP.getN()];\n }\n\n public Register getPC() {\n return registers[RegisterUtils.PC.getN()];\n }\n\n public Register getLR() {\n return registers[RegisterUtils.LR.getN()];\n }\n\n public PSR getCPSR() {\n return cpsr;\n }\n\n public PSR getSPSR() {\n return spsr;\n }\n\n public MemoryAccessor getMemory() {\n return memory;\n }\n\n public Register[] getRegisters() {\n return registers;\n }\n}" }, { "identifier": "AddressParser", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/parse/args/AddressParser.java", "snippet": "public class AddressParser implements ArgumentParser<AddressParser.UpdatableInteger> {\n protected static HashMap<StateContainer, Integer> updateValue = new HashMap<>();\n\n public static void reset(StateContainer stateContainer) {\n updateValue.remove(stateContainer);\n }\n\n @Override\n public UpdatableInteger parse(@NotNull StateContainer stateContainer, @NotNull String string) {\n if (string.startsWith(\"*\")) {\n String symbol = string.substring(1).strip().toUpperCase();\n int rtn = stateContainer.getPseudoData().get(symbol);\n return new UpdatableInteger(rtn, stateContainer, false, false, null);\n } else if (!string.startsWith(\"[\")) {\n throw new SyntaxASMException(\"Invalid address '\" + string + \"'\");\n }\n\n boolean updateNow = string.endsWith(\"!\");\n\n if (updateNow) string = string.substring(0, string.length() - 1);\n\n if (string.endsWith(\"]\")) {\n String mem = string.substring(1, string.length() - 1);\n String[] mems = mem.split(\",\");\n\n mems = Arrays.stream(mems).map(String::strip).toArray(String[]::new);\n\n Register reg = ArgumentParsers.REGISTER.parse(stateContainer, mems[0]);\n\n if (mems.length == 1) {\n return new UpdatableInteger(reg.getData(),\n stateContainer,\n true,\n updateNow,\n reg);\n\n } else if (mems.length == 2) {\n if (mems[1].startsWith(\"#\")) {\n return new UpdatableInteger(reg.getData() + ArgumentParsers.IMM.parse(stateContainer, mems[1]),\n stateContainer,\n false,\n updateNow,\n reg);\n } else {\n return new UpdatableInteger(reg.getData() + ArgumentParsers.REGISTER.parse(stateContainer, mems[1]).getData(),\n stateContainer,\n false,\n updateNow,\n reg);\n }\n\n } else if (mems.length == 3) {\n ShiftParser.ShiftFunction sf = ArgumentParsers.SHIFT.parse(stateContainer, mems[2]);\n return new UpdatableInteger(reg.getData() + sf.apply(ArgumentParsers.REGISTER.parse(stateContainer, mems[1]).getData()),\n stateContainer,\n false,\n updateNow,\n reg);\n } else {\n throw new SyntaxASMException(\"Invalid address '\" + string + \"'\");\n }\n\n } else {\n throw new SyntaxASMException(\"Invalid address '\" + string + \"'\");\n }\n }\n\n @Override\n public AddressParser.UpdatableInteger none() {\n return null;\n }\n\n public static final class UpdatableInteger {\n\n private final int integer;\n private final StateContainer stateContainer;\n private final Register register;\n private boolean update;\n\n /**\n * Crée un UpdatableInteger qui s'occupe de mettre à jour\n *\n * @param integer l'entier contenu\n * @param stateContainer le conteneur d'état associé à cet Updatable\n * @param update vrai si on autorise l'update du registre à l'appel de update()\n * @param updateNow si l'update doit se faire à la création de l'objet\n * @param register le registre à appeler\n */\n public UpdatableInteger(int integer, StateContainer stateContainer, boolean update, boolean updateNow, Register register) {\n this.integer = integer;\n this.register = register;\n this.update = update;\n this.stateContainer = stateContainer;\n\n if (updateNow) register.setData(integer);\n }\n\n public int toInt() {\n return integer;\n }\n\n public void update() {\n if (register == null) return;\n if (update && updateValue.containsKey(stateContainer)) register.setData(updateValue.get(stateContainer));\n update = false;\n }\n }\n}" }, { "identifier": "ShiftParser", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/parse/args/ShiftParser.java", "snippet": "public class ShiftParser implements ArgumentParser<ShiftParser.ShiftFunction> {\n @Override\n public ShiftParser.ShiftFunction parse(@NotNull StateContainer stateContainer, @NotNull String string) {\n try {\n if (string.length() <= 3) {\n if (string.equals(\"RRX\")) {\n Function<Integer, Integer> func = (i -> {\n i = Integer.rotateRight(i, 1);\n boolean c = ((i >> 31) & 1) == 1;\n if (stateContainer.getCPSR().getC()) {\n i |= (1 << 31); // set a bit to 1\n } else {\n i &= ~(1 << 31); // set a bit to 0\n }\n\n stateContainer.getCPSR().setC(c);\n\n return i;\n });\n return new ShiftFunction(stateContainer, func);\n } else {\n throw new SyntaxASMException(\"Invalid shift expression '\" + string + \"'\");\n }\n }\n\n String type = string.substring(0, 3);\n String shift = string.substring(3).strip();\n int value = ArgumentParsers.IMM_OR_REGISTER.parse(stateContainer, shift);\n\n Function<Integer,Integer> func = switch (type) {\n case \"LSL\" -> {\n if (value < 0 || value > 31)\n throw new SyntaxASMException(\"Invalid shift value '\" + shift + \"', expected value between 0 and 31 included\");\n yield (i -> i << value);\n }\n case \"LSR\" -> {\n if (value < 1 || value > 32)\n throw new SyntaxASMException(\"Invalid shift value '\" + shift + \"', expected value between 1 and 32 included\");\n yield (i -> i >>> value);\n }\n case \"ASR\" -> {\n if (value < 1 || value > 32)\n throw new SyntaxASMException(\"Invalid shift value '\" + shift + \"', expected value between 1 and 32 included\");\n yield (i -> i >> value);\n }\n case \"ROR\" -> {\n if (value < 1 || value > 31)\n throw new SyntaxASMException(\"Invalid shift value '\" + shift + \"', expected value between 1 and 31 included\");\n yield (i -> Integer.rotateRight(i, value));\n }\n default -> throw new SyntaxASMException(\"Invalid shift expression '\" + string + \"'\");\n };\n\n return new ShiftFunction(stateContainer, func);\n\n } catch (IndexOutOfBoundsException exception) {\n throw new SyntaxASMException(\"Invalid shift expression '\" + string + \"'\");\n }\n }\n\n public static class ShiftFunction {\n\n private final StateContainer stateContainer;\n private final Function<Integer, Integer> shift;\n private boolean called;\n\n public ShiftFunction(StateContainer stateContainer, Function<Integer, Integer> shift) {\n this.stateContainer = stateContainer;\n this.shift = shift;\n this.called = false;\n }\n\n public final int apply(int i) {\n if (called) throw new IllegalStateException(\"ShiftFunctions are single-use functions\");\n int rtn = this.shift.apply(i);\n AddressParser.updateValue.put(stateContainer, rtn);\n called = true;\n return rtn;\n }\n }\n\n @Override\n public ShiftParser.ShiftFunction none() {\n return new ShiftFunction(new StateContainer(), (i -> i));\n }\n}" } ]
import fr.dwightstudio.jarmemu.sim.parse.args.ShiftParser; import fr.dwightstudio.jarmemu.asm.DataMode; import fr.dwightstudio.jarmemu.asm.UpdateMode; import fr.dwightstudio.jarmemu.sim.exceptions.IllegalDataWritingASMException; import fr.dwightstudio.jarmemu.sim.exceptions.MemoryAccessMisalignedASMException; import fr.dwightstudio.jarmemu.sim.obj.Register; import fr.dwightstudio.jarmemu.sim.obj.StateContainer; import fr.dwightstudio.jarmemu.sim.parse.args.AddressParser;
6,094
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * 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.asm.inst; public class STRExecutor implements InstructionExecutor<Register, AddressParser.UpdatableInteger, Integer, ShiftParser.ShiftFunction> { @Override
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * 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.asm.inst; public class STRExecutor implements InstructionExecutor<Register, AddressParser.UpdatableInteger, Integer, ShiftParser.ShiftFunction> { @Override
public void execute(StateContainer stateContainer, boolean forceExecution, boolean updateFlags, DataMode dataMode, UpdateMode updateMode, Register arg1, AddressParser.UpdatableInteger arg2, Integer arg3, ShiftParser.ShiftFunction arg4) {
1
2023-10-17 18:22:09+00:00
8k
GTNewHorizons/FarmingForEngineers
src/main/java/com/guigs44/farmingforengineers/block/BlockMarket.java
[ { "identifier": "FarmingForEngineers", "path": "src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java", "snippet": "@Mod(\n modid = FarmingForEngineers.MOD_ID,\n name = \"Farming for Engineers\",\n dependencies = \"after:mousetweaks[2.8,);after:forestry;after:agricraft\")\n// @Mod.EventBusSubscriber\npublic class FarmingForEngineers {\n\n public static final String MOD_ID = \"farmingforengineers\";\n\n @Mod.Instance(MOD_ID)\n public static FarmingForEngineers instance;\n\n @SidedProxy(\n clientSide = \"com.guigs44.farmingforengineers.client.ClientProxy\",\n serverSide = \"com.guigs44.farmingforengineers.CommonProxy\")\n public static CommonProxy proxy;\n\n public static final Logger logger = LogManager.getLogger();\n\n public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) {\n\n @Override\n public Item getTabIconItem() {\n return Item.getItemFromBlock(FarmingForEngineers.blockMarket);\n }\n };\n\n public static File configDir;\n\n public static Block blockMarket;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n configDir = new File(event.getModConfigurationDirectory(), \"FarmingForEngineers\");\n if (!configDir.exists() && !configDir.mkdirs()) {\n throw new RuntimeException(\"Couldn't create Farming for Engineers configuration directory\");\n }\n\n Configuration config = new Configuration(new File(configDir, \"FarmingForEngineers.cfg\"));\n config.load();\n ModConfig.preInit(config);\n\n proxy.preInit(event);\n\n if (config.hasChanged()) {\n config.save();\n }\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n NetworkHandler.init();\n NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());\n\n new VanillaAddon();\n buildSoftDependProxy(Compat.HARVESTCRAFT, \"com.guigs44.farmingforengineers.compat.HarvestcraftAddon\");\n buildSoftDependProxy(Compat.FORESTRY, \"com.guigs44.farmingforengineers.compat.ForestryAddon\");\n buildSoftDependProxy(Compat.AGRICRAFT, \"com.guigs44.farmingforengineers.compat.AgriCraftAddon\");\n buildSoftDependProxy(Compat.BIOMESOPLENTY, \"com.guigs44.farmingforengineers.compat.BiomesOPlentyAddon\");\n buildSoftDependProxy(Compat.NATURA, \"com.guigs44.farmingforengineers.compat.NaturaAddon\");\n\n ModRecipes.init();\n MarketRegistry.INSTANCE.load(configDir);\n\n EntityRegistry.registerModEntity(EntityMerchant.class, \"merchant\", 0, this, 64, 3, true);\n\n proxy.init(event);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {}\n\n @Mod.EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n event.registerServerCommand(new CommandFarmingForEngineers());\n }\n\n // @SubscribeEvent\n // public static void registerBlocks(RegistryEvent.Register<Block> event) {\n // event.getRegistry().registerAll((ModBlocks.market = new BlockMarket()));\n // }\n\n // @SubscribeEvent\n // public static void registerItems(RegistryEvent.Register<Item> event) {\n // event.getRegistry().registerAll(new\n // ItemBlock(ModBlocks.market).setRegistryName(ModBlocks.market.getRegistryName()));\n // }\n\n @SubscribeEvent\n public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) {\n if (AbstractRegistry.registryErrors.size() > 0) {\n event.player.addChatMessage(\n ChatComponentBuilder.of(\"There were errors loading the Farming for Engineers registries:\").build());\n for (String error : AbstractRegistry.registryErrors) {\n event.player.addChatMessage(ChatComponentBuilder.of(\"* \" + error).build());\n }\n }\n }\n\n private Optional<?> buildSoftDependProxy(String modId, String className) {\n if (Loader.isModLoaded(modId)) {\n try {\n Class<?> clz = Class.forName(className, true, Loader.instance().getModClassLoader());\n return Optional.ofNullable(clz.newInstance());\n } catch (Exception e) {\n return Optional.empty();\n }\n }\n return Optional.empty();\n }\n}" }, { "identifier": "MarketBlockRenderer", "path": "src/main/java/com/guigs44/farmingforengineers/client/render/block/MarketBlockRenderer.java", "snippet": "public class MarketBlockRenderer implements ISimpleBlockRenderingHandler {\n\n public static final int RENDER_ID = RenderingRegistry.getNextAvailableRenderId();\n private static final TileMarket tileEntity = new TileMarket();\n\n @Override\n public void renderInventoryBlock(Block block, int metadata, int modelId, RenderBlocks renderer) {\n GL11.glPushMatrix();\n GL11.glScalef(0.7f, 0.7f, 0.7f);\n TileEntityRendererDispatcher.instance.renderTileEntityAt(tileEntity, 0, -0.5, 0, 0);\n GL11.glPopMatrix();\n }\n\n @Override\n public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId,\n RenderBlocks renderer) {\n return false;\n }\n\n @Override\n public boolean shouldRender3DInInventory(int modelId) {\n return true;\n }\n\n @Override\n public int getRenderId() {\n return RENDER_ID;\n }\n}" }, { "identifier": "EntityMerchant", "path": "src/main/java/com/guigs44/farmingforengineers/entity/EntityMerchant.java", "snippet": "public class EntityMerchant extends EntityCreature implements INpc {\n\n public enum SpawnAnimationType {\n MAGIC,\n FALLING,\n DIGGING\n }\n\n private static final Random rand = new Random();\n public static final String[] NAMES = new String[] { \"Swap-O-Matic\", \"Emerald Muncher\", \"Back Alley Dealer\",\n \"Weathered Salesperson\" };\n\n // private BlockPos marketPos;\n private int marketX;\n private int marketY;\n private int marketZ;\n private EnumFacing facing;\n private boolean spawnDone;\n private SpawnAnimationType spawnAnimation = SpawnAnimationType.MAGIC;\n\n // private BlockPos marketEntityPos;\n private int diggingAnimation;\n // private IBlockState diggingBlockState;\n\n public EntityMerchant(World world) {\n super(world);\n setSize(0.6f, 1.95f);\n this.tasks.addTask(0, new EntityAISwimming(this));\n this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityZombie.class, 8f, 0.6, 0.6));\n this.tasks.addTask(5, new EntityAIMerchant(this, 0.6));\n }\n\n @Override\n protected void entityInit() {\n super.entityInit();\n }\n\n @Override\n protected void applyEntityAttributes() {\n super.applyEntityAttributes();\n getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5);\n }\n\n @Override\n public boolean interact(EntityPlayer player) {\n if (isMarketValid()) {\n player.openGui(\n FarmingForEngineers.MOD_ID,\n GuiHandler.MARKET,\n worldObj,\n (int) marketX,\n (int) marketY,\n (int) marketZ);\n return true;\n }\n return super.interact(player);\n }\n\n @Override\n public void writeEntityToNBT(NBTTagCompound compound) {\n super.writeEntityToNBT(compound);\n // I wonder if using an integer won't be a problem\n compound.setInteger(\"MarketPosX\", marketX);\n compound.setInteger(\"MarketPosY\", marketY);\n compound.setInteger(\"MarketPosZ\", marketZ);\n\n // if(facing != null) {\n // compound.setByte(\"Facing\", (byte) facing.);\n // }\n compound.setBoolean(\"SpawnDone\", spawnDone);\n compound.setByte(\"SpawnAnimation\", (byte) spawnAnimation.ordinal());\n }\n\n @Override\n public void readEntityFromNBT(NBTTagCompound compound) {\n super.readEntityFromNBT(compound);\n if (!compound.hasKey(\"CustomName\")) {\n setCustomNameTag(NAMES[rand.nextInt(NAMES.length)]);\n }\n if (compound.hasKey(\"MarketPosX\")) {\n setMarket(marketX, marketY, marketZ, EnumFacing.getFront(compound.getByte(\"Facing\")));\n }\n spawnDone = compound.getBoolean(\"SpawnDone\");\n spawnAnimation = SpawnAnimationType.values()[compound.getByte(\"SpawnAnimation\")];\n }\n\n @Override\n protected boolean canDespawn() {\n return false;\n }\n\n @Override\n protected String getLivingSound() {\n return \"mob.villager.ambient\";\n } // TODO: Figure out what is the correct string\n\n @Override\n protected String getHurtSound() {\n return \"mob.villager.hit\";\n } // Works\n\n @Override\n protected String getDeathSound() {\n return \"mob.villager.death\";\n }// works\n\n @Override\n public void onEntityUpdate() {\n super.onEntityUpdate();\n if (!worldObj.isRemote) {\n if (ticksExisted % 20 == 0) {\n if (!isMarketValid()) {\n worldObj.setEntityState(this, (byte) 12);\n setDead();\n }\n }\n }\n\n if (!spawnDone && spawnAnimation == SpawnAnimationType.DIGGING) {\n worldObj.setEntityState(this, (byte) 13);\n spawnDone = true;\n }\n if (diggingAnimation > 0) {\n diggingAnimation--;\n for (int i = 0; i < 4; i++) {\n int stateId = 0;\n\n // Block.getStateId(diggingBlockState != null ? diggingBlockState : Blocks.dirt.get());\n // worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, posX, posY, posZ, Math.random() * 2 - 1,\n // Math.random() * 4, Math.random() * 2 - 1, stateId);\n // worldObj.spawnParticle(EnumParticleTypes.BLOCK_DUST, posX, posY, posZ, (Math.random() - 0.5) * 0.5,\n // Math.random() * 0.5f, (Math.random() - 0.5) * 0.5, stateId);\n }\n if (diggingAnimation % 2 == 0) {\n worldObj.playSound(posX, posY, posZ, \"block.gravel.hit\", 1f, (float) (Math.random() + 0.5), false);\n }\n }\n }\n\n // @Override\n // public void handleStatusUpdate(byte id) {\n // if(id == 12) {\n // disappear();\n // return;\n // } else if(id == 13) {\n // diggingBlockState = worldObj.getBlockState(getPosition().down());\n // diggingAnimation = 60;\n // return;\n // }\n // super.handleStatusUpdate(id);\n // }\n\n @Override\n protected void damageEntity(DamageSource damageSrc, float damageAmount) {\n if (!spawnDone && damageSrc == DamageSource.fall) {\n worldObj.playSound(posX, posY, posZ, getHurtSound(), 1f, 2f, false);\n spawnDone = true;\n return;\n }\n super.damageEntity(damageSrc, damageAmount);\n }\n\n @Override\n public float getEyeHeight() {\n return 1.62f;\n }\n\n @Nullable\n public IEntityLivingData onInitialSpawn(@Nullable IEntityLivingData livingData) {\n if (Math.random() < 0.001) {\n setCustomNameTag(Math.random() <= 0.5 ? \"Pam\" : \"Blay\");\n } else {\n setCustomNameTag(NAMES[rand.nextInt(NAMES.length)]);\n }\n setAlwaysRenderNameTag(true);\n return livingData;\n }\n\n // @Override\n // public boolean canBeLeashedTo(EntityPlayer player) {\n // return false;\n // }\n\n public void setMarket(int marketX, int marketY, int marketZ, EnumFacing facing) {\n this.marketX = marketX;\n this.marketY = marketY;\n this.marketZ = marketZ;\n // this.marketEntityPos = marketPos.offset(facing.getOpposite());\n this.facing = facing;\n }\n\n // @Nullable\n // public BlockPos getMarketEntityPosition() {\n // return marketEntityPos;\n // }\n\n public boolean isAtMarket() {\n // TODO: Implement\n // return marketEntityPos != null && getDistanceSq(marketEntityPos.offset(facing.getOpposite())) <= 1;\n return true;\n }\n\n private boolean isMarketValid() {\n // return marketPos != null && worldObj.getBlockState(marketPos).getBlock() == ModBlocks.market;\n return true;\n }\n\n public void setToFacingAngle() {\n float facingAngle = 0f; // facing.getHorizontalAngle();\n setRotation(facingAngle, 0f);\n setRotationYawHead(facingAngle);\n // setRenderYawOffset(facingAngle);\n }\n\n public void disappear() {\n worldObj.playSound(posX, posY, posZ, \"item.firecharge.use\", 1f, 1f, false);\n for (int i = 0; i < 50; i++) {\n worldObj.spawnParticle(\n \"firework\",\n posX,\n posY + 1,\n posZ,\n (Math.random() - 0.5) * 0.5f,\n (Math.random() - 0.5) * 0.5f,\n (Math.random() - 0.5) * 0.5f);\n }\n worldObj.spawnParticle(\"explosion\", posX, posY + 1, posZ, 0, 0, 0);\n setDead();\n }\n\n public void setSpawnAnimation(SpawnAnimationType spawnAnimation) {\n this.spawnAnimation = spawnAnimation;\n }\n\n public int getDiggingAnimation() {\n return diggingAnimation;\n }\n}" }, { "identifier": "GuiHandler", "path": "src/main/java/com/guigs44/farmingforengineers/network/GuiHandler.java", "snippet": "public class GuiHandler implements IGuiHandler {\n\n public static final int MARKET = 1;\n\n @Override\n @Nullable\n public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {\n if (id == MARKET) {\n TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof TileMarket) {\n return new ContainerMarket(player, x, y, z);\n }\n }\n return null;\n }\n\n @Override\n @Nullable\n public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {\n if (id == MARKET) {\n TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof TileMarket) {\n return new GuiMarket(new ContainerMarketClient(player, x, y, z));\n }\n }\n return null;\n }\n}" }, { "identifier": "TileMarket", "path": "src/main/java/com/guigs44/farmingforengineers/tile/TileMarket.java", "snippet": "public class TileMarket extends TileEntity {\n}" } ]
import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import com.guigs44.farmingforengineers.FarmingForEngineers; import com.guigs44.farmingforengineers.client.render.block.MarketBlockRenderer; import com.guigs44.farmingforengineers.entity.EntityMerchant; import com.guigs44.farmingforengineers.network.GuiHandler; import com.guigs44.farmingforengineers.tile.TileMarket;
5,189
package com.guigs44.farmingforengineers.block; /** * A good chunk of the code in this file has been based on Jason Mitchell's (@mitchej123) work. Specifically: * https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockBaseKitchen.java * https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockOven.java * * Licensed under LGPL-3.0 */ public class BlockMarket extends BlockContainer { public EntityMerchant merchant; // public static final PropertyDirection FACING = BlockHorizontal.FACING; public BlockMarket() { super(Material.wood); setBlockName(FarmingForEngineers.MOD_ID + ":market"); // TODO: Fix the name setStepSound(soundTypeWood); setHardness(2f); setResistance(10f); setCreativeTab(FarmingForEngineers.creativeTab); } @Override public void registerBlockIcons(IIconRegister reg) {} @Override public IIcon getIcon(int side, int meta) { return Blocks.log.getIcon(side, 1); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileMarket(); } @Override public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override public void onBlockAdded(World worldIn, int x, int y, int z) { super.onBlockAdded(worldIn, x, y, z); findOrientation(worldIn, x, y, z); } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase placer, ItemStack itemStack) { int facing = MathHelper.floor_double(placer.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; switch (facing) { case 0: world.setBlockMetadataWithNotify(x, y, z, 2, 2); break; case 1: world.setBlockMetadataWithNotify(x, y, z, 5, 2); break; case 2: world.setBlockMetadataWithNotify(x, y, z, 3, 2); break; case 3: world.setBlockMetadataWithNotify(x, y, z, 4, 2); break; } // EnumFacing facing = EnumFacing.NORTH; // BlockPos entityPos = pos.offset(facing.getOpposite()); EntityMerchant.SpawnAnimationType spawnAnimationType = EntityMerchant.SpawnAnimationType.MAGIC; if (world.canBlockSeeTheSky(x, y, z)) { spawnAnimationType = EntityMerchant.SpawnAnimationType.FALLING; } else if (!world.isAirBlock(x, y - 1, z)) { spawnAnimationType = EntityMerchant.SpawnAnimationType.DIGGING; } if (!world.isRemote) { merchant = new EntityMerchant(world); merchant.setMarket(x, y, z, EnumFacing.NORTH); merchant.setToFacingAngle(); merchant.setSpawnAnimation(spawnAnimationType); if (world.canBlockSeeTheSky(x, y, z)) { merchant.setPosition(x + 0.5, y + 172, z + 0.5); } else if (!world.isAirBlock(x, y, z - 1)) { merchant.setPosition(x + 0.5, y + 0.5, z + 0.5); } else { merchant.setPosition(x + 0.5, y, z + 0.5); } world.spawnEntityInWorld(merchant); merchant.onInitialSpawn(null); } if (spawnAnimationType == EntityMerchant.SpawnAnimationType.FALLING) { world.playSound(x + 0.5, y + 1, z + 0.5, "sounds.falling", 1f, 1f, false); } else if (spawnAnimationType == EntityMerchant.SpawnAnimationType.DIGGING) { world.playSound(x + 0.5, y + 1, z, "sounds.falling", 1f, 1f, false); } else { world.playSound(x + 0.5, y + 1, z + 0.5, "item.firecharge.use", 1f, 1f, false); for (int i = 0; i < 50; i++) { world.spawnParticle( "firework", x + 0.5, y + 1, z + 0.5, (Math.random() - 0.5) * 0.5f, (Math.random() - 0.5) * 0.5f, (Math.random() - 0.5) * 0.5f); } world.spawnParticle("explosion", x + 0.5, y + 1, z + 0.5, 0, 0, 0); } } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (!world.isRemote) {
package com.guigs44.farmingforengineers.block; /** * A good chunk of the code in this file has been based on Jason Mitchell's (@mitchej123) work. Specifically: * https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockBaseKitchen.java * https://github.com/GTNewHorizons/CookingForBlockheads/blob/master/src/main/java/net/blay09/mods/cookingforblockheads/block/BlockOven.java * * Licensed under LGPL-3.0 */ public class BlockMarket extends BlockContainer { public EntityMerchant merchant; // public static final PropertyDirection FACING = BlockHorizontal.FACING; public BlockMarket() { super(Material.wood); setBlockName(FarmingForEngineers.MOD_ID + ":market"); // TODO: Fix the name setStepSound(soundTypeWood); setHardness(2f); setResistance(10f); setCreativeTab(FarmingForEngineers.creativeTab); } @Override public void registerBlockIcons(IIconRegister reg) {} @Override public IIcon getIcon(int side, int meta) { return Blocks.log.getIcon(side, 1); } @Override public TileEntity createNewTileEntity(World world, int meta) { return new TileMarket(); } @Override public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override public void onBlockAdded(World worldIn, int x, int y, int z) { super.onBlockAdded(worldIn, x, y, z); findOrientation(worldIn, x, y, z); } @Override public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase placer, ItemStack itemStack) { int facing = MathHelper.floor_double(placer.rotationYaw * 4.0F / 360.0F + 0.5D) & 3; switch (facing) { case 0: world.setBlockMetadataWithNotify(x, y, z, 2, 2); break; case 1: world.setBlockMetadataWithNotify(x, y, z, 5, 2); break; case 2: world.setBlockMetadataWithNotify(x, y, z, 3, 2); break; case 3: world.setBlockMetadataWithNotify(x, y, z, 4, 2); break; } // EnumFacing facing = EnumFacing.NORTH; // BlockPos entityPos = pos.offset(facing.getOpposite()); EntityMerchant.SpawnAnimationType spawnAnimationType = EntityMerchant.SpawnAnimationType.MAGIC; if (world.canBlockSeeTheSky(x, y, z)) { spawnAnimationType = EntityMerchant.SpawnAnimationType.FALLING; } else if (!world.isAirBlock(x, y - 1, z)) { spawnAnimationType = EntityMerchant.SpawnAnimationType.DIGGING; } if (!world.isRemote) { merchant = new EntityMerchant(world); merchant.setMarket(x, y, z, EnumFacing.NORTH); merchant.setToFacingAngle(); merchant.setSpawnAnimation(spawnAnimationType); if (world.canBlockSeeTheSky(x, y, z)) { merchant.setPosition(x + 0.5, y + 172, z + 0.5); } else if (!world.isAirBlock(x, y, z - 1)) { merchant.setPosition(x + 0.5, y + 0.5, z + 0.5); } else { merchant.setPosition(x + 0.5, y, z + 0.5); } world.spawnEntityInWorld(merchant); merchant.onInitialSpawn(null); } if (spawnAnimationType == EntityMerchant.SpawnAnimationType.FALLING) { world.playSound(x + 0.5, y + 1, z + 0.5, "sounds.falling", 1f, 1f, false); } else if (spawnAnimationType == EntityMerchant.SpawnAnimationType.DIGGING) { world.playSound(x + 0.5, y + 1, z, "sounds.falling", 1f, 1f, false); } else { world.playSound(x + 0.5, y + 1, z + 0.5, "item.firecharge.use", 1f, 1f, false); for (int i = 0; i < 50; i++) { world.spawnParticle( "firework", x + 0.5, y + 1, z + 0.5, (Math.random() - 0.5) * 0.5f, (Math.random() - 0.5) * 0.5f, (Math.random() - 0.5) * 0.5f); } world.spawnParticle("explosion", x + 0.5, y + 1, z + 0.5, 0, 0, 0); } } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) { if (!world.isRemote) {
player.openGui(FarmingForEngineers.instance, GuiHandler.MARKET, world, x, y, z);
3
2023-10-17 00:25:50+00:00
8k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/syntax/RichLabel.java
[ { "identifier": "CollinsHeadFinder", "path": "src/berkeley_parser/edu/berkeley/nlp/ling/CollinsHeadFinder.java", "snippet": "public class CollinsHeadFinder extends AbstractCollinsHeadFinder {\n\n\tpublic CollinsHeadFinder() {\n\t\tthis(new PennTreebankLanguagePack());\n\t}\n\n\tprotected int postOperationFix(int headIdx, List<Tree<String>> daughterTrees) {\n\t\tif (headIdx >= 2) {\n\t\t\tString prevLab = daughterTrees.get(headIdx - 1).getLabel();\n\t\t\tif (prevLab.equals(\"CC\")) {\n\t\t\t\tint newHeadIdx = headIdx - 2;\n\t\t\t\tTree<String> t = daughterTrees.get(newHeadIdx);\n\t\t\t\twhile (newHeadIdx >= 0 && t.isPreTerminal()\n\t\t\t\t\t\t&& tlp.isPunctuationTag(t.getLabel())) {\n\t\t\t\t\tnewHeadIdx--;\n\t\t\t\t}\n\t\t\t\tif (newHeadIdx >= 0) {\n\t\t\t\t\theadIdx = newHeadIdx;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn headIdx;\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tpublic CollinsHeadFinder(TreebankLanguagePack tlp) {\n\t\tsuper(tlp);\n\n\t\tnonTerminalInfo = new HashMap();\n\t\t// This version from Collins' diss (1999: 236-238)\n\t\tnonTerminalInfo.put(\"ADJP\", new String[][] { { \"left\", \"NNS\", \"QP\",\n\t\t\t\t\"NN\", \"$\", \"ADVP\", \"JJ\", \"VBN\", \"VBG\", \"ADJP\", \"JJR\", \"NP\",\n\t\t\t\t\"JJS\", \"DT\", \"FW\", \"RBR\", \"RBS\", \"SBAR\", \"RB\" } });\n\t\tnonTerminalInfo.put(\"ADVP\", new String[][] { { \"right\", \"RB\", \"RBR\",\n\t\t\t\t\"RBS\", \"FW\", \"ADVP\", \"TO\", \"CD\", \"JJR\", \"JJ\", \"IN\", \"NP\",\n\t\t\t\t\"JJS\", \"NN\" } });\n\t\tnonTerminalInfo.put(\"CONJP\", new String[][] { { \"right\", \"CC\", \"RB\",\n\t\t\t\t\"IN\" } });\n\t\tnonTerminalInfo.put(\"FRAG\", new String[][] { { \"right\" } }); // crap\n\t\tnonTerminalInfo.put(\"INTJ\", new String[][] { { \"left\" } });\n\t\tnonTerminalInfo.put(\"LST\", new String[][] { { \"right\", \"LS\", \":\" } });\n\t\tnonTerminalInfo.put(\"NAC\", new String[][] { { \"left\", \"NN\", \"NNS\",\n\t\t\t\t\"NNP\", \"NNPS\", \"NP\", \"NAC\", \"EX\", \"$\", \"CD\", \"QP\", \"PRP\",\n\t\t\t\t\"VBG\", \"JJ\", \"JJS\", \"JJR\", \"ADJP\", \"FW\" } });\n\t\tnonTerminalInfo.put(\"NX\", new String[][] { { \"left\" } }); // crap\n\t\tnonTerminalInfo.put(\"PP\", new String[][] { { \"right\", \"IN\", \"TO\",\n\t\t\t\t\"VBG\", \"VBN\", \"RP\", \"FW\" } });\n\t\t// should prefer JJ? (PP (JJ such) (IN as) (NP (NN crocidolite)))\n\t\tnonTerminalInfo.put(\"PRN\", new String[][] { { \"left\" } });\n\t\tnonTerminalInfo.put(\"PRT\", new String[][] { { \"right\", \"RP\" } });\n\t\tnonTerminalInfo.put(\"QP\", new String[][] { { \"left\", \"$\", \"IN\", \"NNS\",\n\t\t\t\t\"NN\", \"JJ\", \"RB\", \"DT\", \"CD\", \"NCD\", \"QP\", \"JJR\", \"JJS\" } });\n\t\tnonTerminalInfo.put(\"RRC\", new String[][] { { \"right\", \"VP\", \"NP\",\n\t\t\t\t\"ADVP\", \"ADJP\", \"PP\" } });\n\t\tnonTerminalInfo.put(\"S\", new String[][] { { \"left\", \"TO\", \"IN\", \"VP\",\n\t\t\t\t\"S\", \"SBAR\", \"ADJP\", \"UCP\", \"NP\" } });\n\t\tnonTerminalInfo.put(\"SBAR\", new String[][] { { \"left\", \"WHNP\", \"WHPP\",\n\t\t\t\t\"WHADVP\", \"WHADJP\", \"IN\", \"DT\", \"S\", \"SQ\", \"SINV\", \"SBAR\",\n\t\t\t\t\"FRAG\" } });\n\t\tnonTerminalInfo.put(\"SBARQ\", new String[][] { { \"left\", \"SQ\", \"S\",\n\t\t\t\t\"SINV\", \"SBARQ\", \"FRAG\" } });\n\t\tnonTerminalInfo.put(\"SINV\", new String[][] { { \"left\", \"VBZ\", \"VBD\",\n\t\t\t\t\"VBP\", \"VB\", \"MD\", \"VP\", \"S\", \"SINV\", \"ADJP\", \"NP\" } });\n\t\tnonTerminalInfo.put(\"SQ\", new String[][] { { \"left\", \"VBZ\", \"VBD\",\n\t\t\t\t\"VBP\", \"VB\", \"MD\", \"VP\", \"SQ\" } });\n\t\tnonTerminalInfo.put(\"UCP\", new String[][] { { \"right\" } });\n\t\tnonTerminalInfo.put(\"VP\", new String[][] { { \"left\", \"TO\", \"VBD\",\n\t\t\t\t\"VBN\", \"MD\", \"VBZ\", \"VB\", \"VBG\", \"VBP\", \"AUX\", \"AUXG\", \"VP\",\n\t\t\t\t\"ADJP\", \"NN\", \"NNS\", \"NP\" } });\n\t\tnonTerminalInfo.put(\"WHADJP\", new String[][] { { \"left\", \"CC\", \"WRB\",\n\t\t\t\t\"JJ\", \"ADJP\" } });\n\t\tnonTerminalInfo.put(\"WHADVP\",\n\t\t\t\tnew String[][] { { \"right\", \"CC\", \"WRB\" } });\n\t\tnonTerminalInfo.put(\"WHNP\", new String[][] { { \"left\", \"WDT\", \"WP\",\n\t\t\t\t\"WP$\", \"WHADJP\", \"WHPP\", \"WHNP\" } });\n\t\tnonTerminalInfo.put(\"WHPP\", new String[][] { { \"right\", \"IN\", \"TO\",\n\t\t\t\t\"FW\" } });\n\t\tnonTerminalInfo.put(\"X\", new String[][] { { \"right\" } }); // crap rule\n\t\tnonTerminalInfo.put(\"NP\", new String[][] {\n\t\t\t\t{ \"rightdis\", \"NN\", \"NNP\", \"NNPS\", \"NNS\", \"NX\", \"POS\", \"JJR\" },\n\t\t\t\t{ \"left\", \"NP\" }, { \"rightdis\", \"$\", \"ADJP\", \"PRN\" },\n\t\t\t\t{ \"right\", \"CD\" }, { \"rightdis\", \"JJ\", \"JJS\", \"RB\", \"QP\" } });\n\t\tnonTerminalInfo.put(\"TYPO\", new String[][] { { \"left\" } }); // another\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// crap\n\t\t// rule, for\n\t\t// Switchboard\n\t\t// (Roger)\n\t}\n\n\t/**\n\t * Go through trees and determine their heads and print them. Just for\n\t * debuggin'. <br>\n\t * Usage: <code>\n\t * java edu.stanford.nlp.trees.CollinsHeadFinder treebankFilePath\n\t * </code>\n\t * \n\t * @param args\n\t * The treebankFilePath\n\t */\n\n\tpublic static void main(String[] args) {\n\t\tTrees.PennTreeReader reader = new Trees.PennTreeReader(\n\t\t\t\tnew StringReader(\n\t\t\t\t\t\t\"((S (NP (DT the) (JJ quick) (JJ (AA (BB (CC brown)))) (NN fox)) (VP (VBD jumped) (PP (IN over) (NP (DT the) (JJ lazy) (NN dog)))) (. .)))\"));\n\t\tTree<String> tree = reader.next();\n\t\tSystem.out.println(\"tree \" + tree);\n\n\t\tCollinsHeadFinder headFinder = new CollinsHeadFinder();\n\t\twhile (!tree.isLeaf()) {\n\t\t\tTree<String> head = headFinder.determineHead(tree);\n\t\t\tSystem.out.println(\"head \" + head);\n\t\t\ttree = head;\n\t\t}\n\t}\n\n\tprivate static final long serialVersionUID = -8747319554557223437L;\n\n}" }, { "identifier": "HeadFinder", "path": "src/berkeley_parser/edu/berkeley/nlp/ling/HeadFinder.java", "snippet": "public interface HeadFinder extends Serializable {\n\n\t/**\n\t * Determine which daughter of the current parse tree is the head. It\n\t * assumes that the daughters already have had their heads determined.\n\t * Another method has to do the tree walking.\n\t * \n\t * @param t\n\t * The parse tree to examine the daughters of\n\t * @return The parse tree that is the head. The convention has been that\n\t * this returns <code>null</code> if no head is found. But maybe it\n\t * should throw an exception?\n\t */\n\tpublic Tree<String> determineHead(Tree<String> t);\n\n\tpublic static class Utils {\n\n\t\tpublic static Pair<String, String> getHeadWordAndPartOfSpeechPair(\n\t\t\t\tHeadFinder hf, Tree<String> tree) {\n\t\t\tString headWord = null;\n\t\t\tString headPOS = null;\n\t\t\twhile (true) {\n\t\t\t\tif (tree.isPreTerminal()) {\n\t\t\t\t\theadPOS = tree.getLabel();\n\t\t\t\t}\n\t\t\t\tif (tree.isLeaf()) {\n\t\t\t\t\theadWord = tree.getLabel();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ttree = hf.determineHead(tree);\n\t\t\t}\n\t\t\treturn Pair.newPair(headWord, headPOS);\n\t\t}\n\n\t}\n\n}" }, { "identifier": "Pair", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Pair.java", "snippet": "public class Pair<F, S> implements Serializable {\n\tstatic final long serialVersionUID = 42;\n\n\tF first;\n\tS second;\n\n\tpublic F getFirst() {\n\t\treturn first;\n\t}\n\n\tpublic S getSecond() {\n\t\treturn second;\n\t}\n\n\tpublic void setFirst(F pFirst) {\n\t\tfirst = pFirst;\n\t}\n\n\tpublic void setSecond(S pSecond) {\n\t\tsecond = pSecond;\n\t}\n\n\tpublic Pair<S, F> reverse() {\n\t\treturn new Pair<S, F>(second, first);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (!(o instanceof Pair))\n\t\t\treturn false;\n\n\t\tfinal Pair pair = (Pair) o;\n\n\t\tif (first != null ? !first.equals(pair.first) : pair.first != null)\n\t\t\treturn false;\n\t\tif (second != null ? !second.equals(pair.second) : pair.second != null)\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint result;\n\t\tresult = (first != null ? first.hashCode() : 0);\n\t\tresult = 29 * result + (second != null ? second.hashCode() : 0);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + getFirst() + \", \" + getSecond() + \")\";\n\t}\n\n\tpublic Pair(F first, S second) {\n\t\tthis.first = first;\n\t\tthis.second = second;\n\t}\n\n\t// Compares only first values\n\tpublic static class FirstComparator<S extends Comparable<? super S>, T>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p1.getFirst().compareTo(p2.getFirst());\n\t\t}\n\t}\n\n\tpublic static class ReverseFirstComparator<S extends Comparable<? super S>, T>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p2.getFirst().compareTo(p1.getFirst());\n\t\t}\n\t}\n\n\t// Compares only second values\n\tpublic static class SecondComparator<S, T extends Comparable<? super T>>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p1.getSecond().compareTo(p2.getSecond());\n\t\t}\n\t}\n\n\tpublic static class ReverseSecondComparator<S, T extends Comparable<? super T>>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p2.getSecond().compareTo(p1.getSecond());\n\t\t}\n\t}\n\n\tpublic static <S, T> Pair<S, T> newPair(S first, T second) {\n\t\treturn new Pair<S, T>(first, second);\n\t}\n\n\t// Duplicate method to faccilitate backwards compatibility\n\t// - aria42\n\tpublic static <S, T> Pair<S, T> makePair(S first, T second) {\n\t\treturn new Pair<S, T>(first, second);\n\t}\n\n\tpublic static class LexicographicPairComparator<F, S> implements\n\t\t\tComparator<Pair<F, S>> {\n\t\tComparator<F> firstComparator;\n\t\tComparator<S> secondComparator;\n\n\t\tpublic int compare(Pair<F, S> pair1, Pair<F, S> pair2) {\n\t\t\tint firstCompare = firstComparator.compare(pair1.getFirst(),\n\t\t\t\t\tpair2.getFirst());\n\t\t\tif (firstCompare != 0)\n\t\t\t\treturn firstCompare;\n\t\t\treturn secondComparator.compare(pair1.getSecond(),\n\t\t\t\t\tpair2.getSecond());\n\t\t}\n\n\t\tpublic LexicographicPairComparator(Comparator<F> firstComparator,\n\t\t\t\tComparator<S> secondComparator) {\n\t\t\tthis.firstComparator = firstComparator;\n\t\t\tthis.secondComparator = secondComparator;\n\t\t}\n\t}\n\n\tpublic static class DefaultLexicographicPairComparator<F extends Comparable<F>, S extends Comparable<S>>\n\t\t\timplements Comparator<Pair<F, S>> {\n\n\t\tpublic int compare(Pair<F, S> o1, Pair<F, S> o2) {\n\t\t\tint firstCompare = o1.getFirst().compareTo(o2.getFirst());\n\t\t\tif (firstCompare != 0) {\n\t\t\t\treturn firstCompare;\n\t\t\t}\n\t\t\treturn o2.getSecond().compareTo(o2.getSecond());\n\t\t}\n\n\t}\n\n}" } ]
import java.io.StringReader; import java.util.ArrayList; import java.util.List; import edu.berkeley.nlp.ling.CollinsHeadFinder; import edu.berkeley.nlp.ling.HeadFinder; import edu.berkeley.nlp.util.Pair;
3,848
package edu.berkeley.nlp.syntax; /** * Created by IntelliJ IDEA. User: aria42 Date: Oct 25, 2008 Time: 4:04:53 PM */ public class RichLabel { private String headWord; private String headTag; private int start; private int stop; private int headIndex; private String label; private Tree<String> origNode; public int getSpanSize() { return stop - start; } public int getHeadIndex() { return headIndex; } public void setHeadIndex(int headIndex) { this.headIndex = headIndex; } public String getHeadWord() { return headWord; } public void setHeadWord(String headWord) { this.headWord = headWord; } public String getHeadTag() { return headTag; } public void setHeadTag(String headTag) { this.headTag = headTag; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getStop() { return stop; } public void setStop(int stop) { this.stop = stop; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Tree<String> getOriginalNode() { return origNode; } public void setOriginalNode(Tree<String> origNode) { this.origNode = origNode; } @Override public String toString() { return String.format("%s(%s[%d]-%s)[%d,%d]", label, headWord, headIndex, headTag, start, stop); } private static final CollinsHeadFinder cf = new CollinsHeadFinder(); public static Tree<RichLabel> getRichTree(Tree<String> tree) { return getRichTree(tree, cf); } public static Tree<RichLabel> getRichTree(Tree<String> tree,
package edu.berkeley.nlp.syntax; /** * Created by IntelliJ IDEA. User: aria42 Date: Oct 25, 2008 Time: 4:04:53 PM */ public class RichLabel { private String headWord; private String headTag; private int start; private int stop; private int headIndex; private String label; private Tree<String> origNode; public int getSpanSize() { return stop - start; } public int getHeadIndex() { return headIndex; } public void setHeadIndex(int headIndex) { this.headIndex = headIndex; } public String getHeadWord() { return headWord; } public void setHeadWord(String headWord) { this.headWord = headWord; } public String getHeadTag() { return headTag; } public void setHeadTag(String headTag) { this.headTag = headTag; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getStop() { return stop; } public void setStop(int stop) { this.stop = stop; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public Tree<String> getOriginalNode() { return origNode; } public void setOriginalNode(Tree<String> origNode) { this.origNode = origNode; } @Override public String toString() { return String.format("%s(%s[%d]-%s)[%d,%d]", label, headWord, headIndex, headTag, start, stop); } private static final CollinsHeadFinder cf = new CollinsHeadFinder(); public static Tree<RichLabel> getRichTree(Tree<String> tree) { return getRichTree(tree, cf); } public static Tree<RichLabel> getRichTree(Tree<String> tree,
HeadFinder headFinder) {
1
2023-10-22 13:13:22+00:00
8k
UZ9/cs-1331-drivers
src/StartMenuTests.java
[ { "identifier": "TestFailedException", "path": "src/com/cs1331/drivers/exception/TestFailedException.java", "snippet": "public class TestFailedException extends Exception {\n public TestFailedException() {\n }\n\n public TestFailedException(String message) {\n super(message);\n }\n}" }, { "identifier": "RecursiveSearch", "path": "src/com/cs1331/drivers/javafx/RecursiveSearch.java", "snippet": "public class RecursiveSearch {\n @SuppressWarnings(\"unchecked\")\n public static <T extends Node> T recursiveSearch(Filter<T> filter, Class<T> type, Pane current) {\n for (int i = 0; i < current.getChildren().size(); i++) {\n Node node = current.getChildren().get(i);\n\n if (type.isAssignableFrom(node.getClass())) {\n T castVar = (T) node;\n\n if (filter.matches(castVar)) {\n return castVar;\n }\n } else if (node instanceof Pane) {\n T res = recursiveSearch(filter, type, (Pane) node);\n if (res != null) return res;\n }\n }\n\n return null;\n }\n}" }, { "identifier": "TestFunction", "path": "src/com/cs1331/drivers/testing/TestFunction.java", "snippet": "public class TestFunction {\n /**\n * Detects if the given Strings do not have the same content (case-sensitive)\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(String actual, String expected) throws TestFailedException {\n boolean failed = false;\n\n if (actual == null) {\n if (expected != null) {\n throw new TestFailedException(\"Test failed! Received null, but expected \\\"\" + expected + \"\\\"\");\n }\n } else if (expected == null) {\n throw new TestFailedException(\"Test failed! Received \\\"\" + actual + \"\\\", but expected null\");\n } else {\n\n if (!actual.replaceAll(\"\\n\", System.lineSeparator()).equals(expected.replaceAll(\"\\n\", System.lineSeparator()))) {\n failed = true;\n }\n }\n\n if (failed) {\n \n \n String expectedString = \"\\\"\" + expected + \"\\\"\";\n String coloredActual = StringUtils.getColorCodedDifference(\"\\\"\" + actual + \"\\\"\", expectedString);\n\n \n if (coloredActual.trim().contains(\"\\n\")) {\n coloredActual = \"\\n\" + coloredActual + \"\\n\";\n }\n if (expected.trim().contains(\"\\n\")) {\n expectedString = \"\\n\\\"\" + expected + \"\\\"\\n\";\n }\n\n throw new TestFailedException(\n \"Strings different! Received \" + coloredActual + \" but expected \" + expectedString);\n }\n }\n\n public static void assertEqual(Iterable<?> actual, Iterable<?> expected) throws TestFailedException {\n\n boolean failed = false;\n\n if (actual == null || expected == null) {\n failed = actual == expected;\n throw new TestFailedException(\n \"List different! Received \\\"\" + actual == null ? \"null\" : TestUtils.iterableToString(actual) + \"\\\", expected \\\"\" + expected == null ? \"null\" : TestUtils.iterableToString(expected) + \"\\\"\");\n } else {\n Iterator<?> aIterator = actual.iterator();\n Iterator<?> eIterator = expected.iterator();\n while (aIterator.hasNext() && eIterator.hasNext()) {\n if (!aIterator.next().equals(eIterator.next())) {\n failed = true;\n }\n }\n\n if (aIterator.hasNext() != eIterator.hasNext()) {\n throw new TestFailedException(\"List lengths different! Received \\\"\" + TestUtils.iterableToString(actual) + \"\\\" but expected \\\"\" + TestUtils.iterableToString(expected) + \"\\\"\");\n }\n }\n\n if (failed) {\n throw new TestFailedException(\n \"List different! Received \\\"\" + TestUtils.iterableToString(actual) + \"\\\", expected \\\"\" + TestUtils.iterableToString(expected) + \"\\\"\");\n }\n\n }\n\n public static void assertEqual(List<String> actual, List<String> expected) throws TestFailedException {\n boolean failed = false;\n\n if (actual == null || expected == null || actual.size() != expected.size()) {\n failed = actual == expected;\n } else {\n for (int i = 0; i < expected.size(); i++) {\n if (expected.get(i) == null) {\n failed = actual.get(i) != null;\n\n } else {\n failed = !actual.get(i).equals(expected.get(i));\n\n }\n if (failed) break;\n }\n }\n\n if (failed) {\n throw new TestFailedException(\n \"List Different! Received \\\"\" + actual + \"\\\", expected \\\"\" + expected + \"\\\"\");\n }\n }\n\n /**\n * Detects if the given integers are not equal.\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(int actual, int expected) throws TestFailedException {\n boolean failed = (actual != expected);\n if (failed) {\n throw new TestFailedException(\"Integer value difference: Received \" + actual + \", expected \" + expected);\n }\n }\n\n /**\n * Detects if the given doubles are not within 1.0e-6 of one another.\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(double actual, double expected) throws TestFailedException {\n final double ALLOWABLE_ERROR = 0.000001;\n\n boolean failed = (Math.abs(actual - expected) > ALLOWABLE_ERROR);\n\n if (failed) {\n throw new TestFailedException(\"Double value difference: \\n\\tReceived \" + actual + \", expected \" + expected);\n }\n }\n\n /**\n * Detects if the given booleans do not have equal values.\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(boolean actual, boolean expected) throws TestFailedException {\n boolean failed = (actual != expected);\n\n if (failed) {\n throw new TestFailedException(\"Boolean value difference: Received \" + actual + \", expected \" + expected);\n }\n }\n\n /**\n * Detects if the given objects are equal by their .equals() methods. By default, this method will also test\n * for symmetry.\n *\n * @param expected Whether or not these two objects should be equal by their .equals() methods\n * @param obj1 The first object to compare.\n * @param obj2 The second object to compare.\n * @throws TestFailedException if the test fails\n */\n public static void assertEqual(boolean expected, Object obj1, Object obj2) throws TestFailedException {\n boolean actual = obj1.equals(obj2);\n if (actual != expected) {\n throw new TestFailedException(\"Boolean value difference with .equals() method. When comparing\\n\\\"\" + obj1.toString() + \"\\\" with \\\"\" + obj2.toString() + \"\\\", Received \" + actual + \", expected \" + expected);\n }\n\n if (actual != obj2.equals(obj1)) {\n throw new TestFailedException(\"Asymmetry detected! When comparing \\\"\" + obj1.toString() + \"\\\" with \\\"\" + obj2.toString() + \"\\\", Received \" + actual + \". But when calling .equals() the other way, received \" + !actual);\n }\n }\n\n /**\n * Tests the given code for a particular type of Exception.\n * @param exceptionType The class of the expected Exception.\n * @param codeThatThrowsException Runnable code that is intended to throw an exceptino of type exceptionType. Must NOT throw a TestFailedException\n * @throws TestFailedException\n */\n public static void testForException(Class<? extends Exception> exceptionType, Runnable codeThatThrowsException) throws TestFailedException {\n try {\n codeThatThrowsException.run();\n throw new TestFailedException(exceptionType.getSimpleName() + \" did NOT occur when it was supposed to!\");\n } catch (Exception e) {\n if (e.getClass() == exceptionType) {\n if (e.getMessage() == null || e.getMessage().isBlank()) {\n throw new TestFailedException(\"Make sure you're setting a descriptive message for your \" + e.getClass().getSimpleName() + \"!\");\n }\n // Test passed! Finish running method and return to the invoker\n } else if (e.getClass() == TestFailedException.class && e.getMessage().contains(\"did NOT occur\")) {\n\n throw new TestFailedException(\"No exception occurred! The code should have thrown a \" + exceptionType.getSimpleName());\n\n } else {\n\n throw new TestFailedException(\"Exception class difference! Received \" + e.getClass().getSimpleName() + \" but expected \" + exceptionType.getSimpleName() + \".\"\n + \"\\nFull stack trace:\\n\" + StringUtils.stackTraceToString(e));\n\n }\n }\n }\n\n /**\n * Tester for String inputs. Takes in a String -> String function, and compares the output with the desired output.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @param inputs The StringInput values to test.\n * @throws TestFailedException\n */\n public static void testStringInputs(String actual, TestUtils.StringFunction codeToRun, TestUtils.StringInput[] inputs) throws TestFailedException {\n\n for (TestUtils.StringInput stringInput : inputs) {\n try {\n assertEqual(actual, codeToRun.run(stringInput.getStringValue()));\n } catch (TestFailedException tfe) {\n throw new TestFailedException(\"When inputted string is \" + stringInput.toString() + \": \" + tfe.getMessage());\n }\n }\n\n }\n\n /**\n * Convenience method that calls testStringInputs(String, StringFunction, StringInput[]) for ALL\n * values of the StringFunction enum.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @throws TestFailedException\n */\n public static void testStringInputs(String actual, TestUtils.StringFunction codeToRun) throws TestFailedException {\n testStringInputs(actual, codeToRun, TestUtils.StringInput.values());\n }\n\n /**\n * Tester for String inputs. Takes in a String -> String function, and compares the output with the desired output.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @param inputs The StringInput values to test.\n * @throws TestFailedException\n */\n public static void testStringInputsForException(Class<? extends Exception> exceptionType, Consumer<String> codeToRun, TestUtils.StringInput... inputs) throws TestFailedException {\n\n for (TestUtils.StringInput stringInput : inputs) {\n try {\n testForException(exceptionType, () -> codeToRun.accept(stringInput.getStringValue()));\n } catch (TestFailedException tfe) {\n throw new TestFailedException(\"When inputted string is \" + stringInput.toString() + \": \" + tfe.getMessage());\n }\n }\n\n }\n\n /**\n * Convenience method that calls testStringInputs(String, StringFunction, StringInput[]) for ALL\n * values of the StringFunction enum.\n * @param actual The expected String output of the runnable function.\n * @param codeToRun A runnable function that takes in a String and outputs a String.\n * @throws TestFailedException\n */\n public static void testStringInputsForException(Class<? extends Exception> exceptionType, Consumer<String> codeToRun) throws TestFailedException {\n testStringInputsForException(exceptionType, codeToRun, TestUtils.StringInput.values());\n }\n\n /**\n * Prints an error message\n *\n * @param actual The actual value\n * @param expected The expected value\n * @throws TestFailedException If the test fails\n */\n public static void failTest(String errorMessage) throws TestFailedException {\n throw new TestFailedException(\"An error occurred: \" + errorMessage);\n }\n\n}" }, { "identifier": "TestManager", "path": "src/com/cs1331/drivers/testing/TestManager.java", "snippet": "public class TestManager {\n protected volatile static AtomicInteger classTests = new AtomicInteger();\n protected volatile static AtomicInteger classTestsFailed = new AtomicInteger();\n\n private static List<String> filter;\n\n /**\n * A list of the currently registered classes to test\n */\n private static final List<Class<?>> testClazzes = new ArrayList<>();\n\n /**\n * A list of the currently registered data classes\n */\n private static final List<Class<?>> dataClazzes = new ArrayList<>();\n\n /**\n * When this method is called, the TestManager will run all tests in the given\n * classes.\n * \n * @param classes The classes to test.\n */\n public static void runTestsOn(Stage stage, Class<?>... classes) {\n for (Class<?> currentClass : classes) {\n registerClass(currentClass);\n }\n\n executeNextTest(stage);\n }\n\n public static void registerDataClasses(Class<?>... classes) {\n for (Class<?> clazz : classes) {\n registerDataClass(clazz);\n }\n }\n\n private static int currentTestChain = 0;\n\n /**\n * Registers and marks test class to be scanned during test execution.\n * \n * @param clazz The input class\n */\n public static void registerClass(Class<?> clazz) {\n if (filter == null || filter.isEmpty() || filter.stream().anyMatch(s -> s.equals(clazz.getName()))) {\n testClazzes.add(clazz);\n }\n }\n\n public static void registerDataClass(Class<?> clazz) {\n dataClazzes.add(clazz);\n }\n\n public static void startNextTestSuite() {\n\n }\n\n /**\n * Executes all registered tests.\n */\n public static void executeNextTest(Stage stage) {\n injectData(stage);\n\n ExecutorService executor = Executors.newFixedThreadPool(1);\n\n List<Runnable> runnables = new ArrayList<>();\n\n runnables.add(new TestContainer(testClazzes.get(currentTestChain)));\n\n // for (Class<?> testClass : testClazzes) {\n // runnables.add(new TestContainer(testClass));\n // }\n\n for (Runnable r : runnables) {\n Future<?> future = executor.submit(r);\n\n try {\n future.get(10, TimeUnit.SECONDS);\n } catch (InterruptedException ignored) {\n\n } catch (ExecutionException e) {\n e.getCause().printStackTrace();\n } catch (TimeoutException e) {\n future.cancel(true);\n\n System.out.println(ColorUtils.formatColorString(AsciiColorCode.BRIGHT_RED_BACKGROUND,\n AsciiColorCode.BRIGHT_WHITE_FOREGROUND, \" FAILED \\u00BB \")\n + \" A test failed by exceeding the time limit. You likely have an infinite loop somewhere.\");\n\n System.exit(-1);\n }\n\n }\n\n executor.shutdown();\n\n StringUtils.printHorizontalLine();\n\n StringUtils.printTextCentered(\"Test Results\");\n System.out.println();\n StringUtils.printTextCentered(\n String.format(\"TOTAL TESTS PASSED: %d/%d\", classTests.get() - classTestsFailed.get(),\n classTests.get()));\n StringUtils.printHorizontalLine();\n\n currentTestChain++;\n\n }\n\n private static void injectData(Stage stage) {\n\n for (Class<?> dataClass : dataClazzes) {\n for (Field f : dataClass.getFields()) {\n InjectData injectAnnotation = f.getAnnotation(InjectData.class);\n\n if (injectAnnotation != null) {\n Scanner scanner = null;\n\n StringBuilder output = new StringBuilder();\n\n if (injectAnnotation.name().equals(\"stage\")) {\n f.setAccessible(true);\n\n try {\n f.set(null, stage);\n } catch (Exception e) {\n e.printStackTrace();\n }\n \n return;\n } else {\n try {\n scanner = new Scanner(new File(injectAnnotation.name()));\n\n while (scanner.hasNextLine()) {\n output.append(scanner.nextLine()).append(\"\\n\");\n }\n } catch (FileNotFoundException e) {\n System.out.println(\"COULDN'T FIND INJECT DATA FILE \" + injectAnnotation.name());\n System.exit(-1);\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n }\n\n // Inject data into variable\n f.setAccessible(true);\n\n try {\n // Set private static final\n f.set(null, output.toString());\n } catch (Exception e) {\n e.printStackTrace();\n System.exit(-1);\n }\n\n }\n }\n }\n }\n\n /**\n * Prints a formatted test category section\n * \n * @param category The name of the section (most likely the class name)\n */\n protected static void printTestCategory(String category) {\n StringUtils.printHorizontalLine();\n StringUtils.printTextCentered(category);\n System.out.println();\n }\n\n /**\n * Sets a filter to determine what test class files can be run.\n * This is primarily used in the CLI options.\n * \n * @param filter The filter of classes\n */\n public static void setTestFilter(List<String> filter) {\n TestManager.filter = filter;\n }\n}" } ]
import java.io.File; import com.cs1331.drivers.annotations.AfterTest; import com.cs1331.drivers.annotations.InjectData; import com.cs1331.drivers.annotations.TestCase; import com.cs1331.drivers.annotations.Tip; import com.cs1331.drivers.exception.TestFailedException; import com.cs1331.drivers.javafx.RecursiveSearch; import com.cs1331.drivers.testing.TestFunction; import com.cs1331.drivers.testing.TestManager; import javafx.application.Platform; import javafx.event.Event; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.layout.Pane; import javafx.stage.Stage;
4,376
public class StartMenuTests { @TestCase(name = "valid title property") @Tip(description = "Make sure you're setting your stage title correctly!") public void checkApplicationTitle() throws TestFailedException {
public class StartMenuTests { @TestCase(name = "valid title property") @Tip(description = "Make sure you're setting your stage title correctly!") public void checkApplicationTitle() throws TestFailedException {
TestFunction.assertEqual(StageData.stage.getTitle(), "Battleship");
2
2023-10-20 03:06:59+00:00
8k
AkramLZ/ServerSync
serversync-bungee/src/main/java/me/akraml/serversync/bungee/BungeeServerSyncPlugin.java
[ { "identifier": "ServerSync", "path": "serversync-common/src/main/java/me/akraml/serversync/ServerSync.java", "snippet": "@Getter\npublic class ServerSync {\n\n private static ServerSync INSTANCE;\n\n private final ServersManager serversManager;\n private final MessageBrokerService messageBrokerService;\n\n /**\n * Private constructor to prevent instantiation from outside and enforce the singleton pattern.\n *\n * @param serversManager The servers manager to manage server operations.\n * @param messageBrokerService The message broker service to handle messaging.\n */\n private ServerSync(final ServersManager serversManager,\n final MessageBrokerService messageBrokerService) {\n this.serversManager = serversManager;\n this.messageBrokerService = messageBrokerService;\n }\n\n /**\n * Retrieves the singleton instance of ServerSync.\n *\n * @return The singleton instance of ServerSync.\n */\n public static ServerSync getInstance() {\n return INSTANCE;\n }\n\n /**\n * Initializes the singleton instance of ServerSync. If the instance is already\n * initialized, this method will throw a {@link RuntimeException} to prevent\n * re-initialization.\n *\n * @param serversManager The servers manager for server operations.\n * @param messageBrokerService The message broker service for messaging.\n * @throws RuntimeException if an instance is already initialized.\n */\n public static void initializeInstance(final ServersManager serversManager,\n final MessageBrokerService messageBrokerService) {\n if (INSTANCE != null) throw new RuntimeException(\"Instance is already initialized\");\n INSTANCE = new ServerSync(serversManager, messageBrokerService);\n }\n\n}" }, { "identifier": "RedisMessageBrokerService", "path": "serversync-common/src/main/java/me/akraml/serversync/broker/RedisMessageBrokerService.java", "snippet": "public final class RedisMessageBrokerService extends MessageBrokerService implements AuthenticatedConnection<JedisPool> {\n\n private final Gson gson = new Gson();\n private final ConnectionCredentials credentials;\n private JedisPool pool;\n\n /**\n * Constructs a new RedisMessageBroker with the given {@link ServersManager} and {@link ConnectionCredentials}.\n *\n * @param serversManager The servers manager to use for actions on servers.\n * @param credentials The credentials used to establish a connection with Redis.\n */\n public RedisMessageBrokerService(final ServersManager serversManager,\n final ConnectionCredentials credentials) {\n super(serversManager);\n this.credentials = credentials;\n }\n\n @Override\n public ConnectionResult connect() {\n\n // Initializes a jedis pool configuration with required information.\n final JedisPoolConfig poolConfig = new JedisPoolConfig();\n poolConfig.setMaxTotal(credentials.getProperty(RedisCredentialsKeys.MAX_TOTAL, Integer.class));\n poolConfig.setMaxIdle(credentials.getProperty(RedisCredentialsKeys.MAX_IDLE, Integer.class));\n poolConfig.setMinIdle(credentials.getProperty(RedisCredentialsKeys.MIN_IDLE, Integer.class));\n poolConfig.setBlockWhenExhausted(credentials.getProperty(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, Boolean.class));\n poolConfig.setMinEvictableIdleTime(\n Duration.ofMillis(credentials.getProperty(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, Long.class))\n );\n poolConfig.setTimeBetweenEvictionRuns(\n Duration.ofMillis(credentials.getProperty(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, Long.class))\n );\n\n // Initializes a new jedis pool instance to hold connections on.\n this.pool = new JedisPool(\n poolConfig,\n credentials.getProperty(RedisCredentialsKeys.HOST, String.class),\n credentials.getProperty(RedisCredentialsKeys.PORT, Integer.class),\n credentials.getProperty(RedisCredentialsKeys.TIMEOUT, Integer.class),\n credentials.getProperty(RedisCredentialsKeys.PASSWORD, String.class)\n );\n\n // Tests if the connection works properly and return the result.\n try (final Jedis ignore = pool.getResource()) {\n return ConnectionResult.SUCCESS;\n } catch (final Exception exception) {\n return ConnectionResult.FAILURE;\n }\n }\n\n @Override\n public JedisPool getConnection() {\n return pool;\n }\n\n @Override\n public ConnectionCredentials getCredentials() {\n return credentials;\n }\n\n @Override\n public void startHandler() {\n CompletableFuture.runAsync(() -> {\n try (final Jedis jedis = getConnection().getResource()) {\n jedis.subscribe(new JedisPubSub() {\n @Override\n public void onMessage(String channel, String message) {\n onMessageReceive(gson.fromJson(message, JsonObject.class));\n }\n }, \"serversync:servers\");\n }\n }).exceptionally(throwable -> {\n throwable.printStackTrace(System.err);\n return null;\n });\n }\n\n @Override\n public void stop() {\n close();\n }\n\n @Override\n public void publish(JsonObject message) {\n try(final Jedis jedis = pool.getResource()) {\n jedis.publish(\"serversync:servers\", message.toString());\n }\n }\n}" }, { "identifier": "ConnectionResult", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/ConnectionResult.java", "snippet": "public enum ConnectionResult {\n\n /**\n * Indicates a successful connection.\n */\n SUCCESS,\n\n /**\n * Indicates a failed connection.\n */\n FAILURE\n\n}" }, { "identifier": "ConnectionType", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/ConnectionType.java", "snippet": "public enum ConnectionType {\n\n REDIS,\n RABBITMQ\n\n}" }, { "identifier": "ConnectionCredentials", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/auth/ConnectionCredentials.java", "snippet": "public final class ConnectionCredentials {\n\n private final Map<CredentialsKey, Object> keyMap = new HashMap<>();\n\n /**\n * Constructor must be private to disallow external initialization.\n */\n private ConnectionCredentials() {\n }\n\n /**\n * Retrieves the value associated with the specified key and casts it to the specified type.\n *\n * @param key The key of the property.\n * @param typeClass The class representing the type of the property.\n * @param <T> The type of the property.\n * @return The value associated with the key, cast to the specified type.\n * @throws ConnectionAuthenticationException if the key is missing in the credentials.\n * @throws ClassCastException if the type is not the same as the key.\n */\n public <T> T getProperty(final CredentialsKey key,\n final Class<T> typeClass) {\n if (!keyMap.containsKey(key)) {\n throw new ConnectionAuthenticationException(\"Missing key=\" + key);\n }\n Object keyObject = keyMap.get(key);\n return typeClass.cast(keyObject);\n }\n\n /**\n * Creates a new instance of the ConnectionCredentials.Builder.\n *\n * @return A new instance of the ConnectionCredentials.Builder.\n */\n public static Builder newBuilder() {\n return new Builder();\n }\n\n /**\n * A builder class for constructing ConnectionCredentials objects.\n */\n public static final class Builder {\n\n private final ConnectionCredentials credentials;\n\n private Builder() {\n this.credentials = new ConnectionCredentials();\n }\n\n /**\n * Adds a key-value pair to the connection credentials.\n *\n * @param key The key of the credential.\n * @param value The value of the credential.\n * @return The Builder instance.\n */\n public Builder addKey(final CredentialsKey key,\n final Object value) {\n credentials.keyMap.put(key, value);\n return this;\n }\n\n /**\n * Builds and returns the ConnectionCredentials object.\n *\n * @return The constructed ConnectionCredentials object.\n */\n public ConnectionCredentials build() {\n return credentials;\n }\n\n }\n\n}" }, { "identifier": "RedisCredentialsKeys", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/auth/credentials/RedisCredentialsKeys.java", "snippet": "public enum RedisCredentialsKeys implements CredentialsKey {\n\n HOST(\"host\"),\n PORT(\"port\"),\n PASSWORD(\"password\"),\n TIMEOUT(\"timeout\"),\n MAX_TOTAL(\"maxTotal\"),\n MAX_IDLE(\"maxIdle\"),\n MIN_IDLE(\"minIdle\"),\n MIN_EVICTABLE_IDLE_TIME(\"minEvictableIdleTime\"),\n TIME_BETWEEN_EVICTION_RUNS(\"timeBetweenEvictionRuns\"),\n BLOCK_WHEN_EXHAUSTED(\"blockWhenExhausted\");\n\n private final String keyName;\n\n RedisCredentialsKeys(String keyName) {\n this.keyName = keyName;\n }\n\n @Override\n public String getKeyName() {\n return keyName;\n }\n}" }, { "identifier": "ServersManager", "path": "serversync-common/src/main/java/me/akraml/serversync/server/ServersManager.java", "snippet": "public abstract class ServersManager {\n\n /** Timer to schedule and manage the heartbeat task. */\n private final Timer timer = new Timer();\n\n /** Map storing the servers using their names as the key. */\n private final Map<String, ServerImpl> servers = new HashMap<>();\n\n /** Integers for heartbeat task delay and maximum time to remove the server. */\n protected int heartbeatSchedulerDelay, maxAliveTime;\n\n /**\n * Starts a recurring task to check servers for their heartbeat signal.\n * Servers that haven't sent a heartbeat signal within the last 30 seconds will be removed.\n */\n public final void startHeartbeatTask() {\n timer.scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n final List<ServerImpl> toRemove = new ArrayList<>();\n servers.values().forEach(server -> {\n if (System.currentTimeMillis() - server.getLastHeartbeat() > maxAliveTime) {\n toRemove.add(server);\n }\n });\n toRemove.forEach(ServersManager.this::removeServer);\n toRemove.clear();\n }\n }, 0L, Duration.ofSeconds(heartbeatSchedulerDelay).toMillis());\n }\n\n /**\n * Retrieves a server instance by its name.\n *\n * @param name The name of the server.\n * @return The server instance or null if not found.\n */\n public final Server getServer(String name) {\n return this.servers.get(name);\n }\n\n /**\n * Adds a server to the managed collection of servers.\n *\n * @param server The server to be added.\n */\n public final void addServer(Server server) {\n this.servers.put(server.getName(), (ServerImpl) server);\n registerInProxy(server);\n }\n\n /**\n * Removes a server from the managed collection of servers.\n * Also, triggers an unregister action specific to the proxy.\n *\n * @param server The server to be removed.\n */\n public final void removeServer(Server server) {\n unregisterFromProxy(server);\n this.servers.remove(server.getName());\n }\n\n /**\n * Abstract method that should be implemented to unregister a server from the associated proxy.\n *\n * @param server The server to be unregistered from the proxy.\n */\n protected abstract void unregisterFromProxy(Server server);\n\n /**\n * Abstract method that should be implemented to register a server in the proxy server.\n *\n * @param server The server to be registered in the proxy.\n */\n protected abstract void registerInProxy(Server server);\n}" } ]
import me.akraml.serversync.connection.auth.ConnectionCredentials; import me.akraml.serversync.connection.auth.credentials.RedisCredentialsKeys; import me.akraml.serversync.server.ServersManager; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; import lombok.Getter; import me.akraml.serversync.ServerSync; import me.akraml.serversync.VersionInfo; import me.akraml.serversync.broker.RedisMessageBrokerService; import me.akraml.serversync.connection.ConnectionResult; import me.akraml.serversync.connection.ConnectionType;
3,787
/* * MIT License * * Copyright (c) 2023 Akram Louze * * 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.akraml.serversync.bungee; /** * An implementation for ServerSync in BungeeCord platform. */ @Getter public final class BungeeServerSyncPlugin extends Plugin { private Configuration config; @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void onLoad() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } try { loadConfig(); } catch (Exception exception) { exception.printStackTrace(System.err); } } @Override public void onEnable() { final long start = System.currentTimeMillis(); getLogger().info("\n" + " __ __ \n" + "/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" + "\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" + "_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" + "\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" + " |___/ \n"); getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL."); final ServersManager serversManager = new BungeeServersManager(this); // Initialize message broker service. final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service")); switch (connectionType) { case REDIS: { getLogger().info("ServerSync will run under Redis message broker..."); long redisStartTime = System.currentTimeMillis(); final Configuration redisSection = config.getSection("redis"); final ConnectionCredentials credentials = ConnectionCredentials.newBuilder() .addKey(RedisCredentialsKeys.HOST, redisSection.getString("host")) .addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port")) .addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password")) .addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout")) .addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total")) .addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle")) .addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle")) .addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time")) .addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs")) .addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted")) .build(); final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService( serversManager, credentials ); final ConnectionResult connectionResult = messageBrokerService.connect(); if (connectionResult == ConnectionResult.FAILURE) { getLogger().severe("Failed to connect into redis, please check credentials!"); return; } getLogger().info("Successfully connected to redis, process took " + (System.currentTimeMillis() - redisStartTime) + "ms!"); messageBrokerService.startHandler();
/* * MIT License * * Copyright (c) 2023 Akram Louze * * 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.akraml.serversync.bungee; /** * An implementation for ServerSync in BungeeCord platform. */ @Getter public final class BungeeServerSyncPlugin extends Plugin { private Configuration config; @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void onLoad() { if (!getDataFolder().exists()) { getDataFolder().mkdir(); } try { loadConfig(); } catch (Exception exception) { exception.printStackTrace(System.err); } } @Override public void onEnable() { final long start = System.currentTimeMillis(); getLogger().info("\n" + " __ __ \n" + "/ _\\ ___ _ ____ _____ _ __/ _\\_ _ _ __ ___ \n" + "\\ \\ / _ \\ '__\\ \\ / / _ \\ '__\\ \\| | | | '_ \\ / __|\n" + "_\\ \\ __/ | \\ V / __/ | _\\ \\ |_| | | | | (__ \n" + "\\__/\\___|_| \\_/ \\___|_| \\__/\\__, |_| |_|\\___|\n" + " |___/ \n"); getLogger().info("This server is running ServerSync " + VersionInfo.VERSION + " by AkramL."); final ServersManager serversManager = new BungeeServersManager(this); // Initialize message broker service. final ConnectionType connectionType = ConnectionType.valueOf(config.getString("message-broker-service")); switch (connectionType) { case REDIS: { getLogger().info("ServerSync will run under Redis message broker..."); long redisStartTime = System.currentTimeMillis(); final Configuration redisSection = config.getSection("redis"); final ConnectionCredentials credentials = ConnectionCredentials.newBuilder() .addKey(RedisCredentialsKeys.HOST, redisSection.getString("host")) .addKey(RedisCredentialsKeys.PORT, redisSection.getInt("port")) .addKey(RedisCredentialsKeys.PASSWORD, redisSection.getString("password")) .addKey(RedisCredentialsKeys.TIMEOUT, redisSection.getInt("timeout")) .addKey(RedisCredentialsKeys.MAX_TOTAL, redisSection.getInt("max-total")) .addKey(RedisCredentialsKeys.MAX_IDLE, redisSection.getInt("max-idle")) .addKey(RedisCredentialsKeys.MIN_IDLE, redisSection.getInt("min-idle")) .addKey(RedisCredentialsKeys.MIN_EVICTABLE_IDLE_TIME, redisSection.getLong("min-evictable-idle-time")) .addKey(RedisCredentialsKeys.TIME_BETWEEN_EVICTION_RUNS, redisSection.getLong("time-between-eviction-runs")) .addKey(RedisCredentialsKeys.BLOCK_WHEN_EXHAUSTED, redisSection.getBoolean("block-when-exhausted")) .build(); final RedisMessageBrokerService messageBrokerService = new RedisMessageBrokerService( serversManager, credentials ); final ConnectionResult connectionResult = messageBrokerService.connect(); if (connectionResult == ConnectionResult.FAILURE) { getLogger().severe("Failed to connect into redis, please check credentials!"); return; } getLogger().info("Successfully connected to redis, process took " + (System.currentTimeMillis() - redisStartTime) + "ms!"); messageBrokerService.startHandler();
ServerSync.initializeInstance(serversManager, messageBrokerService);
0
2023-10-21 12:47:58+00:00
8k
neftalito/R-Info-Plus
arbol/Cuerpo.java
[ { "identifier": "Robot", "path": "form/Robot.java", "snippet": "public class Robot {\n private int ciclos;\n private ArrayList<Coord> misCalles;\n private DeclaracionProcesos procAST;\n private Cuerpo cueAST;\n private DeclaracionVariable varAST;\n private ImageIcon robotImage;\n private ArrayList<Coord> ruta;\n private ArrayList<ArrayList<Coord>> rutas;\n public int Av;\n public int Ca;\n private int direccion;\n private final PropertyChangeSupport pcs;\n private Ciudad city;\n private int floresEnBolsa;\n private int papelesEnBolsa;\n private int floresEnBolsaDeConfiguracion;\n private int papelesEnBolsaDeConfiguracion;\n private ArrayList<Area> areas;\n MonitorEsquinas esquinas;\n MonitorActualizarVentana esperarRefresco;\n public int id;\n private static int cant;\n public int offsetAv;\n public int offsetCa;\n public String dir;\n public MonitorMensajes monitor;\n String nombre;\n Color color;\n public String estado;\n\n public Robot(final Ciudad city, final String nombre) throws Exception {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotAbajo.png\"));\n this.ruta = new ArrayList<Coord>();\n this.rutas = new ArrayList<ArrayList<Coord>>();\n this.Av = 0;\n this.Ca = 0;\n this.direccion = 90;\n this.pcs = new PropertyChangeSupport(this);\n this.floresEnBolsa = 0;\n this.papelesEnBolsa = 0;\n this.floresEnBolsaDeConfiguracion = 0;\n this.papelesEnBolsaDeConfiguracion = 0;\n this.esquinas = MonitorEsquinas.getInstance();\n this.esperarRefresco = MonitorActualizarVentana.getInstance();\n this.offsetAv = 0;\n this.offsetCa = 0;\n this.misCalles = new ArrayList<Coord>();\n this.areas = new ArrayList<Area>();\n this.Av = 0;\n this.Ca = 0;\n this.getRuta().add(new Coord(this.Av, this.Ca));\n this.setNombre(nombre);\n this.city = city;\n this.rutas.add(this.ruta);\n this.id = this.getCity().robots.size();\n this.color = this.getColorById(this.id);\n this.setDireccion(90);\n this.setFlores(this.getFloresEnBolsaDeConfiguracion());\n this.setPapeles(this.getPapelesEnBolsaDeConfiguracion());\n this.estado = \"Nuevo \";\n }\n\n public void crear() throws UnknownHostException, IOException {\n this.dir = \"\";\n System.out.println(this.getId());\n if (this.id == 0) {\n final int puerto = 4000;\n File archivo = null;\n FileReader fr = null;\n BufferedReader br = null;\n archivo = new File(System.getProperty(\"user.dir\") + System.getProperty(\"file.separator\") + \"Conf.txt\");\n try {\n fr = new FileReader(archivo);\n } catch (FileNotFoundException ex) {\n Logger.getLogger(Mover.class.getName()).log(Level.SEVERE, null, ex);\n }\n br = new BufferedReader(fr);\n String ip = null;\n String linea;\n while ((linea = br.readLine()) != null) {\n System.out.println(linea);\n final String[] lineas = linea.split(\" \");\n final String robot = lineas[0];\n ip = lineas[1];\n System.out.println(\" el robot es : \" + robot + \" y la ip es : \" + ip);\n }\n this.dir = \"192.168.0.100\";\n this.dir = ip;\n } else {\n System.out.println(\"Entre al else\");\n this.dir = \"192.168.0.104\";\n final int puerto = 4000;\n }\n try (final Socket s = new Socket(this.dir, 4000)) {\n System.out.println(\"conectados\");\n final DataOutputStream dOut = new DataOutputStream(s.getOutputStream());\n dOut.writeByte(this.getId());\n dOut.flush();\n dOut.close();\n }\n }\n\n public int getCiclos() {\n return this.ciclos;\n }\n\n public void setCiclos(final int ciclos) {\n this.ciclos = ciclos;\n }\n\n public Color getColorById(final int id) {\n switch (id) {\n case 0: {\n return Color.RED;\n }\n case 1: {\n return new Color(0, 137, 221);\n }\n case 2: {\n return Color.PINK;\n }\n case 3: {\n return new Color(0, 153, 68);\n }\n case 4: {\n return Color.MAGENTA;\n }\n default: {\n final int max = 255;\n final int min = 1;\n final int x = (int) (Math.random() * (max - min + 1)) + min;\n final int y = (int) (Math.random() * (max - min + 1)) + min;\n final int z = (int) (Math.random() * (max - min + 1)) + min;\n return new Color(x, y, z);\n }\n }\n }\n\n public void almacenarMensaje(final String nombreDestino, final String valor) throws Exception {\n final Dato d = new Dato(valor, nombreDestino);\n final int id = this.getCity().getRobotByNombre(nombreDestino).id;\n this.monitor.llegoMensaje(id, d);\n }\n\n public void recibirMensaje(final Identificador nombreVariable, final int id, final Identificador NombreRobot)\n throws Exception {\n this.monitor.recibirMensaje(nombreVariable, id, NombreRobot);\n }\n\n public void Informar(final String msj) {\n this.getCity().Informar(msj, this.id);\n this.esperarRefresco.esperar(this.id);\n }\n\n public void bloquearEsquina(final int Av, final int Ca) {\n this.esquinas.bloquear(Av, Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public void liberarEsquina(final int Av, final int Ca) {\n this.esquinas.liberar(Av, Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public Cuerpo getCuerpo() {\n return this.cueAST;\n }\n\n public void agregarArea(final Area a) {\n this.areas.add(a);\n for (int i = a.getAv1(); i <= a.getAv2(); ++i) {\n for (int j = a.getCa1(); j <= a.getCa2(); ++j) {\n this.misCalles.add(new Coord(i, j));\n }\n }\n }\n\n public boolean esAreaVacia() {\n return this.areas.isEmpty();\n }\n\n public void crearMonitor(final int cant) {\n this.monitor = MonitorMensajes.crearMonitorActualizarVentana(cant, this);\n }\n\n public void setCuerpo(final Cuerpo cueAST) {\n this.cueAST = cueAST;\n }\n\n public DeclaracionVariable getVariables() {\n return this.varAST;\n }\n\n public void setVariables(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public int getFloresEnBolsaDeConfiguracion() {\n return this.floresEnBolsaDeConfiguracion;\n }\n\n public void setFloresEnBolsaDeConfiguracion(final int floresEnBolsaDeConfiguracion) {\n this.setFlores(this.floresEnBolsaDeConfiguracion = floresEnBolsaDeConfiguracion);\n }\n\n public int getPapelesEnBolsaDeConfiguracion() {\n return this.papelesEnBolsaDeConfiguracion;\n }\n\n public void setPapelesEnBolsaDeConfiguracion(final int papelesEnBolsaDeConfiguracion) {\n this.setPapeles(this.papelesEnBolsaDeConfiguracion = papelesEnBolsaDeConfiguracion);\n }\n\n public void reset() {\n this.misCalles = new ArrayList<Coord>();\n this.ruta = new ArrayList<Coord>();\n this.rutas = new ArrayList<ArrayList<Coord>>();\n this.areas = new ArrayList<Area>();\n this.rutas.add(this.ruta);\n this.setFlores(this.getFloresEnBolsaDeConfiguracion());\n this.setPapeles(this.getPapelesEnBolsaDeConfiguracion());\n try {\n this.setAv(0);\n this.setCa(0);\n } catch (Exception ex) {\n Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);\n }\n this.setDireccion(90);\n }\n\n public Image getImage() {\n switch (this.getDireccion()) {\n case 0: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotDerecha.png\"));\n break;\n }\n case 90: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotArriba.png\"));\n break;\n }\n case 180: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotIzquierda.png\"));\n break;\n }\n default: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotAbajo.png\"));\n break;\n }\n }\n return this.robotImage.getImage();\n }\n\n public String getNombre() {\n return this.nombre;\n }\n\n public void setNombre(final String nombre) {\n this.nombre = nombre;\n }\n\n public void iniciar(final int x, final int y) throws Exception {\n this.Pos(x, y);\n this.setNewX(x);\n this.setNewY(y);\n this.setFlores(this.getFlores());\n this.setPapeles(this.getPapeles());\n this.getCity().form.jsp.refresh();\n }\n\n public void choque(final String nom, final int id, final int av, final int ca) throws Exception {\n for (final Robot r : this.getCity().robots) {\n if (r.id != id && r.Av == av && r.Ca == ca) {\n this.city.parseError(\" Se produjo un choque entre el robot \" + nom + \" y el robot \" + r.getNombre()\n + \" en la avenida \" + av + \" y la calle \" + ca);\n throw new Exception(\" Se produjo un choque entre el robot \" + nom + \" y el robot \" + r.getNombre()\n + \" en la avenida \" + av + \" y la calle \" + ca);\n }\n }\n }\n\n public void mover() throws Exception {\n int av = this.PosAv();\n int ca = this.PosCa();\n switch (this.getDireccion()) {\n case 0: {\n ++av;\n break;\n }\n case 180: {\n --av;\n break;\n }\n case 90: {\n ++ca;\n break;\n }\n case 270: {\n --ca;\n break;\n }\n }\n if (!this.puedeMover(av, ca, this.areas)) {\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que no corresponde a un area asignada del robot\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que no corresponde a un area asignada del robot\");\n }\n if (this.getCity().isFreePos(ca, av)) {\n this.addPos(av, ca);\n this.setFlores(this.getFlores());\n this.setPapeles(this.getPapeles());\n this.choque(this.nombre, this.id, this.Av, this.Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n return;\n }\n this.city.parseError(\"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que hay un obst\\u00e1culo\");\n throw new Exception(\"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que hay un obst\\u00e1culo\");\n }\n\n public boolean puedeMover(final int av, final int ca, final ArrayList<Area> areas) {\n for (final Coord c : this.misCalles) {\n if (c.getX() == av && c.getY() == ca) {\n return true;\n }\n }\n return false;\n }\n\n public int[] getXCoord() {\n final int[] x = new int[this.ruta.size()];\n for (int c = 0; c < this.ruta.size(); ++c) {\n final Coord p = this.ruta.get(c);\n x[c] = p.getX();\n }\n return x;\n }\n\n public int[] getYCoord() {\n final int[] y = new int[this.ruta.size() + 1];\n for (int c = 0; c < this.ruta.size(); ++c) {\n final Coord p = this.ruta.get(c);\n y[c] = p.getY();\n }\n return y;\n }\n\n public void addPos(final int av, final int ca) throws Exception {\n try {\n final int old = this.city.ciudad[av][ca].getFlores();\n this.setAv(av);\n this.setCa(ca);\n this.pcs.firePropertyChange(\"esquinaFlores\", old, this.city.ciudad[av][ca].getFlores());\n } catch (Exception e) {\n throw new Exception(\"Una de las nuevas coordenadas cae fuera de la ciudad.Av: \" + av + \" Ca: \" + ca\n + \" Calles: \" + this.city.getNumCa() + \" Avenidas: \" + this.city.getNumAv());\n }\n }\n\n public void setAv(final int av) throws Exception {\n if (av > this.city.getNumAv()) {\n throw new Exception();\n }\n if (av != this.PosAv()) {\n this.ruta.add(new Coord(av, this.PosCa()));\n if (av > this.PosAv()) {\n this.setDireccion(0);\n } else {\n this.setDireccion(180);\n }\n }\n this.setNewX(av);\n this.setNewY(this.Ca);\n }\n\n public void setNewX(final int av) {\n final int old = this.PosAv();\n this.Av = av;\n this.pcs.firePropertyChange(\"av\", old, av);\n }\n\n public void setNewY(final int ca) {\n final int old = this.PosCa();\n this.Ca = ca;\n this.pcs.firePropertyChange(\"ca\", old, ca);\n }\n\n public void setCa(final int ca) throws Exception {\n if (ca > this.city.getNumCa()) {\n throw new Exception();\n }\n if (ca != this.PosCa()) {\n this.ruta.add(new Coord(this.PosAv(), ca));\n if (ca < this.PosCa()) {\n this.setDireccion(270);\n } else {\n this.setDireccion(90);\n }\n }\n this.setNewY(ca);\n this.setNewX(this.Av);\n }\n\n public void setDireccion(final int direccion) {\n final int old = this.direccion;\n this.direccion = direccion;\n this.pcs.firePropertyChange(\"direccion\", old, direccion);\n }\n\n public void setEstado(final String str) {\n final String s = this.getEstado();\n this.estado = str;\n this.pcs.firePropertyChange(\"estado\", s, str);\n }\n\n public String getEstado() {\n return this.estado;\n }\n\n public int getDireccion() {\n return this.direccion;\n }\n\n public void addPropertyChangeListener(final PropertyChangeListener listener) {\n this.pcs.addPropertyChangeListener(listener);\n }\n\n public void removePropertyChangeListener(final PropertyChangeListener listener) {\n this.pcs.removePropertyChangeListener(listener);\n }\n\n public void mirarEnDireccion(final int direccion) throws Exception {\n int c;\n for (c = 0; c < 5 && this.getDireccion() != direccion; ++c) {\n this.derecha();\n }\n if (c == 5) {\n throw new Exception(\"La direcci\\u00f3n especificada no corresponde.\");\n }\n }\n\n public void izquierda() {\n switch (this.getDireccion()) {\n case 0: {\n this.setDireccion(90);\n break;\n }\n case 270: {\n this.setDireccion(0);\n break;\n }\n case 180: {\n this.setDireccion(270);\n break;\n }\n case 90: {\n this.setDireccion(180);\n break;\n }\n }\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public void derecha() {\n switch (this.getDireccion()) {\n case 0: {\n this.setDireccion(270);\n break;\n }\n case 270: {\n this.setDireccion(180);\n break;\n }\n case 180: {\n this.setDireccion(90);\n break;\n }\n case 90: {\n this.setDireccion(0);\n break;\n }\n }\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public int PosCa() {\n return this.Ca;\n }\n\n public int PosAv() {\n return this.Av;\n }\n\n public void Pos(final int Av, final int Ca) throws Exception {\n if (!this.puedeMover(Av, Ca, this.areas)) {\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que no corresponde a un area asignada del robot\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que no corresponde a un area asignada del robot\");\n }\n if (this.getCity().isFreePos(Ca, Av)) {\n this.getRutas().add(this.getRuta());\n this.setRuta(new ArrayList<Coord>());\n this.getRuta().add(new Coord(Av, Ca));\n this.setNewX(Av);\n this.setNewY(Ca);\n this.choque(this.nombre, this.id, Av, Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n return;\n }\n this.city.parseError(\"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que hay un obst\\u00e1culo\");\n throw new Exception(\"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que hay un obst\\u00e1culo\");\n }\n\n public ArrayList<Coord> getRuta() {\n return this.ruta;\n }\n\n public Ciudad getCity() {\n return this.city;\n }\n\n public void tomarFlor() throws Exception {\n if (this.getCity().levantarFlor(this.PosAv(), this.PosCa())) {\n this.setFlores(this.getFlores() + 1);\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.setFlores(this.getFlores());\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"tomarFlor\\\" debido a que no hay ninguna flor en la esquina\");\n }\n\n public int getFlores() {\n return this.floresEnBolsa;\n }\n\n public void setFlores(final int flores) {\n final int old = this.getFlores();\n this.floresEnBolsa = flores;\n this.pcs.firePropertyChange(\"flores\", old, flores);\n }\n\n public void tomarPapel() throws Exception {\n if (this.getCity().levantarPapel(this.PosAv(), this.PosCa())) {\n this.setPapeles(this.getPapeles() + 1);\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.setPapeles(this.getPapeles());\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"tomarPapel\\\" debido a que no hay ningun papel en la esquina\");\n }\n\n public boolean HayPapelEnLaBolsa() {\n return this.getPapeles() > 0;\n }\n\n public boolean HayFlorEnLaBolsa() {\n return this.getFlores() > 0;\n }\n\n public int getPapeles() {\n return this.papelesEnBolsa;\n }\n\n public void setColor(final Color col) {\n final Color old = this.color;\n this.color = col;\n this.pcs.firePropertyChange(\"color\", old, col);\n }\n\n public Color getColor() {\n return this.color;\n }\n\n public void setPapeles(final int papeles) {\n final int old = this.getPapeles();\n this.papelesEnBolsa = papeles;\n this.pcs.firePropertyChange(\"papeles\", old, papeles);\n }\n\n public void depositarPapel() throws Exception {\n if (this.getPapeles() > 0) {\n this.setPapeles(this.getPapeles() - 1);\n this.getCity().dejarPapel(this.PosAv(), this.PosCa());\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarPapel\\\" debido a que no hay ningun papel en la bolsa\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarPapel\\\" debido a que no hay ningun papel en la bolsa\");\n }\n\n public void depositarFlor() throws Exception {\n if (this.getFlores() > 0) {\n this.setFlores(this.getFlores() - 1);\n this.getCity().dejarFlor(this.PosAv(), this.PosCa());\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarFlor\\\" debido a que no hay ninguna en la bolsa de flores\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarFlor\\\" debido a que no hay ninguna en la bolsa de flores\");\n }\n\n public ArrayList<ArrayList<Coord>> getRutas() {\n return this.rutas;\n }\n\n public void setRuta(final ArrayList<Coord> ruta) {\n this.ruta = ruta;\n }\n\n public void setRutas(final ArrayList<ArrayList<Coord>> rutas) {\n this.rutas = rutas;\n }\n\n public DeclaracionProcesos getProcAST() {\n return this.procAST;\n }\n\n public void setProcAST(final DeclaracionProcesos procAST) throws CloneNotSupportedException {\n synchronized (this) {\n final ArrayList<Proceso> ps = new ArrayList<Proceso>();\n for (final Proceso j : procAST.getProcesos()) {\n final DeclaracionVariable ddvv = j.getDV();\n final Identificador I = new Identificador(j.getI().toString());\n final ArrayList<ParametroFormal> pfs = new ArrayList<ParametroFormal>();\n for (final ParametroFormal pformal : j.getPF()) {\n final Identificador In = new Identificador(pformal.getI().toString());\n final ParametroFormal pf = new ParametroFormal(In, pformal.getT(), pformal.getTA());\n pfs.add(pf);\n }\n final ArrayList<Sentencia> ss = new ArrayList<Sentencia>();\n for (final Sentencia sen : j.getC().getS()) {\n System.out.println(\"Sentencia : \" + sen.toString());\n final Sentencia s = (Sentencia) sen.clone();\n ss.add(s);\n }\n final ArrayList<Variable> dvs = new ArrayList<Variable>();\n for (final Variable v : ddvv.variables) {\n final Variable V = (Variable) v.clone();\n dvs.add(V);\n }\n final DeclaracionVariable ddvs = new DeclaracionVariable(dvs);\n final Cuerpo cue = new Cuerpo(ss, ddvs);\n final Proceso p = new Proceso(I, pfs, procAST, ddvs, cue);\n ps.add(p);\n }\n final DeclaracionProcesos dp = new DeclaracionProcesos(ps);\n this.procAST = dp;\n }\n }\n\n public DeclaracionVariable getVarAST() {\n return this.varAST;\n }\n\n public void setVarAST(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public int getId() {\n return this.id;\n }\n\n public void setId(final int id) {\n this.id = id;\n }\n\n static {\n Robot.cant = 0;\n }\n}" }, { "identifier": "Sentencia", "path": "arbol/sentencia/Sentencia.java", "snippet": "public abstract class Sentencia extends AST {\n DeclaracionVariable varAST;\n Robot r;\n\n public Robot getRobot() {\n return this.r;\n }\n\n public void setRobot(final Robot r) {\n this.r = r;\n }\n\n public void ejecutar() throws Exception {\n }\n\n public void setDV(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public DeclaracionVariable getDV() {\n return this.varAST;\n }\n\n @Override\n public void setPrograma(final Programa P) {\n this.programa = P;\n }\n\n @Override\n public Programa getPrograma() {\n return this.programa;\n }\n}" } ]
import form.Robot; import arbol.sentencia.Sentencia; import java.util.ArrayList;
6,508
package arbol; public class Cuerpo extends AST { private ArrayList<Sentencia> S; DeclaracionVariable varAST;
package arbol; public class Cuerpo extends AST { private ArrayList<Sentencia> S; DeclaracionVariable varAST;
Robot rob;
0
2023-10-20 15:45:37+00:00
8k
wevez/ClientCoderPack
src/tech/tenamen/Main.java
[ { "identifier": "Client", "path": "src/tech/tenamen/client/Client.java", "snippet": "public class Client implements Downloadable {\n\n private String VERSION_NAME;\n private File JSON_FILE, JAR_FILE;\n\n private final List<Library> LIBRARIES = new ArrayList<>();\n public Asset asset;\n\n private int javaMajorVersion = -1;\n\n public Client(final File folder) throws Exception {\n if (!folder.isFile()) {\n final List<File> JSON_CANDIDATE = new ArrayList<>(), JAR_CANDIDATE = new ArrayList<>();\n // collect json and jar candidates\n for (final File f : Objects.requireNonNull(folder.listFiles())) {\n if (!f.isFile()) continue;\n final String upperFileName = f.getName().toUpperCase();\n if (upperFileName.endsWith(\".JSON\")) {\n JSON_CANDIDATE.add(f);\n } else if (upperFileName.endsWith(\".JAR\")) {\n JAR_CANDIDATE.add(f);\n }\n }\n for (File jsonCandidate : JSON_CANDIDATE) {\n final String jsonFileRawName = jsonCandidate.getName();\n final String jsonFileName = jsonFileRawName.substring(0, jsonFileRawName.length() - \".json\".length());\n for (File jarCandidate : JAR_CANDIDATE) {\n final String jarFileRawName = jarCandidate.getName();\n final String jarFileName = jarFileRawName.substring(0, jarFileRawName.length() - \".jar\".length());\n if (jsonFileName.equalsIgnoreCase(jarFileName)) {\n this.VERSION_NAME = jsonFileName;\n this.JAR_FILE = jarCandidate;\n this.JSON_FILE = jsonCandidate;\n break;\n }\n }\n if (JSON_FILE != null && JAR_FILE != null && VERSION_NAME != null) break;\n }\n if (JSON_FILE == null) throw new Exception(\"The folder doesn't have json\");\n if (JAR_FILE == null) throw new Exception(\"The folder doesn't have jar\");\n if (VERSION_NAME == null) throw new Exception(\"The name is null\");\n } else {\n throw new Exception(\"The folder is not folder\");\n }\n }\n\n public void parseDependencies() {\n JsonObject object = null;\n try {\n object = new GsonBuilder().setPrettyPrinting().create().fromJson(new FileReader(this.JSON_FILE), JsonObject.class);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n if (object == null) return;\n // arguments\n if (object.has(\"arguments\")) {\n // TODO make launch property from json\n final JsonObject arguments = object.getAsJsonObject(\"arguments\");\n }\n // asset index\n if (object.has(\"assetIndex\")) {\n final JsonObject assetIndex = object.getAsJsonObject(\"assetIndex\");\n String assetId = null, assetSha1 = null, assetUrl = null;\n long assetSize = -1, assetTutorialSize = -1;\n if (assetIndex.has(\"id\")) assetId = assetIndex.get(\"id\").getAsString();\n if (assetIndex.has(\"sha1\")) assetSha1 = assetIndex.get(\"sha1\").getAsString();\n if (assetIndex.has(\"url\")) assetUrl = assetIndex.get(\"url\").getAsString();\n if (assetIndex.has(\"size\")) assetSize = assetIndex.get(\"size\").getAsLong();\n if (assetIndex.has(\"totalSize\")) assetTutorialSize = assetIndex.get(\"totalSize\").getAsLong();\n if (assetId != null && assetSha1 != null && assetUrl != null && assetSize != -1 && assetTutorialSize != -1) {\n asset = new Asset(assetId, assetSha1, assetSize, assetTutorialSize, assetUrl);\n }\n }\n // downloads\n if (object.has(\"downloads\")) {\n final JsonObject downloads = object.getAsJsonObject(\"downloads\");\n if (downloads.has(\"client\")) {\n final JsonObject client = downloads.getAsJsonObject(\"client\");\n new Thread(() -> {\n NetUtil.download(client.get(\"url\").getAsString(), new File(Main.LIBRARIES_DIR, \"client.jar\"));\n }).start();\n Main.IDE.getLibraryNames().add(\"client.jar\");\n }\n if (downloads.has(\"client_mappings\")) {\n final JsonObject clientMappings = downloads.getAsJsonObject(\"client_mappings\");\n }\n if (downloads.has(\"server\")) {\n final JsonObject server = downloads.getAsJsonObject(\"server\");\n }\n if (downloads.has(\"server_mappings\")) {\n final JsonObject serverMappings = downloads.getAsJsonObject(\"server_mappings\");\n }\n }\n // java version\n if (object.has(\"javaVersion\")) {\n final JsonObject javaVersion = object.getAsJsonObject(\"javaVersion\");\n // if (javaVersion.has(\"component\"))\n if (javaVersion.has(\"majorVersion\")) this.javaMajorVersion = javaVersion.get(\"majorVersion\").getAsInt();\n }\n if (object.has(\"libraries\")) {\n final JsonArray libraries = object.getAsJsonArray(\"libraries\");\n for (JsonElement e : libraries) {\n String libName = null, libPath = null, libSha1 = null, libUrl = null;\n long libSize = -1;\n final OSRule osRule = new OSRule();\n final List<NativeLibrary> nativeLibraries = new ArrayList<>();\n final JsonObject library = e.getAsJsonObject();\n if (library.has(\"downloads\")) {\n final JsonObject downloads = library.getAsJsonObject(\"downloads\");\n if (downloads.has(\"artifact\")) {\n final JsonObject artifact = downloads.getAsJsonObject(\"artifact\");\n if (artifact.has(\"path\")) libPath = artifact.get(\"path\").getAsString();\n if (artifact.has(\"sha1\")) libSha1 = artifact.get(\"sha1\").getAsString();\n if (artifact.has(\"url\")) libUrl = artifact.get(\"url\").getAsString();\n if (artifact.has(\"size\")) libSize = artifact.get(\"size\").getAsLong();\n }\n if (downloads.has(\"classifiers\")) {\n final JsonObject classifiers = downloads.getAsJsonObject(\"classifiers\");\n final Map<String, JsonObject> nativeObjects = new HashMap<>();\n if (classifiers.has(\"natives-windows\")) {\n nativeObjects.put(\"natives-windows\", classifiers.getAsJsonObject(\"natives-windows\"));\n }\n if (classifiers.has(\"natives-linux\")) {\n nativeObjects.put(\"natives-linux\", classifiers.getAsJsonObject(\"natives-linux\"));\n }\n if (classifiers.has(\"natives-macos\")) {\n nativeObjects.put(\"natives-macos\", classifiers.getAsJsonObject(\"natives-macos\"));\n }\n nativeObjects.forEach((k, v) -> {\n String nativePath = null, nativeSha1 = null, nativeUrl = null;\n long nativeSize = -1;\n if (v.has(\"path\")) nativePath = v.get(\"path\").getAsString();\n if (v.has(\"sha1\")) nativeSha1 = v.get(\"sha1\").getAsString();\n if (v.has(\"url\")) nativeUrl = v.get(\"url\").getAsString();\n if (v.has(\"size\")) nativeSize = v.get(\"size\").getAsLong();\n if (nativePath != null && nativeSha1 != null && nativeUrl != null && nativeSize != -1) {\n nativeLibraries.add(new NativeLibrary(k, nativePath, nativeSha1, nativeSize, nativeUrl));\n }\n });\n }\n }\n if (library.has(\"name\")) {\n libName = library.get(\"name\").getAsString();\n }\n if (library.has(\"rules\")) {\n for (JsonElement r : library.getAsJsonArray(\"rules\")) {\n // os\n final JsonObject rule = r.getAsJsonObject();\n if (rule.has(\"action\")) {\n final String action = rule.get(\"action\").getAsString();\n osRule.setAllow(action.equalsIgnoreCase(\"allow\"));\n }\n if (rule.has(\"os\")) {\n final JsonObject os = rule.getAsJsonObject(\"os\");\n if (os.has(\"name\")) osRule.setOSName(os.get(\"name\").getAsString());\n }\n }\n }\n if (libName != null && libPath != null && libSha1 != null && libUrl != null && libSize != -1) {\n this.LIBRARIES.add(new Library(libName, libPath, libSha1, libSize, libUrl, osRule, nativeLibraries));\n }\n }\n }\n // release time\n if (object.has(\"releaseTime\")) {\n final String releaseTime = object.get(\"releaseTime\").getAsString();\n }\n // time\n if (object.has(\"time\")) {\n final String time = object.get(\"time\").getAsString();\n }\n // type\n if (object.has(\"type\")) {\n final String type = object.get(\"type\").getAsString();\n }\n Main.IDE.getLibraryNames().add(\"jsr305-3.0.2.jar\");\n }\n\n public final String getVersionName() { return this.VERSION_NAME; }\n\n @Override\n public void download(OS os) {\n final List<Thread> threads = new ArrayList<>();\n this.LIBRARIES.forEach(l -> {\n threads.add(new Thread(() -> {\n l.download(os);\n }));\n });\n this.asset.download(os);\n threads.addAll(this.asset.threads);\n for (Thread thread : threads) {\n thread.run();\n }\n for (Thread thread : threads) {\n try {\n thread.join();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n public int getJavaMajorVersion() { return this.javaMajorVersion; }\n\n}" }, { "identifier": "IDE", "path": "src/tech/tenamen/ide/IDE.java", "snippet": "public abstract class IDE {\n\n private final List<String> LIBRARY_NAMES = new ArrayList<>();\n private final List<String> NATIVE_NAMES = new ArrayList<>();\n\n public final List<String> getLibraryNames() { return this.LIBRARY_NAMES; }\n public final List<String> getNativeNames() { return this.NATIVE_NAMES; }\n\n public abstract void createProperties();\n\n}" }, { "identifier": "InteliJIDE", "path": "src/tech/tenamen/ide/InteliJIDE.java", "snippet": "public class InteliJIDE extends IDE {\n\n private static File PROPERTY_DIR, IDE_LIBRARIES_DIR;\n\n @Override\n public void createProperties() {\n PROPERTY_DIR = new File(Main.WORKING_DIR, \".idea\");\n PROPERTY_DIR.mkdirs();\n IDE_LIBRARIES_DIR = new File(PROPERTY_DIR, \"libraries\");\n IDE_LIBRARIES_DIR.mkdirs();\n // .gitignore\n System.out.println(\"Making .gitignore\");\n this.makeGitignore();\n // .name\n System.out.println(\"Making .name\");\n this.makeName();\n // misc.xml\n System.out.println(\"Making misc.xml\");\n this.makeMisc();\n // modules.xml\n System.out.println(\"Making modules.xml\");\n this.makeModules();\n // vcs.xml\n System.out.println(\"Making vcs.xml\");\n this.makeVCS();\n // workspace.xml\n System.out.println(\"Making workspace.xml\");\n this.makeWorkspace();\n // libraries\n System.out.println(\"Making libraries\");\n this.makeLibraries();\n // iml\n System.out.println(\"Making iml\");\n this.makeIml();\n }\n\n private void makeGitignore() {\n final File gitignoreFile = new File(PROPERTY_DIR, \".gitignore\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"# Default ignored files\\n/shelf/\\n/workspace.xml\\n\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeName() {\n final File gitignoreFile = new File(PROPERTY_DIR, \".name\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(Main.WORKING_DIR.getName());\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeMisc() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"misc.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(String.format(\" <component name=\\\"ProjectRootManager\\\" version=\\\"2\\\" languageLevel=\\\"JDK_%d\\\" default=\\\"true\\\" project-jdk-name=\\\"%d\\\" project-jdk-type=\\\"JavaSDK\\\">\\n\",\n Main.client.getJavaMajorVersion(), Main.client.getJavaMajorVersion()));\n writer.write(\" <output url=\\\"file://$PROJECT_DIR$/out\\\" />\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeModules() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"modules.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(\" <component name=\\\"ProjectModuleManager\\\">\\n\");\n writer.write(\" <modules>\\n\");\n writer.write(String.format(\" <module fileurl=\\\"file://$PROJECT_DIR$/%s.iml\\\" filepath=\\\"$PROJECT_DIR$/%s.iml\\\" />\\n\",\n Main.WORKING_DIR.getName(), Main.WORKING_DIR.getName()));\n writer.write(\" </modules>\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeVCS() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"vcs.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(\" <component name=\\\"VcsDirectoryMappings\\\">\\n\");\n writer.write(\" <mapping directory=\\\"\\\" vcs=\\\"Git\\\" />\\n\");\n writer.write(\" <mapping directory=\\\"$PROJECT_DIR$\\\" vcs=\\\"Git\\\" />\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeWorkspace() {\n final File gitignoreFile = new File(PROPERTY_DIR, \"workspace.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<project version=\\\"4\\\">\\n\");\n writer.write(\"</project>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeLibraries() {\n final File gitignoreFile = new File(IDE_LIBRARIES_DIR, \"ccp.xml\");\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<component name=\\\"libraryTable\\\">\\n\");\n writer.write(\" <library name=\\\"ccp\\\">\\n\");\n writer.write(\" <CLASSES>\\n\");\n for (String libraryName : this.getLibraryNames()) {\n writer.write(String.format(\" <root url=\\\"jar://$PROJECT_DIR$/libraries/%s!/\\\" />\\n\", libraryName));\n }\n writer.write(\" </CLASSES>\\n\");\n writer.write(\" <JAVADOC />\\n\");\n writer.write(\" <NATIVE>\\n\");\n writer.write(\" <root url=\\\"file://$PROJECT_DIR$/libraries/natives\\\" />\\n\");\n writer.write(\" </NATIVE>\\n\");\n writer.write(\" <SOURCES />\\n\");\n writer.write(\" </library>\\n\");\n writer.write(\"</component>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n private void makeIml() {\n final File gitignoreFile = new File(Main.WORKING_DIR, String.format(\"%s.iml\", Main.WORKING_DIR.getName()));\n FileWriter writer = null;\n try {\n writer = new FileWriter(gitignoreFile);\n writer.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\");\n writer.write(\"<module type=\\\"JAVA_MODULE\\\" version=\\\"4\\\">\\n\");\n writer.write(\" <component name=\\\"NewModuleRootManager\\\" inherit-compiler-output=\\\"true\\\">\\n\");\n writer.write(\" <exclude-output />\\n\");\n writer.write(\" <content url=\\\"file://$MODULE_DIR$\\\">\\n\");\n writer.write(\" <sourceFolder url=\\\"file://$MODULE_DIR$/src\\\" isTestSource=\\\"false\\\" />\\n\");\n writer.write(\" </content>\\n\");\n writer.write(\" <orderEntry type=\\\"inheritedJdk\\\" />\\n\");\n writer.write(\" <orderEntry type=\\\"sourceFolder\\\" forTests=\\\"false\\\" />\\n\");\n writer.write(\" <orderEntry type=\\\"library\\\" name=\\\"ccp\\\" level=\\\"project\\\" />\\n\");\n writer.write(\" </component>\\n\");\n writer.write(\"</module>\");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}" }, { "identifier": "OS", "path": "src/tech/tenamen/property/OS.java", "snippet": "public enum OS {\n\n WINDOWS(\"windows\", \"natives-windows\"),\n MAC(\"osx\", \"natives-macos\"),\n LINUX(\"linux\", \"natives-linux\");\n\n private final String OS_RULE_NAME, NATIVE_OS_NAME;\n\n OS(final String OS_RULE_NAME, final String NATIVE_OS_NAME) {\n this.OS_RULE_NAME = OS_RULE_NAME;\n this.NATIVE_OS_NAME = NATIVE_OS_NAME;\n }\n\n public String toOsRule() { return OS_RULE_NAME; }\n public String toNativeOs() { return NATIVE_OS_NAME; }\n}" } ]
import tech.tenamen.client.Client; import tech.tenamen.ide.IDE; import tech.tenamen.ide.InteliJIDE; import tech.tenamen.property.OS; import java.io.File; import java.util.Scanner;
4,323
package tech.tenamen; public class Main { public static IDE IDE = new InteliJIDE();
package tech.tenamen; public class Main { public static IDE IDE = new InteliJIDE();
public static Client client;
0
2023-10-20 06:56:19+00:00
8k
Invadermonky/Omniwand
src/main/java/com/invadermonky/omniwand/network/MessageRevertWand.java
[ { "identifier": "Omniwand", "path": "src/main/java/com/invadermonky/omniwand/Omniwand.java", "snippet": "@Mod(\n modid = Omniwand.MOD_ID,\n name = Omniwand.MOD_NAME,\n version = Omniwand.MOD_VERSION,\n acceptedMinecraftVersions = Omniwand.MC_VERSION,\n guiFactory = Omniwand.GUI_FACTORY\n)\npublic class Omniwand {\n public static final String MOD_ID = \"omniwand\";\n public static final String MOD_NAME = \"Omniwand\";\n public static final String MOD_VERSION = \"1.12.2-1.0.1\";\n public static final String GUI_FACTORY = \"com.invadermonky.omniwand.client.GuiFactory\";\n public static final String MC_VERSION = \"[1.12.2]\";\n\n public static final String ProxyClientClass = \"com.invadermonky.omniwand.proxy.ClientProxy\";\n public static final String ProxyServerClass = \"com.invadermonky.omniwand.proxy.CommonProxy\";\n\n public static SimpleNetworkWrapper network;\n\n @Mod.Instance(MOD_ID)\n public static Omniwand INSTANCE;\n\n @SidedProxy(clientSide = ProxyClientClass, serverSide = ProxyServerClass)\n public static CommonProxy proxy;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n LogHelper.info(\"Starting Omniwand.\");\n\n //Config and config event subscriber\n ConfigHandler.preInit();\n MinecraftForge.EVENT_BUS.register(new ConfigHandler());\n\n proxy.preInit(event);\n LogHelper.debug(\"Finished preInit phase.\");\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.init(event);\n LogHelper.debug(\"Finished init phase.\");\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n LogHelper.debug(\"Finished postInit phase.\");\n }\n}" }, { "identifier": "TransformHandler", "path": "src/main/java/com/invadermonky/omniwand/handlers/TransformHandler.java", "snippet": "public class TransformHandler {\n public static final TransformHandler INSTANCE = new TransformHandler();\n public static final THashMap<String,String> modNames = new THashMap<>();\n\n public static boolean autoMode = true;\n\n @SubscribeEvent\n public void onItemDropped(ItemTossEvent event) {\n if(event.getPlayer().isSneaking()) {\n EntityItem e = event.getEntityItem();\n ItemStack stack = e.getItem();\n TransformHandler.removeItemFromWand(e, stack, false, e::setItem);\n autoMode = true;\n }\n }\n\n @SubscribeEvent\n public void onItemBroken(PlayerDestroyItemEvent event) {\n TransformHandler.removeItemFromWand(event.getEntityPlayer(), event.getOriginal(), true, (transform) -> {\n event.getEntityPlayer().setHeldItem(event.getHand(), transform);\n autoMode = true;\n });\n }\n\n @SideOnly(Side.CLIENT)\n @SubscribeEvent\n public void onPlayerSwing(PlayerInteractEvent.LeftClickEmpty event) {\n ItemStack stack = event.getItemStack();\n if(!ConfigHandler.crouchRevert || event.getEntityPlayer().isSneaking()) {\n if (stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) {\n Omniwand.network.sendToServer(new MessageRevertWand());\n autoMode = true;\n }\n }\n }\n\n public static NBTTagCompound getWandNBTData(ItemStack stack) {\n return stack.getTagCompound().getCompoundTag(References.TAG_WAND_DATA);\n }\n\n public static String getModFromState(IBlockState state) {\n return getModOrAlias(state.getBlock().getRegistryName().getNamespace());\n }\n\n public static String getModFromStack(ItemStack stack) {\n return getModOrAlias(stack.getItem().getCreatorModId(stack));\n }\n\n public static String getModOrAlias(String mod) {\n return ConfigHandler.modAliases.getOrDefault(mod, mod);\n }\n\n public static ItemStack getTransformStackForMod(ItemStack stack, String mod) {\n if(!stack.hasTagCompound()) {\n return stack;\n } else {\n String currentMod = getModFromStack(stack);\n if(mod.equals(currentMod)) {\n return stack;\n } else {\n NBTTagCompound transformData = getWandNBTData(stack);\n return makeTransformedStack(stack, mod, transformData);\n }\n }\n }\n\n public static ItemStack makeTransformedStack(ItemStack currStack, String targetMod, NBTTagCompound transformData) {\n String currMod = NBTHelper.getString(currStack, References.TAG_ITEM_DEFINED_MOD, getModFromStack(currStack));\n NBTTagCompound currTag = new NBTTagCompound();\n currStack.writeToNBT(currTag);\n currTag = currTag.copy();\n\n if(currTag.hasKey(\"tag\")) {\n currTag.getCompoundTag(\"tag\").removeTag(References.TAG_WAND_DATA);\n }\n\n if(!currMod.equalsIgnoreCase(References.MINECRAFT) && !currMod.equalsIgnoreCase(Omniwand.MOD_ID)) {\n transformData.setTag(currMod, currTag);\n }\n\n ItemStack stack;\n NBTTagCompound stackTag;\n\n if(targetMod.equals(References.MINECRAFT)) {\n stack = new ItemStack(RegistryOW.OMNIWAND);\n } else {\n stackTag = transformData.getCompoundTag(targetMod);\n transformData.removeTag(targetMod);\n stack = new ItemStack(stackTag);\n\n if(stack.isEmpty())\n stack = new ItemStack(RegistryOW.OMNIWAND);\n }\n\n if(!stack.hasTagCompound())\n stack.setTagCompound(new NBTTagCompound());\n\n stackTag = stack.getTagCompound();\n stackTag.setTag(References.TAG_WAND_DATA, transformData);\n stackTag.setBoolean(References.TAG_IS_TRANSFORMING, true);\n\n if(stack.getItem() != RegistryOW.OMNIWAND) {\n String displayName = stack.getDisplayName();\n if(stackTag.hasKey(References.TAG_WAND_DISPLAY_NAME))\n displayName = stackTag.getString(References.TAG_WAND_DISPLAY_NAME);\n else\n stackTag.setString(References.TAG_WAND_DISPLAY_NAME, displayName);\n\n stack.setStackDisplayName(TextFormatting.RESET + net.minecraft.util.text.translation.I18n.translateToLocalFormatted(\"omniwand:sudo_name\", TextFormatting.GREEN + displayName + TextFormatting.RESET));\n //stack.setStackDisplayName(TextFormatting.RESET + I18n.format(\"omniwand:sudo_name\", TextFormatting.GREEN + displayName + TextFormatting.RESET));\n }\n stack.setCount(1);\n return stack;\n }\n\n public static void removeItemFromWand(Entity entity, ItemStack stack, boolean isBroken, Consumer<ItemStack> consumer) {\n if(!stack.isEmpty() && isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) {\n\n NBTTagCompound transformData = getWandNBTData(stack).copy();\n ItemStack transform = makeTransformedStack(stack, References.MINECRAFT, transformData);\n NBTTagCompound newTransformData = getWandNBTData(transform);\n\n String currMod = NBTHelper.getString(stack, References.TAG_ITEM_DEFINED_MOD, getModFromStack(stack));\n newTransformData.removeTag(currMod);\n\n if (!isBroken) {\n if (!entity.getEntityWorld().isRemote) {\n EntityItem newItem = new EntityItem(entity.getEntityWorld(), entity.posX, entity.posY, entity.posZ, transform);\n entity.getEntityWorld().spawnEntity(newItem);\n }\n\n ItemStack copy = stack.copy();\n NBTTagCompound copyTag = copy.getTagCompound();\n if (copyTag == null) {\n copyTag = new NBTTagCompound();\n copy.setTagCompound(copyTag);\n }\n\n copyTag.removeTag(\"display\");\n String displayName = copyTag.getString(References.TAG_WAND_DISPLAY_NAME);\n\n if (!displayName.isEmpty() && !displayName.equals(copy.getDisplayName()))\n copy.setStackDisplayName(displayName);\n\n copyTag.removeTag(References.TAG_IS_TRANSFORMING);\n copyTag.removeTag(References.TAG_AUTO_TRANSFORM);\n copyTag.removeTag(References.TAG_WAND_DISPLAY_NAME);\n copyTag.removeTag(References.TAG_WAND_DATA);\n copyTag.removeTag(References.TAG_ITEM_DEFINED_MOD);\n\n consumer.accept(copy);\n } else {\n consumer.accept(transform);\n }\n }\n }\n\n public static String getModNameForId(String modId) {\n modId = modId.toLowerCase(Locale.ENGLISH);\n return modNames.getOrDefault(modId, modId);\n }\n\n public static boolean isOmniwand(ItemStack stack) {\n if(stack.isEmpty())\n return false;\n else if(stack.getItem() == RegistryOW.OMNIWAND)\n return true;\n else\n return stack.hasTagCompound() && stack.getTagCompound().getBoolean(References.TAG_IS_TRANSFORMING);\n }\n\n static {\n for(Map.Entry<String, ModContainer> entry : Loader.instance().getIndexedModList().entrySet()) {\n modNames.put(entry.getKey().toLowerCase().toLowerCase(Locale.ENGLISH), entry.getValue().getName());\n }\n }\n}" }, { "identifier": "RegistryOW", "path": "src/main/java/com/invadermonky/omniwand/init/RegistryOW.java", "snippet": "@Mod.EventBusSubscriber(modid = Omniwand.MOD_ID)\npublic class RegistryOW {\n public static Item OMNIWAND;\n\n @SubscribeEvent\n public static void registerItems(RegistryEvent.Register<Item> event) {\n IForgeRegistry<Item> registry = event.getRegistry();\n OMNIWAND = new ItemWand(\"wand\");\n registry.register(OMNIWAND);\n }\n\n @SubscribeEvent\n public static void registerItemRenders(ModelRegistryEvent event) {\n LogHelper.debug(\"Registering model of item: \" + OMNIWAND.delegate.name());\n ModelResourceLocation loc;\n \n if(ConfigHandler.alternateAppearance)\n loc = new ModelResourceLocation(new ResourceLocation(Omniwand.MOD_ID, \"wand_alt\"), \"inventory\");\n else\n loc = new ModelResourceLocation(OMNIWAND.delegate.name(), \"inventory\");\n\n ModelLoader.setCustomModelResourceLocation(OMNIWAND, 0, loc);\n }\n\n @SubscribeEvent\n public static void registerRecipes(RegistryEvent.Register<IRecipe> event) {\n IForgeRegistry<IRecipe> registry = event.getRegistry();\n registry.register(((ItemWand) OMNIWAND).getAttachmentRecipe());\n }\n}" }, { "identifier": "References", "path": "src/main/java/com/invadermonky/omniwand/util/References.java", "snippet": "public class References {\n public static final String MINECRAFT = \"minecraft\";\n\n public static final String TAG_IS_TRANSFORMING = \"omniwand:is_transforming\";\n public static final String TAG_AUTO_TRANSFORM = \"omniwand:auto_transform\";\n public static final String TAG_WAND_DATA = \"omniwand:data\";\n public static final String TAG_WAND_DISPLAY_NAME = \"omniwand:displayName\";\n public static final String TAG_ITEM_DEFINED_MOD = \"omniwand:definedMod\";\n\n public static final Property ENABLE_TRANSFORM = new Property(\"enableTransforms\", \"true\", Property.Type.BOOLEAN);\n public static final Property RESTRICT_TOOLTIP = new Property(\"restrictTooltip\", \"true\", Property.Type.BOOLEAN);\n public static final Property OFFHAND_TRANSFORM = new Property(\"offhandTransformOnly\", \"false\", Property.Type.BOOLEAN);\n public static final Property CROUCH_REVERT = new Property(\"crouchRevert\", \"false\", Property.Type.BOOLEAN);\n public static final Property ALT_APPEARANCE = new Property(\"alternateAppearance\", \"false\", Property.Type.BOOLEAN);\n public static final Property TRANSFORM_ITEMS = new Property(\"transformItems\", \"\", Property.Type.STRING);\n public static final Property MOD_ALIASES = new Property(\"modAliases\", \"\", Property.Type.STRING);\n public static final Property BLACKLIST_MODS = new Property(\"blacklistedMods\", \"\", Property.Type.STRING);\n public static final Property WHITELIST_ITEMS = new Property(\"whitelistedItems\", \"\", Property.Type.STRING);\n public static final Property WHITELIST_NAMES = new Property(\"whitelistedNames\", \"\", Property.Type.STRING);\n\n //public static void initProps() {\n static {\n ENABLE_TRANSFORM.setComment(\"Enables Omniwand auto-transform.\");\n ENABLE_TRANSFORM.setDefaultValue(true);\n\n RESTRICT_TOOLTIP.setComment(\"Restricts the Omniwand tooltip to only show items that used for transforms.\");\n RESTRICT_TOOLTIP.setDefaultValue(false);\n\n OFFHAND_TRANSFORM.setComment(\"Omniwand will only transform when held in the offhand.\");\n OFFHAND_TRANSFORM.setDefaultValue(false);\n\n CROUCH_REVERT.setComment(\"Omniwand requires crouch + swing to revert from a transformed item.\");\n CROUCH_REVERT.setDefaultValue(false);\n\n ALT_APPEARANCE.setComment(\"If for some reason you hate the fact the Omniwand is a staff you can set this to true. REQUIRES RESTART.\");\n ALT_APPEARANCE.setDefaultValue(false);\n ALT_APPEARANCE.setRequiresMcRestart(true);\n\n TRANSFORM_ITEMS.setComment( \"List of items that will be associated with Omniwand auto-transform. This must be set before\\n\" +\n \"items are crafted into the wand. Only one transform item per mod can be stored in the Omniwand.\\n\\n\" +\n \"This will override the \\\"blacklistedMods\\\" setting.\\n\\n\");\n TRANSFORM_ITEMS.setDefaultValues(new String[]{\n \"appliedenergistics2:certus_quartz_wrench\",\n \"appliedenergistics2:nether_quartz_wrench\",\n \"appliedenergistics2:network_tool\",\n \"astralsorcery:itemwand\",\n \"botania:twigwand\",\n \"draconicevolution:crystal_binder\",\n \"embers:tinker_hammer\",\n \"enderio:item_yeta_wrench\",\n \"immersiveengineering:tool:0\",\n \"mekanism:configurator\",\n \"rftools:smartwrench\",\n \"teslacorelib:wrench\",\n \"thermalfoundation:wrench\"\n });\n\n MOD_ALIASES.setComment(\"List of mod aliases used for Omniwand transforming.\\n\");\n MOD_ALIASES.setDefaultValues(new String[]{\n \"ae2stuff=appliedenergistics2\",\n \"threng=appliedenergistics2\",\n \"animus=bloodmagic\",\n \"bloodarsenal=bloodmagic\",\n \"nautralpledge=botania\",\n \"immersivetech=immersiveengineering\",\n \"immersivepetrolium=immersiveengineering\",\n \"industrialforegoing=teslacorelib\",\n \"redstonearsenal=thermalfoundation\",\n \"thermalcultivation=thermalfoundation\",\n \"thermaldynamics=thermalfoundation\",\n \"thermalexpansion=thermalfoundation\",\n \"rftoolsdim=rftools\",\n \"rftoolspower=rftools\",\n \"rftoolscontrol=rftools\",\n \"integrateddynamics=integratedtunnels\",\n \"mekanismgenerators=mekanism\",\n \"mekanismtools=mekanism\",\n \"deepresonance=rftools\",\n \"xnet=rftools\",\n \"buildcrafttransport=buildcraft\",\n \"buildcraftfactory=buildcraft\",\n \"buildcraftsilicon=buildcraft\"\n });\n\n BLACKLIST_MODS.setComment(\"List of mods to deny attachment to the Omniwand.\\n\");\n BLACKLIST_MODS.setDefaultValues(new String[]{\n \"intangible\",\n \"immersiveengineering\",\n \"tconstruct\"\n });\n\n WHITELIST_ITEMS.setComment(\"List of items that can be attached to the Omniwand.\\nThis will override the \\\"blacklistedMods\\\" setting.\\n\");\n WHITELIST_ITEMS.setDefaultValues(new String[]{\n \"immersiveengineering:tool:1\",\n \"immersiveengineering:tool:2\"\n });\n\n WHITELIST_NAMES.setComment(\"List of names contained within item ids that can be attached to the Omniwand.\\n\");\n WHITELIST_NAMES.setDefaultValues(new String[]{\n \"configurator\",\n \"crowbar\",\n \"hammer\",\n \"rod\",\n \"rotator\",\n \"screwdriver\",\n \"wand\",\n \"wrench\"\n });\n }\n}" } ]
import com.invadermonky.omniwand.Omniwand; import com.invadermonky.omniwand.handlers.TransformHandler; import com.invadermonky.omniwand.init.RegistryOW; import com.invadermonky.omniwand.util.References; import io.netty.buffer.ByteBuf; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
4,104
package com.invadermonky.omniwand.network; public class MessageRevertWand implements IMessage { public MessageRevertWand() {} @Override public void fromBytes(ByteBuf buf) {} @Override public void toBytes(ByteBuf buf) {} public static class MsgHandler implements IMessageHandler<MessageRevertWand,IMessage> { @Override public IMessage onMessage(MessageRevertWand message, MessageContext ctx) { EntityPlayer player = ctx.getServerHandler().player; ItemStack stack = player.getHeldItemMainhand(); if(stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) {
package com.invadermonky.omniwand.network; public class MessageRevertWand implements IMessage { public MessageRevertWand() {} @Override public void fromBytes(ByteBuf buf) {} @Override public void toBytes(ByteBuf buf) {} public static class MsgHandler implements IMessageHandler<MessageRevertWand,IMessage> { @Override public IMessage onMessage(MessageRevertWand message, MessageContext ctx) { EntityPlayer player = ctx.getServerHandler().player; ItemStack stack = player.getHeldItemMainhand(); if(stack != null && TransformHandler.isOmniwand(stack) && stack.getItem() != RegistryOW.OMNIWAND) {
ItemStack newStack = TransformHandler.getTransformStackForMod(stack, References.MINECRAFT);
3
2023-10-16 00:48:26+00:00
8k
hmcts/opal-fines-service
src/test/java/uk/gov/hmcts/opal/controllers/DefendantAccountControllerTest.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 accountNumber;\n\n // parties.surname, parties,initials, parties.forenames, parties.title\n private String fullName;\n\n // business_units.business_unit_type\n private String accountCT;\n\n //parties.account_type\n private String accountType;\n\n //parties.address_line_(*)\n private String address;\n\n //parties.postcode\n private String postCode;\n\n //parties.birth_date\n private LocalDate dob;\n\n //defendant_accounts.last_changed_date\n private LocalDate detailsChanged;\n\n //defendant_accounts.last_hearing_date + defendant_accounts.last_hearing_court_id\n private String lastCourtAppAndCourtCode;\n\n //defendant_accounts.last_movement_date\n private LocalDate lastMovement;\n\n //notes.note_text\n private List<String> commentField;\n\n //defendant_accounts.prosecutor_case_reference\n private String pcr;\n\n //payment_terms.installment_amount / payment_terms.installment_period\n private String paymentDetails;\n\n //payment_terms.instalment_lump_sum\n private BigDecimal lumpSum;\n\n //payment_terms.effective_date\n private LocalDate commencing;\n\n //payment_terms.jail_days\n private int daysInDefault;\n\n //defendant_accounts.last_enforcement\n private String lastEnforcement;\n\n //defendant_accounts.enf_override_result_id\n private String override;\n\n //defendant_accounts.enf_override_enforcer_id\n private Short enforcer;\n\n //defendant_accounts.enforcing_court_id\n private int enforcementCourt;\n\n //defendant_accounts.amount_imposed\n private BigDecimal imposed;\n\n //defendant_accounts.amount_paid\n private BigDecimal amountPaid;\n\n //defendant_accounts.account_balance\n private BigDecimal arrears;\n\n //defendant_accounts.account_balance\n private BigDecimal balance;\n}" }, { "identifier": "AccountEnquiryDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountEnquiryDto.java", "snippet": "@Builder\n@Data\npublic class AccountEnquiryDto implements ToJsonString {\n\n @JsonProperty(\"businessUnitId\")\n private Short businessUnitId;\n @JsonProperty(\"accountNumber\")\n private String accountNumber;\n}" }, { "identifier": "AccountSearchDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java", "snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Company Name or A/C number. */\n private String surname;\n /** Can be either Defendant, Minor Creditor or Company. */\n private String searchType;\n /** Defendant Forenames. */\n private String forename;\n /** Defendant Initials. */\n private String initials;\n /** Defendant Date of Birth. */\n private DateDto dateOfBirth;\n /** Defendant Address, typically just first line. */\n private String addressLineOne;\n /** National Insurance Number. */\n private String niNumber;\n /** Prosecutor Case Reference. */\n private String pcr;\n /** Major Creditor account selection. */\n private String majorCreditor;\n /** Unsure. */\n private String tillNumber;\n}" }, { "identifier": "AccountSearchResultsDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchResultsDto.java", "snippet": "@Builder\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode\npublic class AccountSearchResultsDto implements ToJsonString {\n\n /** The number of AccountSummary objects returned within this response. */\n private Integer count;\n /** The total number of matching Accounts found in the database. */\n private Long totalCount;\n /** The position of the first AccountSummary in this response within the total search of the database. */\n private Integer cursor;\n /** The maximum number of AccountSummary objects that can be returned in a single search response. */\n private final Integer pageSize = 100;\n /** A list of AccountSummary objects, limited to a maximum of pageSize. */\n private List<AccountSummaryDto> searchResults;\n\n public static class AccountSearchResultsDtoBuilder {\n public AccountSearchResultsDtoBuilder searchResults(List<AccountSummaryDto> searchResults) {\n this.searchResults = searchResults;\n this.count(Optional.ofNullable(searchResults).map(List::size).orElse(0));\n return this;\n }\n\n private AccountSearchResultsDtoBuilder count(Integer count) {\n this.count = count;\n return this;\n }\n }\n}" }, { "identifier": "DefendantAccountEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountEntity.java", "snippet": "@Entity\n@Data\n@Table(name = \"defendant_accounts\")\npublic class DefendantAccountEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"defendant_account_id_seq\")\n @SequenceGenerator(name = \"defendant_account_id_seq\", sequenceName = \"defendant_account_id_seq\", allocationSize = 1)\n @Column(name = \"defendant_account_id\")\n private Long defendantAccountId;\n\n @ManyToOne\n @JoinColumn(name = \"business_unit_id\", referencedColumnName = \"business_unit_id\", nullable = false)\n private BusinessUnitsEntity businessUnitId;\n\n @Column(name = \"account_number\", length = 20)\n private String accountNumber;\n\n @Column(name = \"imposed_hearing_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate imposedHearingDate;\n\n @Column(name = \"imposing_court_id\")\n private Long imposingCourtId;\n\n @Column(name = \"amount_imposed\", precision = 18, scale = 2)\n private BigDecimal amountImposed;\n\n @Column(name = \"amount_paid\", precision = 18, scale = 2)\n private BigDecimal amountPaid;\n\n @Column(name = \"account_balance\", precision = 18, scale = 2)\n private BigDecimal accountBalance;\n\n @Column(name = \"account_status\", length = 2)\n private String accountStatus;\n\n @Column(name = \"completed_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate completedDate;\n\n @ManyToOne\n @JoinColumn(name = \"enforcing_court_id\", referencedColumnName = \"court_id\", nullable = false)\n private CourtsEntity enforcingCourtId;\n\n @ManyToOne\n @JoinColumn(name = \"last_hearing_court_id\", referencedColumnName = \"court_id\", nullable = false)\n private CourtsEntity lastHearingCourtId;\n\n @Column(name = \"last_hearing_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastHearingDate;\n\n @Column(name = \"last_movement_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastMovementDate;\n\n @Column(name = \"last_enforcement\", length = 6)\n private String lastEnforcement;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastChangedDate;\n\n @Column(name = \"originator_name\", length = 100)\n private String originatorName;\n\n @Column(name = \"originator_reference\", length = 40)\n private String originatorReference;\n\n @Column(name = \"originator_type\", length = 10)\n private String originatorType;\n\n @Column(name = \"allow_writeoffs\")\n private boolean allowWriteoffs;\n\n @Column(name = \"allow_cheques\")\n private boolean allowCheques;\n\n @Column(name = \"cheque_clearance_period\")\n private Short chequeClearancePeriod;\n\n @Column(name = \"credit_trans_clearance_period\")\n private Short creditTransferClearancePeriod;\n\n @Column(name = \"enf_override_result_id\", length = 10)\n private String enforcementOverrideResultId;\n\n @Column(name = \"enf_override_enforcer_id\")\n private Long enforcementOverrideEnforcerId;\n\n @Column(name = \"enf_override_tfo_lja_id\")\n private Short enforcementOverrideTfoLjaId;\n\n @Column(name = \"unit_fine_detail\", length = 100)\n private String unitFineDetail;\n\n @Column(name = \"unit_fine_value\", precision = 18, scale = 2)\n private BigDecimal unitFineValue;\n\n @Column(name = \"collection_order\")\n private boolean collectionOrder;\n\n @Column(name = \"collection_order_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate collectionOrderEffectiveDate;\n\n @Column(name = \"further_steps_notice_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate furtherStepsNoticeDate;\n\n @Column(name = \"confiscation_order_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate confiscationOrderDate;\n\n @Column(name = \"fine_registration_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate fineRegistrationDate;\n\n @Column(name = \"consolidated_account_type\", length = 1)\n private String consolidatedAccountType;\n\n @Column(name = \"payment_card_requested\")\n private boolean paymentCardRequested;\n\n @Column(name = \"payment_card_requested_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate paymentCardRequestedDate;\n\n @Column(name = \"payment_card_requested_by\", length = 20)\n private String paymentCardRequestedBy;\n\n @Column(name = \"prosecutor_case_reference\", length = 40)\n private String prosecutorCaseReference;\n\n @Column(name = \"enforcement_case_status\", length = 10)\n private String enforcementCaseStatus;\n\n @OneToMany(mappedBy = \"defendantAccount\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> parties;\n\n}" }, { "identifier": "DefendantAccountService", "path": "src/main/java/uk/gov/hmcts/opal/service/DefendantAccountService.java", "snippet": "@Service\n@Transactional\n@Slf4j\n@RequiredArgsConstructor\npublic class DefendantAccountService {\n\n private final DefendantAccountRepository defendantAccountRepository;\n\n private final DefendantAccountPartiesRepository defendantAccountPartiesRepository;\n\n private final PaymentTermsRepository paymentTermsRepository;\n\n private final DebtorDetailRepository debtorDetailRepository;\n\n private final EnforcersRepository enforcersRepository;\n\n private final NoteRepository noteRepository;\n\n public DefendantAccountEntity getDefendantAccount(AccountEnquiryDto request) {\n\n return defendantAccountRepository.findByBusinessUnitId_BusinessUnitIdAndAccountNumber(\n request.getBusinessUnitId(), request.getAccountNumber());\n }\n\n public DefendantAccountEntity putDefendantAccount(DefendantAccountEntity defendantAccountEntity) {\n\n return defendantAccountRepository.save(defendantAccountEntity);\n }\n\n public List<DefendantAccountEntity> getDefendantAccountsByBusinessUnit(Short businessUnitId) {\n\n log.info(\":getDefendantAccountsByBusinessUnit: busUnit: {}\", businessUnitId);\n return defendantAccountRepository.findAllByBusinessUnitId_BusinessUnitId(businessUnitId);\n }\n\n public AccountSearchResultsDto searchDefendantAccounts(AccountSearchDto accountSearchDto) {\n\n if (\"test\".equalsIgnoreCase(accountSearchDto.getCourt())) {\n\n try (InputStream in = Thread.currentThread().getContextClassLoader()\n .getResourceAsStream(\"tempSearchData.json\")) {\n ObjectMapper mapper = newObjectMapper();\n AccountSearchResultsDto dto = mapper.readValue(in, AccountSearchResultsDto.class);\n log.info(\":searchDefendantAccounts: temporary Hack for Front End testing. Read JSON file: \\n{}\",\n dto.toPrettyJsonString());\n return dto;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n Page<DefendantAccountSummary> summariesPage = defendantAccountRepository\n .findBy(DefendantAccountSpecs.findByAccountSearch(accountSearchDto),\n ffq -> ffq.as(DefendantAccountSummary.class).page(Pageable.unpaged()));\n\n List<AccountSummaryDto> dtos = summariesPage.getContent().stream()\n .map(this::toDto)\n .collect(Collectors.toList());\n\n return AccountSearchResultsDto.builder()\n .searchResults(dtos)\n .totalCount(summariesPage.getTotalElements())\n .cursor(summariesPage.getNumber())\n .build();\n }\n\n public AccountDetailsDto getAccountDetailsByDefendantAccountId(Long defendantAccountId) {\n\n\n if (defendantAccountId.equals(0L)) {\n\n\n try (InputStream in = Thread.currentThread().getContextClassLoader()\n .getResourceAsStream(\"tempDetailsData.json\")) {\n\n ObjectMapper mapper = newObjectMapper();\n AccountDetailsDto dto = mapper.readValue(in, AccountDetailsDto.class);\n log.info(\n \"\"\"\n :getAccountDetailsByDefendantAccountId:\n \" temporary Hack for Front End testing. Read JSON file: \\n{}\n \"\"\",\n dto.toPrettyJsonString());\n return dto;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n\n //query db for defendantAccountPartiesEntity\n DefendantAccountPartiesEntity defendantAccountPartiesEntity = defendantAccountPartiesRepository\n .findByDefendantAccountId(defendantAccountId);\n\n //Extract unique defendantAccount and party entities\n final DefendantAccountEntity defendantAccountEntity = defendantAccountPartiesEntity.getDefendantAccount();\n final PartyEntity partyEntity = defendantAccountPartiesEntity.getParty();\n\n //query DB for PaymentTermsEntity\n PaymentTermsEntity paymentTermsEntity = paymentTermsRepository.findByDefendantAccount_DefendantAccountId(\n defendantAccountEntity);\n\n //query DB for EnforcementEntity\n EnforcersEntity enforcersEntity = enforcersRepository.findByEnforcerId(defendantAccountEntity\n .getEnforcementOverrideEnforcerId());\n\n //query DB for NoteEntity by associatedRecordId (defendantAccountId) and noteType (\"AC\")\n List<NoteEntity> noteEntity = noteRepository.findByAssociatedRecordIdAndNoteType(\n defendantAccountEntity.getDefendantAccountId().toString(), \"AC\");\n\n\n //build fullAddress\n final String fullAddress = buildFullAddress(partyEntity);\n\n //build fullName\n final String fullName = buildFullName(partyEntity);\n\n //build paymentDetails\n final String paymentDetails = buildPaymentDetails(paymentTermsEntity);\n\n //build comments\n final List<String> comments = buildCommentsFromAssociatedNotes(noteEntity);\n\n //populate accountDetailsDto and return\n return AccountDetailsDto.builder()\n .accountNumber(defendantAccountEntity.getAccountNumber())\n .fullName(fullName)\n .accountCT(defendantAccountEntity.getBusinessUnitId().getBusinessUnitName())\n .accountType(defendantAccountEntity.getOriginatorType())\n .address(fullAddress)\n .postCode(partyEntity.getPostcode())\n .dob(partyEntity.getDateOfBirth())\n .detailsChanged(defendantAccountEntity.getLastChangedDate())\n .lastCourtAppAndCourtCode(defendantAccountEntity.getLastHearingDate().toString()\n + defendantAccountEntity.getLastHearingCourtId().getCourtCode())\n .lastMovement(defendantAccountEntity.getLastMovementDate())\n .commentField(comments)\n .pcr(defendantAccountEntity.getProsecutorCaseReference())\n .paymentDetails(paymentDetails)\n .lumpSum(paymentTermsEntity.getInstalmentLumpSum())\n .commencing(paymentTermsEntity.getEffectiveDate())\n .daysInDefault(paymentTermsEntity.getJailDays())\n .lastEnforcement(defendantAccountEntity.getLastEnforcement())\n .override(defendantAccountEntity.getEnforcementOverrideResultId())\n .enforcer(enforcersEntity.getEnforcerCode())\n .enforcementCourt(defendantAccountEntity.getEnforcingCourtId().getCourtCode())\n .imposed(defendantAccountEntity.getAmountImposed())\n .amountPaid(defendantAccountEntity.getAmountPaid())\n .arrears(defendantAccountEntity.getAccountBalance())\n .balance(defendantAccountEntity.getAccountBalance())\n .build();\n }\n\n private String buildFullAddress(PartyEntity partyEntity) {\n\n return partyEntity.getAddressLine1() + \", \"\n + partyEntity.getAddressLine2() + \", \"\n + partyEntity.getAddressLine3() + \", \"\n + partyEntity.getAddressLine4() + \", \"\n + partyEntity.getAddressLine5();\n }\n\n private String buildFullName(PartyEntity partyEntity) {\n\n return partyEntity.getOrganisationName() == null ? partyEntity.getTitle() + \" \"\n + partyEntity.getForenames() + \" \"\n + partyEntity.getInitials() + \" \"\n + partyEntity.getSurname() : partyEntity.getOrganisationName();\n }\n\n private String buildPaymentDetails(PaymentTermsEntity paymentTermsEntity) {\n final String paymentType = paymentTermsEntity.getTermsTypeCode();\n\n return switch (paymentType) {\n case \"I\" -> buildInstalmentDetails(paymentTermsEntity);\n case \"B\" -> buildByDateDetails(paymentTermsEntity);\n default -> \"Paid\";\n };\n }\n\n private String buildInstalmentDetails(PaymentTermsEntity paymentTermsEntity) {\n return paymentTermsEntity.getInstalmentAmount() + \" / \" + paymentTermsEntity.getInstalmentPeriod();\n }\n\n private String buildByDateDetails(PaymentTermsEntity paymentTermsEntity) {\n return paymentTermsEntity.getEffectiveDate() + \" By Date\";\n }\n\n private List<String> buildCommentsFromAssociatedNotes(List<NoteEntity> notes) {\n\n List<String> comments = new ArrayList<>();\n\n for (NoteEntity note : notes) {\n\n comments.add(note.getNoteText());\n }\n\n return comments;\n }\n\n public AccountSummaryDto toDto(DefendantAccountSummary summary) {\n Optional<PartyDefendantAccountSummary> party = summary.getParties().stream().findAny().map(PartyLink::getParty);\n return AccountSummaryDto.builder()\n .defendantAccountId(summary.getDefendantAccountId())\n .accountNo(summary.getAccountNumber())\n .court(summary.getImposingCourtId())\n .balance(summary.getAccountBalance())\n .name(party.map(PartyDefendantAccountSummary::getName).orElse(\"\"))\n .addressLine1(party.map(PartyDefendantAccountSummary::getAddressLine1).orElse(\"\"))\n .dateOfBirth(party.map(PartyDefendantAccountSummary::getDateOfBirth).orElse(null))\n .build();\n }\n}" } ]
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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.entity.DefendantAccountEntity; import uk.gov.hmcts.opal.service.DefendantAccountService; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
4,646
package uk.gov.hmcts.opal.controllers; @ExtendWith(MockitoExtension.class) class DefendantAccountControllerTest { @Mock private DefendantAccountService defendantAccountService; @InjectMocks private DefendantAccountController defendantAccountController; @Test public void testGetDefendantAccount_Success() { // Arrange
package uk.gov.hmcts.opal.controllers; @ExtendWith(MockitoExtension.class) class DefendantAccountControllerTest { @Mock private DefendantAccountService defendantAccountService; @InjectMocks private DefendantAccountController defendantAccountController; @Test public void testGetDefendantAccount_Success() { // Arrange
DefendantAccountEntity mockResponse = new DefendantAccountEntity();
4
2023-10-23 14:12:11+00:00
8k
IronRiders/MockSeason23-24
src/main/java/org/ironriders/robot/RobotContainer.java
[ { "identifier": "DriveCommands", "path": "src/main/java/org/ironriders/commands/DriveCommands.java", "snippet": "public class DriveCommands {\n private final DriveSubsystem drive;\n private final SwerveDrive swerve;\n private final VisionSubsystem vision;\n\n public DriveCommands(DriveSubsystem drive) {\n this.drive = drive;\n this.vision = drive.getVision();\n this.swerve = drive.getSwerveDrive();\n }\n\n /**\n * Creates a teleoperated command for swerve drive using joystick inputs.\n *\n * @param x The x-axis joystick input.\n * @param y The y-axis joystick input.\n * @param a The rotation joystick input.\n * @return a command to control the swerve drive during teleop.\n */\n public Command teleopCommand(DoubleSupplier x, DoubleSupplier y, DoubleSupplier a) {\n return drive(\n () -> swerve.getSwerveController().getTargetSpeeds(\n x.getAsDouble(),\n y.getAsDouble(),\n a.getAsDouble() * 2 + swerve.getYaw().getRadians(),\n swerve.getYaw().getRadians(),\n MAX_SPEED\n )\n );\n }\n\n /**\n * Creates a command to set the gyro orientation to a specified rotation.\n *\n * @param rotation The desired rotation for the gyro.\n * @return A command to set the gyro orientation.\n */\n public Command setGyro(Pose2d rotation) {\n return drive.runOnce(() -> swerve.resetOdometry(rotation));\n }\n\n /**\n * Creates a command to drive the swerve robot using specified speeds. Must be repeated to work.\n *\n * @param speeds The supplier providing the desired chassis speeds.\n * @return A command to drive the swerve robot with the specified speeds.\n */\n public Command drive(Supplier<ChassisSpeeds> speeds) {\n return drive(speeds, true, false);\n }\n\n /**\n * Creates a command to drive the swerve robot using specified speeds and control options. Must be repeated to\n * work.\n *\n * @param speeds The supplier providing the desired chassis speeds.\n * @param fieldCentric Whether the control is field-centric.\n * @param openLoop Whether the control is open loop.\n * @return A command to drive the swerve robot with the specified speeds and control options.\n */\n public Command drive(Supplier<ChassisSpeeds> speeds, boolean fieldCentric, boolean openLoop) {\n return drive.runOnce(() -> swerve.drive(\n SwerveController.getTranslation2d(speeds.get()),\n speeds.get().omegaRadiansPerSecond,\n fieldCentric,\n openLoop\n ));\n }\n\n /**\n * Generates a path to the specified destination using default settings false for velocity control which will stop\n * the robot abruptly when it reaches the target.\n *\n * @param target The destination pose represented by a Pose2d object.\n * @return A Command object representing the generated path to the destination.\n */\n public Command pathFindTo(Pose2d target) {\n return pathFindTo(target, false);\n }\n\n /**\n * Generates a path to the specified destination with options for velocity control.\n *\n * @param target The destination pose represented by a Pose2d object.\n * @param preserveEndVelocity A boolean flag indicating whether to preserve velocity at the end of the path.\n * If true, the path will end with the robot going the max velocity; if false, it will\n * stop abruptly.\n * @return A Command object representing the generated path to the destination.\n */\n public Command pathFindTo(Pose2d target, boolean preserveEndVelocity) {\n return AutoBuilder.pathfindToPose(\n target,\n drive.getPathfindingConstraint().getConstraints(),\n preserveEndVelocity ? drive.getPathfindingConstraint().getConstraints().getMaxVelocityMps() : 0\n );\n }\n\n public Command pathFindToTag(Supplier<Integer> id) {\n return pathFindToTag(id, -Arm.LENGTH_FROM_ORIGIN);\n }\n\n /**\n * Generates a path to a specified target identified by a vision tag. This will run only if the id is provided if\n * the id is not provided it will return Command that does nothing and immediately closes itself.\n *\n * @param id The identifier of the vision tag.\n * @param offset The transformation to be applied to the identified target's pose.\n * @return A Command object representing the generated path to the identified target.\n */\n public Command pathFindToTag(Supplier<Integer> id, double offset) {\n Optional<Pose3d> pose = vision.getTag(id.get());\n if (pose.isEmpty()) {\n return Commands.none();\n }\n\n return useVisionForPoseEstimation(\n pathFindTo(Utils.accountedPose(pose.get().toPose2d(), offset).plus(\n new Transform2d(new Translation2d(), Rotation2d.fromDegrees(180))\n ))\n );\n }\n\n public Command lockPose() {\n return drive.runOnce(swerve::lockPose);\n }\n\n /**\n * A utility method that temporarily enables vision-based pose estimation, executes a specified command,\n * and then disables vision-based pose estimation again.\n *\n * @param command The Command object to be executed after enabling vision-based pose estimation.\n * @return A new Command object representing the sequence of actions including vision-based pose estimation.\n */\n public Command useVisionForPoseEstimation(Command command) {\n return vision\n .runOnce(() -> vision.useVisionForPoseEstimation(true))\n .andThen(command)\n .finallyDo(() -> vision.useVisionForPoseEstimation(false));\n }\n\n public Command resetOdometry() {\n return resetOdometry(new Pose2d());\n }\n\n public Command resetOdometry(Pose2d pose) {\n return drive.runOnce(() -> drive.getSwerveDrive().resetOdometry(pose));\n }\n}" }, { "identifier": "RobotCommands", "path": "src/main/java/org/ironriders/commands/RobotCommands.java", "snippet": "public class RobotCommands {\n private final ArmCommands arm;\n private final DriveCommands drive;\n private final DriveSubsystem driveSubsystem;\n private final VisionSubsystem vision;\n private final ManipulatorCommands manipulator;\n\n public RobotCommands(ArmSubsystem arm, DriveSubsystem drive, ManipulatorSubsystem manipulator) {\n this.arm = arm.getCommands();\n this.drive = drive.getCommands();\n driveSubsystem = drive;\n vision = drive.getVision();\n this.manipulator = manipulator.getCommands();\n\n NamedCommands.registerCommand(\"Resting\", resting());\n NamedCommands.registerCommand(\"Driving\", driving());\n NamedCommands.registerCommand(\"Ground Pickup\", groundPickup());\n NamedCommands.registerCommand(\"Exchange\", exchange());\n NamedCommands.registerCommand(\"Exchange Return\", exchangeReturn());\n NamedCommands.registerCommand(\"Portal\", portal());\n NamedCommands.registerCommand(\"Switch\", switchDropOff());\n }\n\n public Command resting() {\n return arm\n .setPivot(Arm.State.REST)\n .alongWith(manipulator.set(Manipulator.State.STOP));\n }\n\n public Command driving() {\n return arm\n .setPivot(Arm.State.FULL)\n .andThen(manipulator.set(Manipulator.State.STOP));\n }\n\n public Command groundPickup() {\n return resting().andThen(manipulator.grabAndStop(3));\n }\n\n public Command exchange() {\n return Commands.sequence(\n driveTo(AprilTagLocation.EXCHANGE),\n arm.setPivot(Arm.State.EXCHANGE),\n manipulator.set(Manipulator.State.EJECT)\n );\n }\n\n public Command exchangeReturn() {\n return Commands.sequence(\n arm.setPivot(Arm.State.EXCHANGE),\n driveTo(AprilTagLocation.EXCHANGE),\n manipulator.grabAndStop(3)\n );\n }\n\n public Command portal() {\n return Commands.sequence(\n driveTo(AprilTagLocation.PORTAL),\n arm.setPivot(Arm.State.PORTAL),\n manipulator.grabAndStop(3)\n );\n }\n\n public Command switchDropOff() {\n return Commands.sequence(\n driveTo(AprilTagLocation.SWITCH),\n arm.setPivot(Arm.State.SWITCH),\n manipulator.set(Manipulator.State.EJECT)\n );\n }\n\n private Command driveTo(AprilTagLocation location) {\n return Commands.sequence(\n drive.lockPose(),\n arm.setPivot(Arm.State.REST),\n Commands.waitSeconds(WAIT_TIME),\n Commands.defer(() -> drive.pathFindToTag(() -> vision.bestTagFor(location)), Set.of(driveSubsystem)),\n drive.lockPose()\n );\n }\n\n /**\n * Builds an autonomous command based on the provided {@code AutoConfig}.\n *\n * @param auto The configuration object specifying the autonomous routine.\n * @return A command representing the autonomous routine specified by the {@code AutoConfig}.\n */\n public Command buildAuto(String auto) {\n return AutoBuilder.buildAuto(auto);\n }\n}" }, { "identifier": "Ports", "path": "src/main/java/org/ironriders/constants/Ports.java", "snippet": "public class Ports {\n /**\n * Driver station ports for the MOTORs.\n */\n public static class Controllers {\n public static final int PRIMARY_CONTROLLER = 0;\n public static final int SECONDARY_CONTROLLER = 1;\n }\n\n /**\n * Ports for each addressable LED strip.\n * <p>\n * S = Strip\n */\n public static class Lights {\n public static class S1 {\n public static final int RSL = 0;\n }\n }\n\n public static class Arm {\n public static final int RIGHT_MOTOR = 10;\n public static final int LEFT_MOTOR = 11;\n\n public static final int PRIMARY_ENCODER = 0;\n public static final int SECONDARY_ENCODER = 1;\n }\n\n public static class Manipulator {\n public static final int RIGHT_MOTOR = 12;\n public static final int LEFT_MOTOR = 13;\n\n }\n}" }, { "identifier": "Teleop", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public class Teleop {\n public static class Speed {\n public static final double MIN_MULTIPLIER = 0.35;\n public static final double EXPONENT = 3;\n public static final double DEADBAND = 0.1;\n }\n\n public static class Controllers {\n public static class Joystick {\n public static final double EXPONENT = 3;\n public static final double DEADBAND = 0.15;\n }\n }\n}" }, { "identifier": "Utils", "path": "src/main/java/org/ironriders/lib/Utils.java", "snippet": "public class Utils {\n /**\n * Calculates the absolute error between the target and current values, considering rotational values.\n *\n * @param target The target value.\n * @param current The current value.\n * @return The absolute error between the target and current values.\n */\n public static double rotationalError(double target, double current) {\n double error = Utils.absoluteRotation(target) - current;\n if (error > 180) {\n error -= 360;\n } else if (error < -180) {\n error += 360;\n }\n return error;\n }\n\n /**\n * Normalizes a rotational input value to the range [0, 360) degrees.\n *\n * @param input The input rotational value.\n * @return The normalized rotational value within the range [0, 360) degrees.\n */\n public static double absoluteRotation(double input) {\n return (input % 360 + 360) % 360;\n }\n\n /**\n * Adjusts a given Transform2d by applying a translation offset, considering the rotation of the origin.\n * The offset is modified based on the alliance obtained from DriverStation.getAlliance(). Also rotates by 180.\n *\n * @param origin The original Transform2d to be adjusted.\n * @param offset The translation offset to be applied.\n * @return A new Transform2d representing the adjusted position.\n */\n public static Pose2d accountedPose(Pose2d origin, double offset) {\n double angle = origin.getRotation().getRadians();\n\n return origin.plus(\n new Transform2d(\n new Translation2d(offset * Math.cos(angle), offset * Math.sin(angle)),\n new Rotation2d()\n )\n );\n }\n\n /**\n * Checks if the input value is within a specified tolerance of the target value.\n *\n * @param input The input value.\n * @param target The target value.\n * @param tolerance The allowable tolerance range.\n * @return {@code true} if the input value is within the specified tolerance of the target value, {@code false}\n * otherwise.\n */\n public static boolean isWithinTolerance(double input, double target, double tolerance) {\n return Math.abs(input - target) <= tolerance;\n }\n\n /**\n * Applies deadband to the input value. If the input falls within the specified deadband range, it is set to 0.\n *\n * @param input The input value to be processed.\n * @param deadband The range around 0 within which the output is set to 0.\n * @return The processed output value after applying deadband.\n */\n public static double deadband(double input, double deadband) {\n return isWithinTolerance(input, 0, deadband) ? 0 : input;\n }\n\n /**\n * Applies a control curve to the input value based on the specified exponent and deadband.\n * The control curve modifies the input such that values within the deadband are set to 0,\n * and the remaining values are transformed using an exponent function.\n *\n * @param input The input value to be modified by the control curve.\n * @param exponent The exponent to which the normalized input (after deadband removal) is raised.\n * @param deadband The range around 0 within which the output is set to 0.\n * @return The modified output value after applying the control curve.\n */\n public static double controlCurve(double input, double exponent, double deadband) {\n input = deadband(input, deadband);\n if (input == 0) {\n return 0;\n }\n\n return sign(input) * Math.pow((Math.abs(input) - deadband) / (1 - deadband), exponent);\n }\n\n /**\n * Returns the sign of the input value.\n *\n * @param input The input value to determine the sign.\n * @return 1 if the input is positive, -1 if negative, 0 if zero.\n */\n public static double sign(double input) {\n return input > 0 ? 1 : -1;\n }\n}" }, { "identifier": "ArmSubsystem", "path": "src/main/java/org/ironriders/subsystems/ArmSubsystem.java", "snippet": "public class ArmSubsystem extends SubsystemBase {\n private final ArmCommands commands;\n private final CANSparkMax leader = new CANSparkMax(Ports.Arm.RIGHT_MOTOR, kBrushless);\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final CANSparkMax follower = new CANSparkMax(Ports.Arm.LEFT_MOTOR, kBrushless);\n private final DutyCycleEncoder primaryEncoder = new DutyCycleEncoder(Ports.Arm.PRIMARY_ENCODER);\n private final DutyCycleEncoder secondaryEncoder = new DutyCycleEncoder(Ports.Arm.SECONDARY_ENCODER);\n private final ProfiledPIDController pid = new ProfiledPIDController(P, I, D, PROFILE);\n\n public ArmSubsystem() {\n leader.setSmartCurrentLimit(CURRENT_LIMIT);\n follower.setSmartCurrentLimit(CURRENT_LIMIT);\n\n leader.setIdleMode(kCoast);\n follower.setIdleMode(kCoast);\n\n primaryEncoder.setPositionOffset(PRIMARY_ENCODER_OFFSET);\n primaryEncoder.setDistancePerRotation(360);\n secondaryEncoder.setPositionOffset(SECONDARY_ENCODER_OFFSET);\n secondaryEncoder.setDistancePerRotation(360);\n\n leader.getEncoder().setPositionConversionFactor(360.0 / GEARING);\n leader.getEncoder().setPosition(getPrimaryPosition());\n\n follower.getEncoder().setPositionConversionFactor(360.0 / GEARING);\n follower.getEncoder().setPosition(getPrimaryPosition());\n\n leader.setSoftLimit(kReverse, Limit.REVERSE);\n leader.enableSoftLimit(kReverse, true);\n leader.setSoftLimit(kForward, Limit.FORWARD);\n leader.enableSoftLimit(kForward, true);\n follower.setSoftLimit(kReverse, Limit.REVERSE);\n follower.enableSoftLimit(kReverse, true);\n follower.setSoftLimit(kForward, Limit.FORWARD);\n follower.enableSoftLimit(kForward, true);\n\n follower.follow(leader, true);\n resetPID();\n\n SmartDashboard.putData(\"arm/Arm PID\", pid);\n SmartDashboard.putData(\"arm/Leader\", primaryEncoder);\n SmartDashboard.putData(\"arm/Follower\", secondaryEncoder);\n\n commands = new ArmCommands(this);\n }\n\n @Override\n public void periodic() {\n SmartDashboard.putNumber(\"arm/Leader (integrated)\", leader.getEncoder().getPosition());\n SmartDashboard.putNumber(\"arm/Follower (integrated)\", follower.getEncoder().getPosition());\n\n if (!Utils.isWithinTolerance(getPrimaryPosition(), getSecondaryPosition(), FAILSAFE_DIFFERENCE)) {\n leader.set(0);\n return;\n }\n\n leader.set(pid.calculate(getPosition()));\n }\n\n\n public ArmCommands getCommands() {\n return commands;\n }\n\n public double getPrimaryPosition() {\n return primaryEncoder.getDistance() + PRIMARY_ENCODER_OFFSET;\n }\n\n public double getSecondaryPosition() {\n return -(secondaryEncoder.getDistance() + SECONDARY_ENCODER_OFFSET);\n }\n\n /**\n * In degrees.\n */\n public double getPosition() {\n return getPrimaryPosition();\n }\n\n public void set(double target) {\n pid.setGoal(target);\n }\n\n public void resetPID() {\n pid.reset(getPosition());\n pid.setGoal(getPosition());\n }\n}" }, { "identifier": "DriveSubsystem", "path": "src/main/java/org/ironriders/subsystems/DriveSubsystem.java", "snippet": "public class DriveSubsystem extends SubsystemBase {\n private final DriveCommands commands;\n private final VisionSubsystem vision = new VisionSubsystem();\n private final SwerveDrive swerveDrive;\n private final EnumSendableChooser<PathfindingConstraintProfile> constraintProfile = new EnumSendableChooser<>(\n PathfindingConstraintProfile.class,\n PathfindingConstraintProfile.getDefault(),\n \"auto/Pathfinding Constraint Profile\"\n );\n\n public DriveSubsystem() {\n try {\n swerveDrive = new SwerveParser(\n new File(Filesystem.getDeployDirectory(), Drive.SWERVE_CONFIG_LOCATION)\n ).createSwerveDrive(MAX_SPEED, STEERING_CONVERSION_FACTOR, DRIVE_CONVERSION_FACTOR);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n SwerveDriveTelemetry.verbosity = SwerveDriveTelemetry.TelemetryVerbosity.HIGH;\n\n AutoBuilder.configureHolonomic(\n swerveDrive::getPose,\n swerveDrive::resetOdometry,\n swerveDrive::getRobotVelocity,\n swerveDrive::setChassisSpeeds,\n new HolonomicPathFollowerConfig(\n 4.5,\n Dimensions.DRIVEBASE_RADIUS,\n new ReplanningConfig()\n ),\n () -> DriverStation.getAlliance().orElse(Alliance.Blue).equals(Alliance.Red),\n this\n );\n\n commands = new DriveCommands(this);\n }\n\n @Override\n public void periodic() {\n PathPlannerLogging.setLogActivePathCallback((poses) -> {\n List<Trajectory.State> states = new ArrayList<>();\n for (Pose2d pose : poses) {\n Trajectory.State state = new Trajectory.State();\n state.poseMeters = pose;\n states.add(state);\n }\n\n swerveDrive.postTrajectory(new Trajectory(states));\n });\n\n getVision().getPoseEstimate().ifPresent(estimatedRobotPose -> {\n swerveDrive.resetOdometry(estimatedRobotPose.estimatedPose.toPose2d());\n swerveDrive.setGyro(estimatedRobotPose.estimatedPose.getRotation());\n// swerveDrive.addVisionMeasurement(\n// estimatedRobotPose.estimatedPose.toPose2d(),\n// estimatedRobotPose.timestampSeconds\n// );\n// swerveDrive.setGyro(estimatedRobotPose.estimatedPose.getRotation());\n });\n }\n\n public DriveCommands getCommands() {\n return commands;\n }\n\n public void setGyro(Rotation3d rotation) {\n swerveDrive.setGyro(new Rotation3d());\n }\n\n public VisionSubsystem getVision() {\n return vision;\n }\n\n public PathfindingConstraintProfile getPathfindingConstraint() {\n return constraintProfile.getSelected();\n }\n\n public SwerveDrive getSwerveDrive() {\n return swerveDrive;\n }\n}" }, { "identifier": "ManipulatorSubsystem", "path": "src/main/java/org/ironriders/subsystems/ManipulatorSubsystem.java", "snippet": "public class ManipulatorSubsystem extends SubsystemBase {\n private final ManipulatorCommands commands;\n private final CANSparkMax leader = new CANSparkMax(Ports.Manipulator.RIGHT_MOTOR, kBrushless);\n @SuppressWarnings(\"FieldCanBeLocal\")\n private final CANSparkMax follower = new CANSparkMax(Ports.Manipulator.LEFT_MOTOR, kBrushless);\n\n public ManipulatorSubsystem() {\n leader.setSmartCurrentLimit(CURRENT_LIMIT);\n follower.setSmartCurrentLimit(CURRENT_LIMIT);\n leader.setIdleMode(kBrake);\n follower.setIdleMode(kBrake);\n\n follower.follow(leader, true);\n\n SmartDashboard.putString(\"manipulator/State\", \"STOP\");\n\n commands = new ManipulatorCommands(this);\n }\n\n public ManipulatorCommands getCommands() {\n return commands;\n }\n\n public void set(State state) {\n switch (state) {\n case GRAB -> grab();\n case EJECT -> eject();\n case STOP -> stop();\n }\n }\n\n private void grab() {\n SmartDashboard.putString(\"manipulator/State\", \"GRAB\");\n leader.set(-GRAB_SPEED);\n }\n\n private void eject() {\n SmartDashboard.putString(\"manipulator/State\", \"EJECT\");\n leader.set(EJECT_SPEED);\n }\n\n private void stop() {\n SmartDashboard.putString(\"manipulator/State\", \"STOP\");\n leader.set(0);\n }\n}" }, { "identifier": "DEFAULT_AUTO", "path": "src/main/java/org/ironriders/constants/Auto.java", "snippet": "public static final String DEFAULT_AUTO = \"TEST\";" }, { "identifier": "Joystick", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public static class Joystick {\n public static final double EXPONENT = 3;\n public static final double DEADBAND = 0.15;\n}" }, { "identifier": "DEADBAND", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public static final double DEADBAND = 0.1;" }, { "identifier": "MIN_MULTIPLIER", "path": "src/main/java/org/ironriders/constants/Teleop.java", "snippet": "public static final double MIN_MULTIPLIER = 0.35;" } ]
import com.pathplanner.lib.auto.AutoBuilder; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.button.CommandJoystick; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import org.ironriders.commands.DriveCommands; import org.ironriders.commands.RobotCommands; import org.ironriders.constants.Ports; import org.ironriders.constants.Teleop; import org.ironriders.lib.Utils; import org.ironriders.subsystems.ArmSubsystem; import org.ironriders.subsystems.DriveSubsystem; import org.ironriders.subsystems.ManipulatorSubsystem; import static org.ironriders.constants.Auto.DEFAULT_AUTO; import static org.ironriders.constants.Teleop.Controllers.Joystick; import static org.ironriders.constants.Teleop.Speed.DEADBAND; import static org.ironriders.constants.Teleop.Speed.MIN_MULTIPLIER;
6,521
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package org.ironriders.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { private final DriveSubsystem drive = new DriveSubsystem(); private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem(); private final ArmSubsystem arm = new ArmSubsystem(); private final CommandXboxController primaryController = new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER); private final CommandJoystick secondaryController = new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER); private final RobotCommands commands = new RobotCommands(arm, drive, manipulator); private final DriveCommands driveCommands = drive.getCommands(); private final SendableChooser<String> autoOptionSelector = new SendableChooser<>(); /** * The container for the robot. Contains subsystems, IO devices, and commands. */ public RobotContainer() { for (String auto : AutoBuilder.getAllAutoNames()) { if (auto.equals("REGISTERED_COMMANDS")) continue; autoOptionSelector.addOption(auto, auto); } autoOptionSelector.setDefaultOption(DEFAULT_AUTO, DEFAULT_AUTO); SmartDashboard.putData("auto/Auto Option", autoOptionSelector); configureBindings(); } private void configureBindings() { Command switchDropOff = commands.switchDropOff(); Command exchange = commands.exchange(); Command exchangeReturn = commands.exchangeReturn(); Command portal = commands.portal(); Command cancelAuto = Commands.runOnce(() -> { switchDropOff.cancel(); exchange.cancel(); exchangeReturn.cancel(); portal.cancel(); }); // Primary Driver drive.setDefaultCommand( driveCommands.teleopCommand( () -> -controlCurve(primaryController.getLeftY()), () -> -controlCurve(primaryController.getLeftX()), () -> -controlCurve(primaryController.getRightX()) ) ); primaryController.rightBumper().onTrue(cancelAuto); primaryController.leftBumper().onTrue(cancelAuto); primaryController.a().onTrue(commands.groundPickup()); primaryController.b().onTrue(switchDropOff); primaryController.x().onTrue(portal); primaryController.y().onTrue(exchange); primaryController.leftStick().onTrue(commands.driving()); primaryController.rightStick().onTrue(commands.driving()); // Secondary Driver secondaryController.button(6).onTrue(exchange); secondaryController.button(7).onTrue(exchangeReturn); secondaryController.button(8).onTrue(portal); secondaryController.button(9).onTrue(switchDropOff); secondaryController.button(10).onTrue(commands.groundPickup()); secondaryController.button(11).onTrue(commands.resting()); secondaryController.button(12).onTrue(commands.driving()); } private double controlCurve(double input) { // Multiplier based on trigger axis (whichever one is larger) then scaled to start at 0.35 return Utils.controlCurve(input, Joystick.EXPONENT, Joystick.DEADBAND) * ( Utils.controlCurve( Math.max(primaryController.getLeftTriggerAxis(), primaryController.getRightTriggerAxis()),
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package org.ironriders.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { private final DriveSubsystem drive = new DriveSubsystem(); private final ManipulatorSubsystem manipulator = new ManipulatorSubsystem(); private final ArmSubsystem arm = new ArmSubsystem(); private final CommandXboxController primaryController = new CommandXboxController(Ports.Controllers.PRIMARY_CONTROLLER); private final CommandJoystick secondaryController = new CommandJoystick(Ports.Controllers.SECONDARY_CONTROLLER); private final RobotCommands commands = new RobotCommands(arm, drive, manipulator); private final DriveCommands driveCommands = drive.getCommands(); private final SendableChooser<String> autoOptionSelector = new SendableChooser<>(); /** * The container for the robot. Contains subsystems, IO devices, and commands. */ public RobotContainer() { for (String auto : AutoBuilder.getAllAutoNames()) { if (auto.equals("REGISTERED_COMMANDS")) continue; autoOptionSelector.addOption(auto, auto); } autoOptionSelector.setDefaultOption(DEFAULT_AUTO, DEFAULT_AUTO); SmartDashboard.putData("auto/Auto Option", autoOptionSelector); configureBindings(); } private void configureBindings() { Command switchDropOff = commands.switchDropOff(); Command exchange = commands.exchange(); Command exchangeReturn = commands.exchangeReturn(); Command portal = commands.portal(); Command cancelAuto = Commands.runOnce(() -> { switchDropOff.cancel(); exchange.cancel(); exchangeReturn.cancel(); portal.cancel(); }); // Primary Driver drive.setDefaultCommand( driveCommands.teleopCommand( () -> -controlCurve(primaryController.getLeftY()), () -> -controlCurve(primaryController.getLeftX()), () -> -controlCurve(primaryController.getRightX()) ) ); primaryController.rightBumper().onTrue(cancelAuto); primaryController.leftBumper().onTrue(cancelAuto); primaryController.a().onTrue(commands.groundPickup()); primaryController.b().onTrue(switchDropOff); primaryController.x().onTrue(portal); primaryController.y().onTrue(exchange); primaryController.leftStick().onTrue(commands.driving()); primaryController.rightStick().onTrue(commands.driving()); // Secondary Driver secondaryController.button(6).onTrue(exchange); secondaryController.button(7).onTrue(exchangeReturn); secondaryController.button(8).onTrue(portal); secondaryController.button(9).onTrue(switchDropOff); secondaryController.button(10).onTrue(commands.groundPickup()); secondaryController.button(11).onTrue(commands.resting()); secondaryController.button(12).onTrue(commands.driving()); } private double controlCurve(double input) { // Multiplier based on trigger axis (whichever one is larger) then scaled to start at 0.35 return Utils.controlCurve(input, Joystick.EXPONENT, Joystick.DEADBAND) * ( Utils.controlCurve( Math.max(primaryController.getLeftTriggerAxis(), primaryController.getRightTriggerAxis()),
Teleop.Speed.EXPONENT,
3
2023-10-23 20:31:46+00:00
8k
ChrisGenti/DiscordTickets
src/main/java/com/github/chrisgenti/discordtickets/listeners/modals/ModalListener.java
[ { "identifier": "TicketManager", "path": "src/main/java/com/github/chrisgenti/discordtickets/managers/TicketManager.java", "snippet": "public class TicketManager {\n private int lastNumber;\n private final List<Ticket> ticketCache;\n\n public TicketManager(DiscordTickets discord) {\n this.ticketCache = new ArrayList<>();\n\n MongoManager mongoManager = discord.getMongoManager();\n this.setLastNumber(mongoManager.ticketLastNumber()); this.ticketCache.addAll(mongoManager.ticketsToList());\n }\n\n public int getLastNumber() {\n return lastNumber;\n }\n\n public Ticket getTicketByChannel(String channelID) {\n return this.ticketCache.stream().filter(var -> var.getChannelID().equals(channelID)).findFirst().orElse(null);\n }\n\n public List<Ticket> getTicketsByUser(String userID) {\n return this.ticketCache.stream().filter(var -> var.getUserID().equals(userID)).collect(Collectors.toList());\n }\n\n public List<Ticket> getTicketCache() {\n return ticketCache;\n }\n\n public void setLastNumber(int number) {\n this.lastNumber = number;\n }\n}" }, { "identifier": "Ticket", "path": "src/main/java/com/github/chrisgenti/discordtickets/objects/Ticket.java", "snippet": "public class Ticket {\n private final int id;\n private final TicketType ticketType;\n private final String userID, channelID;\n private final Date openDate;\n private Date closeDate;\n\n public Ticket(int id, TicketType ticketType, String userID, String channelID, Date openDate) {\n this.id = id;\n this.ticketType = ticketType;\n this.userID = userID;\n this.channelID = channelID;\n this.openDate = openDate;\n this.closeDate = null;\n }\n\n public int getId() {\n return id;\n }\n\n public TicketType getTicketType() {\n return ticketType;\n }\n\n public String getUserID() {\n return userID;\n }\n\n public String getChannelID() {\n return channelID;\n }\n\n public Date getOpenDate() {\n return openDate;\n }\n\n public Date getCloseDate() {\n return closeDate;\n }\n\n public void setCloseDate(Date closeDate) {\n this.closeDate = closeDate;\n }\n}" }, { "identifier": "TicketType", "path": "src/main/java/com/github/chrisgenti/discordtickets/tools/enums/TicketType.java", "snippet": "public enum TicketType {\n PUNISHMENT(\"punishment\", \"TICKETS\", \"Punishment\", \":printer:\"),\n PAYMENTS(\"payments\", \"TICKETS\", \"Buycraft / Payment\", \":dollar:\"),\n STAFF_REPORTS(\"staff_reports\", \"STAFF REPORT TICKETS\", \"Staff Reports\", \":page_facing_up:\"),\n PLAYER_REPORTS(\"player_reports\", \"PLAYER REPORT TICKETS\", \"Player Reports\", \":clipboard:\"),\n BUG_REPORTS(\"bug_reports\", \"TICKETS\", \"Bug Reports\", \":bug:\"),\n GENERAL_QUESTIONS(\"general_questions\", \"TICKETS\", \"General Questions\", \":gear:\");\n\n private final String customID, category, label, emoji;\n TicketType(String customID, String category, String label, String emoji) {\n this.customID = customID; this.category = category; this.label = label; this.emoji = emoji;\n }\n\n public static TicketType getByCustomID(String value) {\n return Arrays.stream(values()).filter(var -> var.customID.equals(value)).findFirst().orElse(null);\n }\n\n public String getCategory() {\n return category;\n }\n\n public String getLabel() {\n return label;\n }\n\n @SuppressWarnings(\"OptionalGetWithoutIsPresent\")\n public SelectMenuOption createMenuOption() {\n return SelectMenuOption.create(this.label, this.customID, \"\", EmojiManager.getByAlias(this.emoji).get().getEmoji());\n }\n}" }, { "identifier": "DiscordTickets", "path": "src/main/java/com/github/chrisgenti/discordtickets/DiscordTickets.java", "snippet": "public class DiscordTickets {\n private final DecimalFormat decimalFormat = new DecimalFormat(\"##0,000\");\n\n private DiscordApi discord;\n private MongoManager mongoManager;\n private TicketManager ticketManager;\n\n public static final String CONFIG_LOCATION = System.getProperty(\"config.location\", \"config.json\");\n\n public void init() {\n /*\n LAUNCH MESSAGE\n */\n Logger.info(MessageUtil.LAUNCH_MESSAGE);\n\n /*\n LOAD\n */\n this.load();\n }\n\n private void load() {\n long mills = System.currentTimeMillis();\n\n ObjectTriple<FileResult, DiscordData, Exception> objectTriple = FileUtil.loadData(Paths.get(CONFIG_LOCATION));\n\n switch (objectTriple.left()) {\n case CREATED, EXISTING -> {\n /*\n START\n */\n this.start(mills, objectTriple.left(), objectTriple.mid()); break;\n }\n case MALFORMED -> {\n /*\n SHUTDOWN\n */\n this.shutdown(); break;\n }\n }\n }\n\n private void start(long mills, @NotNull FileResult result, @NotNull DiscordData data) {\n DiscordData.Discord discordData = data.discord(); DiscordData.Mongo mongoData = data.mongo();\n\n if (discordData.token().isEmpty()) {\n this.shutdown();\n return;\n }\n\n if (mongoData.hostname().isEmpty() || mongoData.username().isEmpty() || mongoData.password().isEmpty()) {\n this.shutdown();\n return;\n }\n\n /*\n DISCORD INSTANCE\n */\n this.discord = new DiscordApiBuilder()\n .setToken(\"MTE1ODc1MjcxMzA5MDI4OTY4NQ.GtV-Us.yBnbC-K-NYr6yErlDxx4oUATUuzaaQqXroYHEg\")\n .addIntents(Intent.MESSAGE_CONTENT, Intent.GUILDS)\n .login()\n .join();\n\n /*\n MANAGERS INSTANCE\n */\n this.mongoManager = new MongoManager(mongoData.hostname(), mongoData.username(), mongoData.password());\n this.ticketManager = new TicketManager(this);\n\n /*\n CREATE COMMANDS\n */\n SlashCommand.with(\"message\", \"Send message for ticket management.\")\n .setDefaultEnabledForPermissions(PermissionType.ADMINISTRATOR)\n .createGlobal(discord)\n .join();\n SlashCommand.with(\"close\", \"Close the ticket linked to this channel.\")\n .setDefaultEnabledForPermissions(PermissionType.ADMINISTRATOR)\n .createGlobal(discord)\n .join();\n Logger.info(\"Successfully logged commands: [Message, Stop]\");\n\n /*\n REGISTER LISTENERS\n */\n this.discord.addListener(new CommandListener(this));\n this.discord.addListener(new MenuListener());\n this.discord.addListener(new ModalListener(this));\n Logger.info(\"Successfully logged events: [SlashCommandCreateEvent, SelectMenuChooseEvent, ModalSubmitEvent]\");\n\n /*\n CONFIG MESSAGE\n */\n Logger.info(\n MessageUtil.CONFIG_MESSAGE\n .replace(\"%config_result%\", result.reason())\n .replace(\"%opened_tickets%\", mongoManager.openedTicketsCount() + \"\")\n .replace(\"%closed_tickets%\", mongoManager.closedTicketsCount() + \"\")\n .replace(\"%mills%\", decimalFormat.format(System.currentTimeMillis() - mills))\n );\n }\n\n private void shutdown() {\n Logger.info(MessageUtil.MALFORMED_CONFIG_MESSAGE);\n\n try {\n Thread.sleep(5000);\n } catch (IllegalArgumentException | InterruptedException exc) {\n throw new RuntimeException(exc);\n }\n }\n\n public DiscordApi getDiscord() {\n return discord;\n }\n\n public MongoManager getMongoManager() {\n return mongoManager;\n }\n\n public TicketManager getTicketManager() {\n return ticketManager;\n }\n}" }, { "identifier": "MongoManager", "path": "src/main/java/com/github/chrisgenti/discordtickets/managers/mongo/MongoManager.java", "snippet": "public class MongoManager {\n private final MongoClientSettings settings;\n\n public MongoManager(String hostname, String username, String password) {\n LoggerFactory.getLogger(MongoManager.class);\n\n this.settings = MongoClientSettings.builder()\n .applyConnectionString(new ConnectionString(\"mongodb+srv://\" + username + \":\" + password + \"@\" + hostname + \"/?retryWrites=true&w=majority\"))\n .serverApi(\n ServerApi.builder()\n .version(ServerApiVersion.V1)\n .build()\n )\n .build();\n }\n\n public void createTicket(Ticket ticket) {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n\n Document document = new Document(); document.put(\"id\", ticket.getId()); document.put(\"type\", ticket.getTicketType().toString()); document.put(\"user_id\", ticket.getUserID()); document.put(\"channel_id\", ticket.getChannelID()); document.put(\"open_date\", Util.formatDate(ticket.getOpenDate()));\n collection.insertOne(document);\n } catch (MongoException ignored) {}\n }\n }\n\n public void closeTicket(Ticket ticket) {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> openCollection = database.getCollection(\"opened_tickets\");\n MongoCollection<Document> closeConnection = database.getCollection(\"closed_tickets\");\n\n Document searchDocument = new Document(); searchDocument.put(\"id\", ticket.getId());\n openCollection.deleteOne(searchDocument);\n\n Document document = new Document(); document.put(\"id\", ticket.getId()); document.put(\"type\", ticket.getTicketType().toString()); document.put(\"user_id\", ticket.getUserID()); document.put(\"channel_id\", ticket.getChannelID()); document.put(\"open_date\", Util.formatDate(ticket.getOpenDate())); document.put(\"close_date\", Util.formatDate(ticket.getCloseDate()));\n closeConnection.insertOne(document);\n } catch (MongoException ignored) {}\n }\n }\n\n public int ticketLastNumber() {\n List<Integer> values = new ArrayList<>();\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection;\n\n collection = database.getCollection(\"opened_tickets\");\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext())\n values.add(cursor.next().getInteger(\"id\"));\n }\n\n collection = database.getCollection(\"closed_tickets\");\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext())\n values.add(cursor.next().getInteger(\"id\"));\n }\n } catch (MongoException ignored) {}\n }\n return values.isEmpty() ? 0 : Collections.max(values);\n }\n\n public List<Ticket> ticketsToList() {\n List<Ticket> values = new ArrayList<>();\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n\n try (MongoCursor<Document> cursor = collection.find().cursor()) {\n while (cursor.hasNext()) {\n Document document = cursor.next();\n\n values.add(new Ticket(\n document.getInteger(\"id\"), TicketType.valueOf(document.getString(\"type\")), document.getString(\"user_id\"), document.getString(\"channel_id\"), Util.parseDate(document.getString(\"open_date\"))\n ));\n }\n }\n } catch (MongoException ignored) {}\n }\n return values;\n }\n\n public int openedTicketsCount() {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"opened_tickets\");\n return Math.toIntExact(collection.countDocuments());\n } catch (MongoException ignored) {}\n }\n return 0;\n }\n\n public int closedTicketsCount() {\n try (MongoClient mongoClient = MongoClients.create(this.settings)) {\n try {\n MongoDatabase database = mongoClient.getDatabase(\"discord_tickets\");\n MongoCollection<Document> collection = database.getCollection(\"closed_tickets\");\n return Math.toIntExact(collection.countDocuments());\n } catch (MongoException ignored) {}\n }\n return 0;\n }\n}" }, { "identifier": "MessageUtil", "path": "src/main/java/com/github/chrisgenti/discordtickets/tools/utils/messages/MessageUtil.java", "snippet": "public class MessageUtil {\n private static final String RESET = \"\\033[0m\";\n private static final String RED = \"\\033[1;31m\";\n private static final String BLUE = \"\\033[1;34m\";\n private static final String WHITE = \"\\033[0;37m\";\n\n private static final char CUBE = '\\u25A0';\n private static final char ARROW = '\\u25B8';\n\n private static final String CUBE_COMPONENT = BLUE + CUBE;\n private static final String CUBE_COMPONENT_LINE = CUBE_COMPONENT + \" \" + CUBE_COMPONENT + \" \" + CUBE_COMPONENT;\n\n private static final String ARROW_COMPONENT = WHITE + ARROW + \" \";\n\n public static final String LAUNCH_MESSAGE =\n \"Starting Discord Tickets...\" + \"\\n\" + \"\\n\" +\n CUBE_COMPONENT_LINE + \"\\n\" + CUBE_COMPONENT_LINE + \" DISCORD TICKETS v1.0\" + \"\\n\" +\n CUBE_COMPONENT_LINE + \"\\n\" + \"\\n\" +\n ARROW_COMPONENT + \"os: \" + System.getProperty(\"os.name\") + \", \" + System.getProperty(\"os.version\") + \" - \" + System.getProperty(\"os.arch\") + \"\\n\" +\n ARROW_COMPONENT + \"java: \" + System.getProperty(\"java.version\") + \" - \" + System.getProperty(\"java.vendor\") + \", \" + System.getProperty(\"java.vendor.url\") + RESET + \"\\n\";\n\n public static final String CONFIG_MESSAGE =\n \"Discord Tickets launch result...\" + \"\\n\" + \"\\n\" +\n ARROW_COMPONENT + \"config location: config.json, %config_result%\" + \"\\n\" +\n ARROW_COMPONENT + \"opened tickets: %opened_tickets%, closed tickets: %closed_tickets%\" + \"\\n\" + \"\\n\" +\n WHITE +\"Bot started in %mills%s\" + \"\\n\";\n\n public static final String MALFORMED_CONFIG_MESSAGE =\n \"\\n\" + \"\\n\" +\n RED + \" ! Error while launching the Discord Tickets...\" + \"\\n\" +\n RED + \" The configuration file is malformed, for security\" + \"\\n\" +\n RED + \" and logistic reason the server will automatically\" + \"\\n\" +\n RED + \" stop in 5 seconds...\" + \"\\n\" + \"\\n\" + RESET;\n\n public static String TICKET_CREATE_MESSAGE =\n WHITE + \"%username% opened a ticket in the %ticket_category% category.\" + BLUE + \" ID: %ticket_id%\" + RESET;\n\n public static String TICKET_CLOSE_MESSAGE =\n WHITE + \"%admin_username% closed %username%'s ticket.\" + BLUE + \" ID: %ticket_id%\" + RESET;\n}" } ]
import com.github.chrisgenti.discordtickets.managers.TicketManager; import com.github.chrisgenti.discordtickets.objects.Ticket; import com.github.chrisgenti.discordtickets.tools.enums.TicketType; import com.github.chrisgenti.discordtickets.DiscordTickets; import com.github.chrisgenti.discordtickets.managers.mongo.MongoManager; import com.github.chrisgenti.discordtickets.tools.utils.messages.MessageUtil; import org.javacord.api.entity.channel.ChannelCategory; import org.javacord.api.entity.channel.TextChannel; import org.javacord.api.entity.message.MessageBuilder; import org.javacord.api.entity.message.MessageFlag; import org.javacord.api.entity.message.embed.EmbedBuilder; import org.javacord.api.entity.message.mention.AllowedMentionsBuilder; import org.javacord.api.entity.permission.PermissionType; import org.javacord.api.entity.permission.PermissionsBuilder; import org.javacord.api.entity.permission.Role; import org.javacord.api.entity.server.Server; import org.javacord.api.entity.user.User; import org.javacord.api.event.interaction.ModalSubmitEvent; import org.javacord.api.listener.interaction.ModalSubmitListener; import org.tinylog.Logger; import java.awt.*; import java.time.Instant; import java.util.Date;
4,723
package com.github.chrisgenti.discordtickets.listeners.modals; public class ModalListener implements ModalSubmitListener { private final MongoManager mongoManager; private final TicketManager ticketManager; public ModalListener(DiscordTickets discord) { this.mongoManager = discord.getMongoManager(); this.ticketManager = discord.getTicketManager(); } @Override public void onModalSubmit(ModalSubmitEvent event) { User user = event.getModalInteraction().getUser(); String customID = event.getModalInteraction().getCustomId().replace("_modal", ""); TicketType ticketType = TicketType.getByCustomID(customID); if (ticketType == null) return; if (event.getModalInteraction().getServer().isEmpty()) return; Server server = event.getModalInteraction().getServer().get(); if (ticketManager.getTicketsByUser(user.getIdAsString()).size() == 2) { event.getInteraction().createImmediateResponder() .setFlags(MessageFlag.EPHEMERAL) .addEmbed( new EmbedBuilder() .setAuthor("Discord Support Tickets", "", "https://i.imgur.com/s5k4che.png") .setDescription("You have reached your ticket limit.") .setColor(Color.RED) ).respond(); return; } if (server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().isEmpty()) return; ChannelCategory category = server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().get(); Role role = null; if (server.getRolesByName("SUPPORT").stream().findFirst().isPresent()) role = server.getRolesByName("SUPPORT").stream().findFirst().get(); String username = null; if (event.getModalInteraction().getTextInputValueByCustomId("username").isPresent()) username = event.getModalInteraction().getTextInputValueByCustomId("username").get(); String description = null; if (event.getModalInteraction().getTextInputValueByCustomId("description").isPresent()) description = event.getModalInteraction().getTextInputValueByCustomId("description").get(); String reportedUsername = null; if ((ticketType == TicketType.PLAYER_REPORTS || ticketType == TicketType.STAFF_REPORTS) && event.getModalInteraction().getTextInputValueByCustomId("reported_username").isPresent()) reportedUsername = event.getModalInteraction().getTextInputValueByCustomId("reported_username").get(); int number = ticketManager.getLastNumber() + 1; MessageBuilder builder = reportedUsername == null ? this.createMessage(ticketType, role, username, description) : this.createMessage(ticketType, role, username, reportedUsername, description); server.createTextChannelBuilder() .setCategory(category) .setName( "ticket-{username}-{id}" .replace("{username}", user.getName()) .replace("{id}", String.valueOf(number)) ) .addPermissionOverwrite(server.getEveryoneRole(), new PermissionsBuilder().setDenied(PermissionType.VIEW_CHANNEL).build()) .addPermissionOverwrite(event.getModalInteraction().getUser(), new PermissionsBuilder().setAllowed(PermissionType.VIEW_CHANNEL, PermissionType.SEND_MESSAGES).build()) .create().whenComplete((var, throwable) -> { if (var.getCurrentCachedInstance().isEmpty()) return; TextChannel channel = var.getCurrentCachedInstance().get(); builder.send(channel); event.getInteraction().createImmediateResponder() .setAllowedMentions(new AllowedMentionsBuilder().build()) .addEmbed( new EmbedBuilder() .setAuthor(ticketType.getLabel() + " Ticket", "", "https://i.imgur.com/s5k4che.png") .setDescription("New ticket created: <#" + channel.getIdAsString() + ">") .setColor(Color.GREEN) ).setFlags(MessageFlag.EPHEMERAL).respond(); Ticket ticket = new Ticket(number, ticketType, user.getIdAsString(), channel.getIdAsString(), Date.from(Instant.now())); mongoManager.createTicket(ticket); ticketManager.getTicketCache().add(ticket); ticketManager.setLastNumber(number); Logger.info(
package com.github.chrisgenti.discordtickets.listeners.modals; public class ModalListener implements ModalSubmitListener { private final MongoManager mongoManager; private final TicketManager ticketManager; public ModalListener(DiscordTickets discord) { this.mongoManager = discord.getMongoManager(); this.ticketManager = discord.getTicketManager(); } @Override public void onModalSubmit(ModalSubmitEvent event) { User user = event.getModalInteraction().getUser(); String customID = event.getModalInteraction().getCustomId().replace("_modal", ""); TicketType ticketType = TicketType.getByCustomID(customID); if (ticketType == null) return; if (event.getModalInteraction().getServer().isEmpty()) return; Server server = event.getModalInteraction().getServer().get(); if (ticketManager.getTicketsByUser(user.getIdAsString()).size() == 2) { event.getInteraction().createImmediateResponder() .setFlags(MessageFlag.EPHEMERAL) .addEmbed( new EmbedBuilder() .setAuthor("Discord Support Tickets", "", "https://i.imgur.com/s5k4che.png") .setDescription("You have reached your ticket limit.") .setColor(Color.RED) ).respond(); return; } if (server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().isEmpty()) return; ChannelCategory category = server.getChannelCategoriesByName(ticketType.getCategory()).stream().findFirst().get(); Role role = null; if (server.getRolesByName("SUPPORT").stream().findFirst().isPresent()) role = server.getRolesByName("SUPPORT").stream().findFirst().get(); String username = null; if (event.getModalInteraction().getTextInputValueByCustomId("username").isPresent()) username = event.getModalInteraction().getTextInputValueByCustomId("username").get(); String description = null; if (event.getModalInteraction().getTextInputValueByCustomId("description").isPresent()) description = event.getModalInteraction().getTextInputValueByCustomId("description").get(); String reportedUsername = null; if ((ticketType == TicketType.PLAYER_REPORTS || ticketType == TicketType.STAFF_REPORTS) && event.getModalInteraction().getTextInputValueByCustomId("reported_username").isPresent()) reportedUsername = event.getModalInteraction().getTextInputValueByCustomId("reported_username").get(); int number = ticketManager.getLastNumber() + 1; MessageBuilder builder = reportedUsername == null ? this.createMessage(ticketType, role, username, description) : this.createMessage(ticketType, role, username, reportedUsername, description); server.createTextChannelBuilder() .setCategory(category) .setName( "ticket-{username}-{id}" .replace("{username}", user.getName()) .replace("{id}", String.valueOf(number)) ) .addPermissionOverwrite(server.getEveryoneRole(), new PermissionsBuilder().setDenied(PermissionType.VIEW_CHANNEL).build()) .addPermissionOverwrite(event.getModalInteraction().getUser(), new PermissionsBuilder().setAllowed(PermissionType.VIEW_CHANNEL, PermissionType.SEND_MESSAGES).build()) .create().whenComplete((var, throwable) -> { if (var.getCurrentCachedInstance().isEmpty()) return; TextChannel channel = var.getCurrentCachedInstance().get(); builder.send(channel); event.getInteraction().createImmediateResponder() .setAllowedMentions(new AllowedMentionsBuilder().build()) .addEmbed( new EmbedBuilder() .setAuthor(ticketType.getLabel() + " Ticket", "", "https://i.imgur.com/s5k4che.png") .setDescription("New ticket created: <#" + channel.getIdAsString() + ">") .setColor(Color.GREEN) ).setFlags(MessageFlag.EPHEMERAL).respond(); Ticket ticket = new Ticket(number, ticketType, user.getIdAsString(), channel.getIdAsString(), Date.from(Instant.now())); mongoManager.createTicket(ticket); ticketManager.getTicketCache().add(ticket); ticketManager.setLastNumber(number); Logger.info(
MessageUtil.TICKET_CREATE_MESSAGE
5
2023-10-23 13:24:05+00:00
8k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthPublisherAdapter.java
[ { "identifier": "BaseEthAdapter", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/BaseEthAdapter.java", "snippet": "public abstract class BaseEthAdapter {\n\n private static final BigInteger GAS_LIMIT = BigInteger.valueOf(6721975L);\n private static final BigInteger GAS_PRICE = BigInteger.valueOf(20000000000L);\n\n private final ContractGasProvider contractGasProvider = new ContractGasProvider() {\n @Override\n public BigInteger getGasPrice(String contractFunc) {\n return GAS_PRICE;\n }\n\n @Override\n public BigInteger getGasPrice() {\n return GAS_PRICE;\n }\n\n @Override\n public BigInteger getGasLimit(String contractFunc) {\n return GAS_LIMIT;\n }\n\n @Override\n public BigInteger getGasLimit() {\n return GAS_LIMIT;\n }\n };\n\n private final Web3j web3j;\n\n protected BaseEthAdapter(Web3j web3j) {\n this.web3j = web3j;\n }\n\n protected static Credentials createDummyCredentials() {\n try {\n return Credentials.create(Keys.createEcKeyPair());\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public String getCurrentBlockNumber() {\n try {\n BigInteger blockNumber = web3j.ethBlockNumber().sendAsync().get().getBlockNumber();\n return Numeric.toHexStringWithPrefix(blockNumber);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n protected static EthFilter createEventFilter(String contractAddress, String blockNumber,\n Event event) {\n BigInteger blockNum;\n if (blockNumber != null) {\n blockNum = Numeric.toBigInt(blockNumber).add(BigInteger.ONE);\n } else {\n blockNum = BigInteger.ZERO;\n }\n\n DefaultBlockParameter from = DefaultBlockParameter.valueOf(blockNum);\n DefaultBlockParameter to = DefaultBlockParameterName.LATEST;\n\n EthFilter filter = new EthFilter(from, to, contractAddress);\n filter.addSingleTopic(EventEncoder.encode(event));\n return filter;\n }\n\n protected static String getBlockNumberFromEventResponse(BaseEventResponse response) {\n return Numeric.toHexStringWithPrefix(response.log.getBlockNumber());\n }\n\n protected FeedPublisher createPublisherContract(String contractAddr, Credentials credentials) {\n return new FeedPublisherWrapper(contractAddr, web3j, credentials, contractGasProvider);\n }\n\n protected FeedRegistry createRegistryContract(String contractAddr, Credentials credentials) {\n return new FeedRegistryWrapper(contractAddr, web3j, credentials, contractGasProvider);\n }\n\n protected FeedSubscriber createSubscriberContract(String contractAddr, Credentials credentials) {\n return new FeedSubscriberWrapper(contractAddr, web3j, credentials, contractGasProvider);\n }\n\n protected static boolean isValidAddress(String address) {\n return address != null && !address.equals(\"0x0000000000000000000000000000000000000000\");\n }\n\n}" }, { "identifier": "EthUtil", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/EthUtil.java", "snippet": "public final class EthUtil {\n\n private EthUtil() {}\n\n public static String shortenAddress(String addr) {\n return addr.substring(0, 6) + \"...\" + addr.substring(addr.length() - 2);\n }\n\n}" }, { "identifier": "FeedPublisher", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedPublisher.java", "snippet": "@SuppressWarnings(\"rawtypes\")\npublic class FeedPublisher extends Contract {\n public static final String BINARY = \"608060405234801561001057600080fd5b50600080546001600160a01b03191633179055604080516060810190915260288082526100459190610b80602083013961004a565b610104565b6100918160405160240161005e91906100b6565b60408051601f198184030181529190526020810180516001600160e01b0390811663104c13eb60e21b1790915261009416565b50565b80516a636f6e736f6c652e6c6f6790602083016000808383865afa5050505050565b600060208083528351808285015260005b818110156100e3578581018301518582016040015282016100c7565b506000604082860101526040601f19601f8301168501019250505092915050565b610a6d806101136000396000f3fe608060405234801561001057600080fd5b506004361061007d5760003560e01c80637b7636a11161005b5780637b7636a1146100c05780637c83510f146100e057806384b439c0146100f55780638da5cb5b1461010857600080fd5b806313af4035146100825780631c4bdaa314610097578063243e280b146100ad575b600080fd5b61009561009036600461064b565b610123565b005b6002546040519081526020015b60405180910390f35b6100956100bb366004610691565b610178565b6100d36100ce366004610742565b6102aa565b6040516100a491906107a1565b6100e86103f8565b6040516100a491906107d8565b610095610103366004610691565b61048a565b6000546040516001600160a01b0390911681526020016100a4565b6000546001600160a01b031633146101565760405162461bcd60e51b815260040161014d906107eb565b60405180910390fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146101a25760405162461bcd60e51b815260040161014d906107eb565b600280546040805160608101825282815242602082019081529181018581526001840185556000949094528051600384027f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace810191825592517f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5acf84015593519293909290917f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ad0019061025490826108bb565b50505061027b604051806060016040528060228152602001610a166022913933838561058e565b60405181907f6dda240fc875f1ee65b95abd125377f81bf199395a55b7f2ef46c713cae8c29890600090a25050565b6102ce60405180606001604052806000815260200160008152602001606081525090565b600254821061031f5760405162461bcd60e51b815260206004820152601860248201527f507562206974656d20646f6573206e6f74206578697374210000000000000000604482015260640161014d565b600282815481106103325761033261097b565b9060005260206000209060030201604051806060016040529081600082015481526020016001820154815260200160028201805461036f90610833565b80601f016020809104026020016040519081016040528092919081815260200182805461039b90610833565b80156103e85780601f106103bd576101008083540402835291602001916103e8565b820191906000526020600020905b8154815290600101906020018083116103cb57829003601f168201915b5050505050815250509050919050565b60606001805461040790610833565b80601f016020809104026020016040519081016040528092919081815260200182805461043390610833565b80156104805780601f1061045557610100808354040283529160200191610480565b820191906000526020600020905b81548152906001019060200180831161046357829003601f168201915b5050505050905090565b6000546001600160a01b031633146104b45760405162461bcd60e51b815260040161014d906107eb565b60016104c082826108bb565b5061058b6040518060400160405280601d81526020017f4163636f756e742025732073657420666565642055524c3a2027257327000000815250336001805461050890610833565b80601f016020809104026020016040519081016040528092919081815260200182805461053490610833565b80156105815780601f1061055657610100808354040283529160200191610581565b820191906000526020600020905b81548152906001019060200180831161056457829003601f168201915b50505050506105dd565b50565b6105d7848484846040516024016105a89493929190610991565b60408051601f198184030181529190526020810180516001600160e01b0316632d23bb1960e11b179052610629565b50505050565b6106248383836040516024016105f5939291906109d7565b60408051601f198184030181529190526020810180516001600160e01b031663e0e9ad4f60e01b179052610629565b505050565b80516a636f6e736f6c652e6c6f6790602083016000808383865afa5050505050565b60006020828403121561065d57600080fd5b81356001600160a01b038116811461067457600080fd5b9392505050565b634e487b7160e01b600052604160045260246000fd5b6000602082840312156106a357600080fd5b813567ffffffffffffffff808211156106bb57600080fd5b818401915084601f8301126106cf57600080fd5b8135818111156106e1576106e161067b565b604051601f8201601f19908116603f011681019083821181831017156107095761070961067b565b8160405282815287602084870101111561072257600080fd5b826020860160208301376000928101602001929092525095945050505050565b60006020828403121561075457600080fd5b5035919050565b6000815180845260005b8181101561078157602081850181015186830182015201610765565b506000602082860101526020601f19601f83011685010191505092915050565b602081528151602082015260208201516040820152600060408301516060808401526107d0608084018261075b565b949350505050565b602081526000610674602083018461075b565b60208082526028908201527f43616c6c6572206f66207468652066756e6374696f6e206973206e6f7420746860408201526765206f776e65722160c01b606082015260800190565b600181811c9082168061084757607f821691505b60208210810361086757634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111561062457600081815260208120601f850160051c810160208610156108945750805b601f850160051c820191505b818110156108b3578281556001016108a0565b505050505050565b815167ffffffffffffffff8111156108d5576108d561067b565b6108e9816108e38454610833565b8461086d565b602080601f83116001811461091e57600084156109065750858301515b600019600386901b1c1916600185901b1785556108b3565b600085815260208120601f198616915b8281101561094d5788860151825594840194600190910190840161092e565b508582101561096b5787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b634e487b7160e01b600052603260045260246000fd5b6080815260006109a4608083018761075b565b6001600160a01b03861660208401526040830185905282810360608401526109cc818561075b565b979650505050505050565b6060815260006109ea606083018661075b565b6001600160a01b03851660208401528281036040840152610a0b818561075b565b969550505050505056fe4163636f756e74202573207075626c6973686564206974656d2025643a2027257327a264697066735822122015025348b2070e170e07b005bee318202c0997e07c9b4a7af027615656f8950964736f6c634300081300335075626c697368657220636f6e747261637420686173206265656e20636f6e737472756374656421\";\n\n public static final String FUNC_GETFEEDURL = \"getFeedUrl\";\n\n public static final String FUNC_GETPUBITEM = \"getPubItem\";\n\n public static final String FUNC_GETTOTALPUBITEMCOUNT = \"getTotalPubItemCount\";\n\n public static final String FUNC_OWNER = \"owner\";\n\n public static final String FUNC_PUBLISH = \"publish\";\n\n public static final String FUNC_SETFEEDURL = \"setFeedUrl\";\n\n public static final String FUNC_SETOWNER = \"setOwner\";\n\n public static final Event NEWPUBITEM_EVENT = new Event(\"NewPubItem\",\n Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>(true) {}));\n\n @Deprecated\n protected FeedPublisher(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);\n }\n\n protected FeedPublisher(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n super(BINARY, contractAddress, web3j, credentials, contractGasProvider);\n }\n\n @Deprecated\n protected FeedPublisher(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);\n }\n\n protected FeedPublisher(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider);\n }\n\n public List<NewPubItemEventResponse> getNewPubItemEvents(TransactionReceipt transactionReceipt) {\n List<EventValuesWithLog> valueList = extractEventParametersWithLog(NEWPUBITEM_EVENT, transactionReceipt);\n ArrayList<NewPubItemEventResponse> responses = new ArrayList<NewPubItemEventResponse>(valueList.size());\n for (EventValuesWithLog eventValues : valueList) {\n NewPubItemEventResponse typedResponse = new NewPubItemEventResponse();\n typedResponse.log = eventValues.getLog();\n typedResponse.num = (BigInteger) eventValues.getIndexedValues().get(0).getValue();\n responses.add(typedResponse);\n }\n return responses;\n }\n\n public Flowable<NewPubItemEventResponse> newPubItemEventFlowable(EthFilter filter) {\n return web3j.ethLogFlowable(filter).map(new Function<Log, NewPubItemEventResponse>() {\n @Override\n public NewPubItemEventResponse apply(Log log) {\n EventValuesWithLog eventValues = extractEventParametersWithLog(NEWPUBITEM_EVENT, log);\n NewPubItemEventResponse typedResponse = new NewPubItemEventResponse();\n typedResponse.log = log;\n typedResponse.num = (BigInteger) eventValues.getIndexedValues().get(0).getValue();\n return typedResponse;\n }\n });\n }\n\n public Flowable<NewPubItemEventResponse> newPubItemEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {\n EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());\n filter.addSingleTopic(EventEncoder.encode(NEWPUBITEM_EVENT));\n return newPubItemEventFlowable(filter);\n }\n\n public RemoteFunctionCall<String> getFeedUrl() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETFEEDURL,\n Arrays.<Type>asList(),\n Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}));\n return executeRemoteCallSingleValueReturn(function, String.class);\n }\n\n public RemoteFunctionCall<PubItem> getPubItem(BigInteger num) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETPUBITEM, \n Arrays.<Type>asList(new Uint256(num)),\n Arrays.<TypeReference<?>>asList(new TypeReference<PubItem>() {}));\n return executeRemoteCallSingleValueReturn(function, PubItem.class);\n }\n\n public RemoteFunctionCall<BigInteger> getTotalPubItemCount() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETTOTALPUBITEMCOUNT,\n Arrays.<Type>asList(),\n Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));\n return executeRemoteCallSingleValueReturn(function, BigInteger.class);\n }\n\n public RemoteFunctionCall<String> owner() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_OWNER,\n Arrays.<Type>asList(),\n Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));\n return executeRemoteCallSingleValueReturn(function, String.class);\n }\n\n public RemoteFunctionCall<TransactionReceipt> publish(String data) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_PUBLISH,\n Arrays.<Type>asList(new Utf8String(data)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> setFeedUrl(String feedUrl) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_SETFEEDURL, \n Arrays.<Type>asList(new Utf8String(feedUrl)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> setOwner(String _newOwner) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_SETOWNER,\n Arrays.<Type>asList(new Address(160, _newOwner)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n @Deprecated\n public static FeedPublisher load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n return new FeedPublisher(contractAddress, web3j, credentials, gasPrice, gasLimit);\n }\n\n @Deprecated\n public static FeedPublisher load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n return new FeedPublisher(contractAddress, web3j, transactionManager, gasPrice, gasLimit);\n }\n\n public static FeedPublisher load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n return new FeedPublisher(contractAddress, web3j, credentials, contractGasProvider);\n }\n\n public static FeedPublisher load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n return new FeedPublisher(contractAddress, web3j, transactionManager, contractGasProvider);\n }\n\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n return deployRemoteCall(FeedPublisher.class, web3j, credentials, contractGasProvider, BINARY, \"\");\n }\n\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n return deployRemoteCall(FeedPublisher.class, web3j, transactionManager, contractGasProvider, BINARY, \"\");\n }\n\n @Deprecated\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n return deployRemoteCall(FeedPublisher.class, web3j, credentials, gasPrice, gasLimit, BINARY, \"\");\n }\n\n @Deprecated\n public static RemoteCall<FeedPublisher> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n return deployRemoteCall(FeedPublisher.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, \"\");\n }\n\n public static class PubItem extends DynamicStruct {\n public BigInteger num;\n\n public BigInteger timestamp;\n\n public String data;\n\n public PubItem(BigInteger num, BigInteger timestamp, String data) {\n super(new Uint256(num), new Uint256(timestamp), new Utf8String(data));\n this.num = num;\n this.timestamp = timestamp;\n this.data = data;\n }\n\n public PubItem(Uint256 num, Uint256 timestamp, Utf8String data) {\n super(num, timestamp, data);\n this.num = num.getValue();\n this.timestamp = timestamp.getValue();\n this.data = data.getValue();\n }\n }\n\n public static class NewPubItemEventResponse extends BaseEventResponse {\n public BigInteger num;\n }\n}" }, { "identifier": "NewPubItemEventResponse", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedPublisher.java", "snippet": "public static class NewPubItemEventResponse extends BaseEventResponse {\n public BigInteger num;\n}" }, { "identifier": "PubItem", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedPublisher.java", "snippet": "public static class PubItem extends DynamicStruct {\n public BigInteger num;\n\n public BigInteger timestamp;\n\n public String data;\n\n public PubItem(BigInteger num, BigInteger timestamp, String data) {\n super(new Uint256(num), new Uint256(timestamp), new Utf8String(data));\n this.num = num;\n this.timestamp = timestamp;\n this.data = data;\n }\n\n public PubItem(Uint256 num, Uint256 timestamp, Utf8String data) {\n super(num, timestamp, data);\n this.num = num.getValue();\n this.timestamp = timestamp.getValue();\n this.data = data.getValue();\n }\n}" } ]
import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import com.moonstoneid.aerocast.common.eth.BaseEthAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher; import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.NewPubItemEventResponse; import com.moonstoneid.aerocast.common.eth.contracts.FeedPublisher.PubItem; import io.reactivex.disposables.Disposable; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.web3j.crypto.Credentials; import org.web3j.protocol.Web3j; import org.web3j.protocol.core.methods.request.EthFilter;
5,807
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j
package com.moonstoneid.aerocast.aggregator.eth; @Component @Slf4j
public class EthPublisherAdapter extends BaseEthAdapter {
0
2023-10-23 20:33:07+00:00
8k
UnityFoundation-io/Libre311
app/src/test/java/app/JurisdictionSupportRootControllerTest.java
[ { "identifier": "ServiceDTO", "path": "app/src/main/java/app/dto/service/ServiceDTO.java", "snippet": "@Introspected\npublic class ServiceDTO {\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n @JsonProperty(\"service_name\")\n private String serviceName;\n\n private String description;\n\n private boolean metadata;\n\n private ServiceType type;\n\n public ServiceDTO() {\n }\n\n public ServiceDTO(Service service) {\n this.serviceCode = service.getServiceCode();\n this.serviceName = service.getServiceName();\n this.description = service.getDescription();\n this.metadata = service.isMetadata();\n this.type = service.getType();\n if (service.getJurisdiction() != null) {\n this.jurisdictionId = service.getJurisdiction().getId();\n }\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public boolean isMetadata() {\n return metadata;\n }\n\n public void setMetadata(boolean metadata) {\n this.metadata = metadata;\n }\n\n public ServiceType getType() {\n return type;\n }\n\n public void setType(ServiceType type) {\n this.type = type;\n }\n}" }, { "identifier": "PostRequestServiceRequestDTO", "path": "app/src/main/java/app/dto/servicerequest/PostRequestServiceRequestDTO.java", "snippet": "@Introspected\npublic class PostRequestServiceRequestDTO {\n\n @NotBlank\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @Nullable\n @QueryValue(value = \"jurisdiction_id\")\n private String jurisdictionId;\n\n @JsonProperty(\"lat\")\n private String latitude;\n\n @JsonProperty(\"long\")\n private String longitude;\n\n @JsonProperty(\"address_string\")\n private String addressString;\n\n // The internal address ID used by a jurisdiction’s master address repository or other addressing system.\n @JsonProperty(\"address_id\")\n private String addressId;\n\n @Email(regexp = \"^[a-zA-Z0-9_+&*-]+(?:\\\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,7}$\")\n private String email;\n\n // The unique device ID of the device submitting the request. This is usually only used for mobile devices.\n @JsonProperty(\"device_id\")\n private String deviceId;\n\n // The unique ID for the user account of the person submitting the request\n @JsonProperty(\"account_id\")\n private String accountId;\n\n @JsonProperty(\"first_name\")\n @Pattern(regexp = \"^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð\\\\-'. ]+$\")\n private String firstName;\n\n @JsonProperty(\"last_name\")\n @Pattern(regexp = \"^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð\\\\-'. ]+$\")\n private String lastName;\n\n private String phone;\n\n @Size(max = 4000)\n private String description;\n\n @JsonProperty(\"media_url\")\n private String mediaUrl;\n\n @NotBlank\n @JsonProperty(\"g_recaptcha_response\")\n private String gRecaptchaResponse;\n\n public PostRequestServiceRequestDTO(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getLatitude() {\n return latitude;\n }\n\n public void setLatitude(String latitude) {\n this.latitude = latitude;\n }\n\n public String getLongitude() {\n return longitude;\n }\n\n public void setLongitude(String longitude) {\n this.longitude = longitude;\n }\n\n public String getAddressString() {\n return addressString;\n }\n\n public void setAddressString(String addressString) {\n this.addressString = addressString;\n }\n\n public String getAddressId() {\n return addressId;\n }\n\n public void setAddressId(String addressId) {\n this.addressId = addressId;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getDeviceId() {\n return deviceId;\n }\n\n public void setDeviceId(String deviceId) {\n this.deviceId = deviceId;\n }\n\n public String getAccountId() {\n return accountId;\n }\n\n public void setAccountId(String accountId) {\n this.accountId = accountId;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getMediaUrl() {\n return mediaUrl;\n }\n\n public void setMediaUrl(String mediaUrl) {\n this.mediaUrl = mediaUrl;\n }\n\n // see https://github.com/micronaut-projects/micronaut-core/issues/1853\n public Map<String, Object> toMap() {\n Map<String, Object> m = new HashMap<>();\n m.put(\"service_code\", getServiceCode());\n return m;\n }\n\n public String getgRecaptchaResponse() {\n return gRecaptchaResponse;\n }\n\n public void setgRecaptchaResponse(String gRecaptchaResponse) {\n this.gRecaptchaResponse = gRecaptchaResponse;\n }\n\n @Nullable\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(@Nullable String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n}" }, { "identifier": "PostResponseServiceRequestDTO", "path": "app/src/main/java/app/dto/servicerequest/PostResponseServiceRequestDTO.java", "snippet": "public class PostResponseServiceRequestDTO implements ServiceRequestResponseDTO {\n\n @JsonProperty(\"service_request_id\")\n private Long id;\n\n private String token;\n\n // Information about the action expected to fulfill the request or otherwise address the information reported.\n @JsonProperty(\"service_notice\")\n private String serviceNotice;\n\n @JsonProperty(\"account_id\")\n private String accountId;\n\n public PostResponseServiceRequestDTO() {\n }\n\n public PostResponseServiceRequestDTO(ServiceRequest serviceRequest) {\n this.id = serviceRequest.getId();\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getServiceNotice() {\n return serviceNotice;\n }\n\n public void setServiceNotice(String serviceNotice) {\n this.serviceNotice = serviceNotice;\n }\n\n public String getAccountId() {\n return accountId;\n }\n\n public void setAccountId(String accountId) {\n this.accountId = accountId;\n }\n}" }, { "identifier": "ServiceRequestDTO", "path": "app/src/main/java/app/dto/servicerequest/ServiceRequestDTO.java", "snippet": "@Introspected\npublic class ServiceRequestDTO implements ServiceRequestResponseDTO {\n\n @JsonProperty(\"service_request_id\")\n private Long id;\n\n @JsonProperty(\"jurisdiction_id\")\n private String jurisdictionId;\n\n private ServiceRequestStatus status;\n\n @JsonProperty(\"status_notes\")\n private String statusNotes;\n\n @JsonProperty(\"service_name\")\n private String serviceName;\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n private String description;\n\n @JsonProperty(\"agency_responsible\")\n private String agencyResponsible;\n\n @JsonProperty(\"service_notice\")\n private String serviceNotice;\n\n @JsonProperty(\"requested_datetime\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Instant dateCreated;\n\n @JsonProperty(\"updated_datetime\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Instant dateUpdated;\n\n @JsonProperty(\"expected_datetime\")\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n private Instant expectedDate;\n\n @JsonProperty(\"address\")\n private String address;\n\n // The internal address ID used by a jurisdiction’s master address repository or other addressing system.\n @JsonProperty(\"address_id\")\n private String addressId;\n\n @JsonProperty(\"zipcode\")\n private String zipCode;\n\n @JsonProperty(\"lat\")\n private String latitude;\n\n @JsonProperty(\"long\")\n private String longitude;\n\n @JsonProperty(\"media_url\")\n private String mediaUrl;\n\n @JsonProperty(\"selected_values\")\n private List<ServiceDefinitionAttribute> selectedValues;\n\n public ServiceRequestDTO() {\n }\n\n public ServiceRequestDTO(ServiceRequest serviceRequest) {\n this.id = serviceRequest.getId();\n this.status = serviceRequest.getStatus();\n this.statusNotes = serviceRequest.getStatusNotes();\n this.serviceName = serviceRequest.getService().getServiceName();\n this.serviceCode = serviceRequest.getService().getServiceCode();\n this.description = serviceRequest.getDescription();\n this.agencyResponsible = serviceRequest.getAgencyResponsible();\n this.serviceNotice = serviceRequest.getServiceNotice();\n this.dateCreated = serviceRequest.getDateCreated();\n this.dateUpdated = serviceRequest.getDateUpdated();\n this.expectedDate = serviceRequest.getExpectedDate();\n this.address = serviceRequest.getAddressString();\n this.addressId = serviceRequest.getAddressId();\n this.zipCode = serviceRequest.getZipCode();\n this.latitude = serviceRequest.getLatitude();\n this.longitude = serviceRequest.getLongitude();\n this.mediaUrl = serviceRequest.getMediaUrl();\n if (serviceRequest.getJurisdiction() != null) {\n this.jurisdictionId = serviceRequest.getJurisdiction().getId();\n }\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public ServiceRequestStatus getStatus() {\n return status;\n }\n\n public void setStatus(ServiceRequestStatus status) {\n this.status = status;\n }\n\n public String getStatusNotes() {\n return statusNotes;\n }\n\n public void setStatusNotes(String statusNotes) {\n this.statusNotes = statusNotes;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public String getAgencyResponsible() {\n return agencyResponsible;\n }\n\n public void setAgencyResponsible(String agencyResponsible) {\n this.agencyResponsible = agencyResponsible;\n }\n\n public String getServiceNotice() {\n return serviceNotice;\n }\n\n public void setServiceNotice(String serviceNotice) {\n this.serviceNotice = serviceNotice;\n }\n\n public Instant getDateCreated() {\n return dateCreated;\n }\n\n public void setDateCreated(Instant dateCreated) {\n this.dateCreated = dateCreated;\n }\n\n public Instant getDateUpdated() {\n return dateUpdated;\n }\n\n public void setDateUpdated(Instant dateUpdated) {\n this.dateUpdated = dateUpdated;\n }\n\n public Instant getExpectedDate() {\n return expectedDate;\n }\n\n public void setExpectedDate(Instant expectedDate) {\n this.expectedDate = expectedDate;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getAddressId() {\n return addressId;\n }\n\n public void setAddressId(String addressId) {\n this.addressId = addressId;\n }\n\n public String getZipCode() {\n return zipCode;\n }\n\n public void setZipCode(String zipCode) {\n this.zipCode = zipCode;\n }\n\n public String getLatitude() {\n return latitude;\n }\n\n public void setLatitude(String latitude) {\n this.latitude = latitude;\n }\n\n public String getLongitude() {\n return longitude;\n }\n\n public void setLongitude(String longitude) {\n this.longitude = longitude;\n }\n\n public String getMediaUrl() {\n return mediaUrl;\n }\n\n public void setMediaUrl(String mediaUrl) {\n this.mediaUrl = mediaUrl;\n }\n\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n\n // see https://github.com/micronaut-projects/micronaut-core/issues/1853\n public Map<String, Object> toMap() {\n Map<String, Object> m = new HashMap<>();\n m.put(\"service_code\", getServiceCode());\n return m;\n }\n\n public List<ServiceDefinitionAttribute> getSelectedValues() {\n return selectedValues;\n }\n\n public void setSelectedValues(List<ServiceDefinitionAttribute> selectedValues) {\n this.selectedValues = selectedValues;\n }\n}" }, { "identifier": "ServiceRepository", "path": "app/src/main/java/app/model/service/ServiceRepository.java", "snippet": "@Repository\npublic interface ServiceRepository extends PageableRepository<Service, Long> {\n Optional<Service> findByServiceCode(String serviceCode);\n\n Page<Service> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n\n Optional<Service> findByServiceCodeAndJurisdictionId(String serviceCode, String jurisdictionId);\n}" }, { "identifier": "ServiceRequestRepository", "path": "app/src/main/java/app/model/servicerequest/ServiceRequestRepository.java", "snippet": "@Repository\npublic interface ServiceRequestRepository extends PageableRepository<ServiceRequest, Long> {\n Page<ServiceRequest> findByIdIn(List<Long> serviceRequestIds, Pageable pageable);\n\n Page<ServiceRequest> findByServiceServiceCode(String serviceCode, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCode(String serviceCode);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedBetween(String serviceCode, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedBetween(String serviceCode, Instant start, Instant end);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedAfter(String serviceCode, Instant start, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedAfter(String serviceCode, Instant start);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedBefore(String serviceCode, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedBefore(String serviceCode, Instant end);\n\n Page<ServiceRequest> findByStatus(ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByStatus(ServiceRequestStatus status);\n Page<ServiceRequest> findByStatusAndDateCreatedBetween(ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedBetween(ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByStatusAndDateCreatedAfter(ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedAfter(ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByStatusAndDateCreatedBefore(ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedBefore(ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByServiceServiceCodeAndStatus(String serviceCode, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatus(String serviceCode, ServiceRequestStatus status);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBetween(String serviceCode, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBetween(String serviceCode, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedAfter(String serviceCode, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedAfter(String serviceCode, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBefore(String serviceCode, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBefore(String serviceCode, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByDateCreatedBetween(Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByDateCreatedBetween(Instant startDate, Instant endDate);\n Page<ServiceRequest> findByDateCreatedAfter(Instant start, Pageable pageable);\n List<ServiceRequest> findByDateCreatedAfter(Instant start);\n Page<ServiceRequest> findByDateCreatedBefore(Instant end, Pageable pageable);\n List<ServiceRequest> findByDateCreatedBefore(Instant end);\n\n Optional<ServiceRequest> findByServiceServiceNameIlike(String serviceName);\n\n // jurisdiction\n Optional<ServiceRequest> findByIdAndJurisdictionId(Long serviceRequestId, String jurisdictionId);\n Page<ServiceRequest> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n List<ServiceRequest> findAllByJurisdictionId(String jurisdictionId);\n\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCode(String jurisdictionId, String serviceCode, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCode(String jurisdictionId, String serviceCode);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(String jurisdictionId, String serviceCode, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(String jurisdictionId, String serviceCode, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(String jurisdictionId, String serviceCode, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(String jurisdictionId, String serviceCode, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(String jurisdictionId, String serviceCode, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(String jurisdictionId, String serviceCode, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndStatus(String jurisdictionId, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatus(String jurisdictionId, ServiceRequestStatus status);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBetween(String jurisdictionId, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBetween(String jurisdictionId, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedAfter(String jurisdictionId, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedAfter(String jurisdictionId, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBefore(String jurisdictionId, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBefore(String jurisdictionId, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatus(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatus(String jurisdictionId, String serviceCode, ServiceRequestStatus status);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedBetween(String jurisdictionId, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedBetween(String jurisdictionId, Instant startDate, Instant endDate);\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedAfter(String jurisdictionId, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedAfter(String jurisdictionId, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedBefore(String jurisdictionId, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedBefore(String jurisdictionId, Instant end);\n}" }, { "identifier": "DbCleanup", "path": "app/src/test/java/app/util/DbCleanup.java", "snippet": "@Singleton\npublic class DbCleanup {\n\n private final ServiceRequestRepository serviceRequestRepository;\n private final JurisdictionRepository jurisdictionRepository;\n\n public DbCleanup(ServiceRequestRepository serviceRequestRepository, JurisdictionRepository jurisdictionRepository) {\n this.serviceRequestRepository = serviceRequestRepository;\n this.jurisdictionRepository = jurisdictionRepository;\n }\n\n @Transactional\n public void cleanupServiceRequests() {\n serviceRequestRepository.deleteAll();\n }\n\n @Transactional\n public void cleanupJurisdictions() {\n jurisdictionRepository.deleteAll();\n }\n}" }, { "identifier": "MockAuthenticationFetcher", "path": "app/src/test/java/app/util/MockAuthenticationFetcher.java", "snippet": "@Replaces(AuthenticationFetcher.class)\n@Singleton\npublic class MockAuthenticationFetcher implements AuthenticationFetcher {\n\n\n private Authentication authentication;\n\n @Override\n public Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {\n return Publishers.just(this.authentication);\n }\n\n public void setAuthentication(Authentication authentication) {\n this.authentication = authentication;\n }\n}" }, { "identifier": "MockReCaptchaService", "path": "app/src/test/java/app/util/MockReCaptchaService.java", "snippet": "@Singleton\n@Replaces(ReCaptchaService.class)\npublic class MockReCaptchaService extends ReCaptchaService {\n\n public MockReCaptchaService() {}\n\n public Boolean verifyReCaptcha(String response) {\n return true;\n }\n}" }, { "identifier": "MockSecurityService", "path": "app/src/test/java/app/util/MockSecurityService.java", "snippet": "@Replaces(SecurityService.class)\n@Singleton\npublic class MockSecurityService implements SecurityService {\n\n private ServerAuthentication serverAuthentication;\n\n @PostConstruct\n public void postConstruct() {\n serverAuthentication = new ServerAuthentication(\"[email protected]\",\n null,\n null);\n }\n\n @Override\n public Optional<String> username() {\n return Optional.empty();\n }\n\n @Override\n public Optional<Authentication> getAuthentication() {\n return Optional.of(serverAuthentication);\n }\n\n @Override\n public boolean isAuthenticated() {\n return false;\n }\n\n @Override\n public boolean hasRole(String role) {\n return false;\n }\n\n public void setServerAuthentication(ServerAuthentication serverAuthentication) {\n this.serverAuthentication = serverAuthentication;\n }\n}" } ]
import app.dto.service.ServiceDTO; import app.dto.servicerequest.PostRequestServiceRequestDTO; import app.dto.servicerequest.PostResponseServiceRequestDTO; import app.dto.servicerequest.ServiceRequestDTO; import app.model.service.ServiceRepository; import app.model.servicerequest.ServiceRequestRepository; import app.util.DbCleanup; import app.util.MockAuthenticationFetcher; import app.util.MockReCaptchaService; import app.util.MockSecurityService; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.CSVReader; import com.opencsv.exceptions.CsvValidationException; import io.micronaut.core.util.StringUtils; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.HttpStatus; import io.micronaut.http.MediaType; import io.micronaut.http.client.HttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.exceptions.HttpClientResponseException; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; import java.util.Optional; import static io.micronaut.http.HttpStatus.INTERNAL_SERVER_ERROR; import static io.micronaut.http.HttpStatus.UNAUTHORIZED; import static org.junit.jupiter.api.Assertions.*;
6,715
// 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; @MicronautTest(environments={"test-jurisdiction-support"}) public class JurisdictionSupportRootControllerTest { @Inject @Client("/api") HttpClient client; @Inject MockReCaptchaService mockReCaptchaService; @Inject
// 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; @MicronautTest(environments={"test-jurisdiction-support"}) public class JurisdictionSupportRootControllerTest { @Inject @Client("/api") HttpClient client; @Inject MockReCaptchaService mockReCaptchaService; @Inject
ServiceRepository serviceRepository;
4
2023-10-18 15:37:36+00:00
8k
JonnyOnlineYT/xenza
src/minecraft/com/mojang/authlib/yggdrasil/YggdrasilAuthenticationService.java
[ { "identifier": "Agent", "path": "src/minecraft/com/mojang/authlib/Agent.java", "snippet": "public class Agent {\n public static final Agent MINECRAFT = new Agent(\"Minecraft\", 1);\n public static final Agent SCROLLS = new Agent(\"Scrolls\", 1);\n private final String name;\n private final int version;\n\n public Agent(String name, int version) {\n this.name = name;\n this.version = version;\n }\n\n public String getName() {\n return this.name;\n }\n\n public int getVersion() {\n return this.version;\n }\n\n @Override\n public String toString() {\n return \"Agent{name='\" + this.name + '\\'' + \", version=\" + this.version + '}';\n }\n}" }, { "identifier": "GameProfile", "path": "src/minecraft/com/mojang/authlib/GameProfile.java", "snippet": "public class GameProfile {\n private final UUID id;\n private final String name;\n private final PropertyMap properties = new PropertyMap();\n private boolean legacy;\n\n public GameProfile(UUID id, String name) {\n if (id == null && StringUtils.isBlank(name)) {\n throw new IllegalArgumentException(\"Name and ID cannot both be blank\");\n } else {\n this.id = id;\n this.name = name;\n }\n }\n\n public UUID getId() {\n return this.id;\n }\n\n public String getName() {\n return this.name;\n }\n\n public PropertyMap getProperties() {\n return this.properties;\n }\n\n public boolean isComplete() {\n return this.id != null && StringUtils.isNotBlank(this.getName());\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n } else if (o != null && this.getClass() == o.getClass()) {\n GameProfile that = (GameProfile)o;\n if (this.id != null ? this.id.equals(that.id) : that.id == null) {\n return this.name != null ? this.name.equals(that.name) : that.name == null;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }\n\n @Override\n public int hashCode() {\n int result = this.id != null ? this.id.hashCode() : 0;\n return 31 * result + (this.name != null ? this.name.hashCode() : 0);\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"id\", this.id)\n .append(\"name\", this.name)\n .append(\"properties\", this.properties)\n .append(\"legacy\", this.legacy)\n .toString();\n }\n\n public boolean isLegacy() {\n return this.legacy;\n }\n}" }, { "identifier": "GameProfileRepository", "path": "src/minecraft/com/mojang/authlib/GameProfileRepository.java", "snippet": "public interface GameProfileRepository {\n void findProfilesByNames(String[] var1, Agent var2, ProfileLookupCallback var3);\n}" }, { "identifier": "HttpAuthenticationService", "path": "src/minecraft/com/mojang/authlib/HttpAuthenticationService.java", "snippet": "public abstract class HttpAuthenticationService extends BaseAuthenticationService {\n private static final Logger LOGGER = new Logger();\n private final Proxy proxy;\n\n protected HttpAuthenticationService(Proxy proxy) {\n Validate.notNull(proxy);\n this.proxy = proxy;\n }\n\n public Proxy getProxy() {\n return this.proxy;\n }\n\n protected HttpURLConnection createUrlConnection(URL url) throws IOException {\n Validate.notNull(url);\n LOGGER.debug(\"Opening connection to \" + url);\n HttpURLConnection connection = (HttpURLConnection)url.openConnection(this.proxy);\n connection.setConnectTimeout(15000);\n connection.setReadTimeout(15000);\n connection.setUseCaches(false);\n return connection;\n }\n\n public String performPostRequest(URL url, String post, String contentType) throws IOException {\n Validate.notNull(url);\n Validate.notNull(post);\n Validate.notNull(contentType);\n HttpURLConnection connection = this.createUrlConnection(url);\n byte[] postAsBytes = post.getBytes(Charsets.UTF_8);\n connection.setRequestProperty(\"Content-Type\", contentType + \"; charset=utf-8\");\n connection.setRequestProperty(\"Content-Length\", \"\" + postAsBytes.length);\n connection.setDoOutput(true);\n LOGGER.debug(\"Writing POST data to \" + url + \": \" + post);\n OutputStream outputStream = null;\n\n try {\n outputStream = connection.getOutputStream();\n IOUtils.write(postAsBytes, outputStream);\n } finally {\n IOUtils.closeQuietly(outputStream);\n }\n\n LOGGER.debug(\"Reading data from \" + url);\n InputStream inputStream = null;\n\n String var10;\n try {\n inputStream = connection.getInputStream();\n String result = IOUtils.toString(inputStream, Charsets.UTF_8);\n LOGGER.debug(\"Successful read, server response was \" + connection.getResponseCode());\n LOGGER.debug(\"Response: \" + result);\n return result;\n } catch (IOException var19) {\n IOUtils.closeQuietly(inputStream);\n inputStream = connection.getErrorStream();\n if (inputStream == null) {\n LOGGER.debug(\"Request failed\", var19);\n throw var19;\n }\n\n LOGGER.debug(\"Reading error page from \" + url);\n String resultx = IOUtils.toString(inputStream, Charsets.UTF_8);\n LOGGER.debug(\"Successful read, server response was \" + connection.getResponseCode());\n LOGGER.debug(\"Response: \" + resultx);\n var10 = resultx;\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n\n return var10;\n }\n\n public String performGetRequest(URL url) throws IOException {\n Validate.notNull(url);\n HttpURLConnection connection = this.createUrlConnection(url);\n LOGGER.debug(\"Reading data from \" + url);\n InputStream inputStream = null;\n\n String var6;\n try {\n inputStream = connection.getInputStream();\n String result = IOUtils.toString(inputStream, Charsets.UTF_8);\n LOGGER.debug(\"Successful read, server response was \" + connection.getResponseCode());\n LOGGER.debug(\"Response: \" + result);\n return result;\n } catch (IOException var10) {\n IOUtils.closeQuietly(inputStream);\n inputStream = connection.getErrorStream();\n if (inputStream == null) {\n LOGGER.debug(\"Request failed\", var10);\n throw var10;\n }\n\n LOGGER.debug(\"Reading error page from \" + url);\n String resultx = IOUtils.toString(inputStream, Charsets.UTF_8);\n LOGGER.debug(\"Successful read, server response was \" + connection.getResponseCode());\n LOGGER.debug(\"Response: \" + resultx);\n var6 = resultx;\n } finally {\n IOUtils.closeQuietly(inputStream);\n }\n\n return var6;\n }\n\n public static URL constantURL(String url) {\n try {\n return new URL(url);\n } catch (MalformedURLException var2) {\n throw new Error(\"Couldn't create constant for \" + url, var2);\n }\n }\n\n public static String buildQuery(Map<String, Object> query) {\n if (query == null) {\n return \"\";\n } else {\n StringBuilder builder = new StringBuilder();\n\n for(Entry<String, Object> entry : query.entrySet()) {\n if (builder.length() > 0) {\n builder.append('&');\n }\n\n try {\n builder.append(URLEncoder.encode(entry.getKey(), \"UTF-8\"));\n } catch (UnsupportedEncodingException var6) {\n LOGGER.error(\"Unexpected exception building query\", var6);\n }\n\n if (entry.getValue() != null) {\n builder.append('=');\n\n try {\n builder.append(URLEncoder.encode(entry.getValue().toString(), \"UTF-8\"));\n } catch (UnsupportedEncodingException var5) {\n LOGGER.error(\"Unexpected exception building query\", var5);\n }\n }\n }\n\n return builder.toString();\n }\n }\n\n public static URL concatenateURL(URL url, String query) {\n try {\n return url.getQuery() != null && url.getQuery().length() > 0\n ? new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + \"&\" + query)\n : new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + \"?\" + query);\n } catch (MalformedURLException var3) {\n throw new IllegalArgumentException(\"Could not concatenate given URL with GET arguments!\", var3);\n }\n }\n}" }, { "identifier": "UserAuthentication", "path": "src/minecraft/com/mojang/authlib/UserAuthentication.java", "snippet": "public interface UserAuthentication {\n boolean canLogIn();\n\n void logIn() throws AuthenticationException;\n\n void logOut();\n\n boolean isLoggedIn();\n\n boolean canPlayOnline();\n\n GameProfile[] getAvailableProfiles();\n\n GameProfile getSelectedProfile();\n\n void selectGameProfile(GameProfile var1) throws AuthenticationException;\n\n void loadFromStorage(Map<String, Object> var1);\n\n Map<String, Object> saveForStorage();\n\n void setUsername(String var1);\n\n void setPassword(String var1);\n\n String getAuthenticatedToken();\n\n String getUserID();\n\n PropertyMap getUserProperties();\n\n UserType getUserType();\n}" }, { "identifier": "AuthenticationException", "path": "src/minecraft/com/mojang/authlib/exceptions/AuthenticationException.java", "snippet": "public class AuthenticationException extends Exception {\n public AuthenticationException() {\n }\n\n public AuthenticationException(String message) {\n super(message);\n }\n\n public AuthenticationException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public AuthenticationException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "AuthenticationUnavailableException", "path": "src/minecraft/com/mojang/authlib/exceptions/AuthenticationUnavailableException.java", "snippet": "public class AuthenticationUnavailableException extends AuthenticationException {\n public AuthenticationUnavailableException() {\n }\n\n public AuthenticationUnavailableException(String message) {\n super(message);\n }\n\n public AuthenticationUnavailableException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public AuthenticationUnavailableException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "InvalidCredentialsException", "path": "src/minecraft/com/mojang/authlib/exceptions/InvalidCredentialsException.java", "snippet": "public class InvalidCredentialsException extends AuthenticationException {\n public InvalidCredentialsException() {\n }\n\n public InvalidCredentialsException(String message) {\n super(message);\n }\n\n public InvalidCredentialsException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public InvalidCredentialsException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "UserMigratedException", "path": "src/minecraft/com/mojang/authlib/exceptions/UserMigratedException.java", "snippet": "public class UserMigratedException extends InvalidCredentialsException {\n public UserMigratedException() {\n }\n\n public UserMigratedException(String message) {\n super(message);\n }\n\n public UserMigratedException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public UserMigratedException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "MinecraftSessionService", "path": "src/minecraft/com/mojang/authlib/minecraft/MinecraftSessionService.java", "snippet": "public interface MinecraftSessionService {\n void joinServer(GameProfile var1, String var2, String var3) throws AuthenticationException;\n\n GameProfile hasJoinedServer(GameProfile var1, String var2) throws AuthenticationUnavailableException;\n\n Map<MinecraftProfileTexture.Type, MinecraftProfileTexture> getTextures(GameProfile var1, boolean var2);\n\n GameProfile fillProfileProperties(GameProfile var1, boolean var2);\n}" }, { "identifier": "PropertyMap", "path": "src/minecraft/com/mojang/authlib/properties/PropertyMap.java", "snippet": "public class PropertyMap extends ForwardingMultimap<String, Property> {\n private final Multimap<String, Property> properties = LinkedHashMultimap.create();\n\n protected Multimap<String, Property> delegate() {\n return this.properties;\n }\n\n public static class Serializer implements JsonSerializer<PropertyMap>, JsonDeserializer<PropertyMap> {\n public PropertyMap deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n PropertyMap result = new PropertyMap();\n if (json instanceof JsonObject) {\n JsonObject object = (JsonObject)json;\n\n for(Entry<String, JsonElement> entry : object.entrySet()) {\n if (entry.getValue() instanceof JsonArray) {\n for(JsonElement element : (JsonArray)entry.getValue()) {\n result.put(entry.getKey(), new Property(entry.getKey(), element.getAsString()));\n }\n }\n }\n } else if (json instanceof JsonArray) {\n for(JsonElement element : (JsonArray)json) {\n if (element instanceof JsonObject) {\n JsonObject object = (JsonObject)element;\n String name = object.getAsJsonPrimitive(\"name\").getAsString();\n String value = object.getAsJsonPrimitive(\"value\").getAsString();\n if (object.has(\"signature\")) {\n result.put(name, new Property(name, value, object.getAsJsonPrimitive(\"signature\").getAsString()));\n } else {\n result.put(name, new Property(name, value));\n }\n }\n }\n }\n\n return result;\n }\n\n public JsonElement serialize(PropertyMap src, Type typeOfSrc, JsonSerializationContext context) {\n JsonArray result = new JsonArray();\n\n for(Property property : src.values()) {\n JsonObject object = new JsonObject();\n object.addProperty(\"name\", property.getName());\n object.addProperty(\"value\", property.getValue());\n if (property.hasSignature()) {\n object.addProperty(\"signature\", property.getSignature());\n }\n\n result.add(object);\n }\n\n return result;\n }\n }\n}" }, { "identifier": "ProfileSearchResultsResponse", "path": "src/minecraft/com/mojang/authlib/yggdrasil/response/ProfileSearchResultsResponse.java", "snippet": "public class ProfileSearchResultsResponse extends Response {\n private GameProfile[] profiles;\n\n public GameProfile[] getProfiles() {\n return this.profiles;\n }\n\n public static class Serializer implements JsonDeserializer<ProfileSearchResultsResponse> {\n public ProfileSearchResultsResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n ProfileSearchResultsResponse result = new ProfileSearchResultsResponse();\n if (json instanceof JsonObject) {\n JsonObject object = (JsonObject)json;\n if (object.has(\"error\")) {\n result.setError(object.getAsJsonPrimitive(\"error\").getAsString());\n }\n\n if (object.has(\"errorMessage\")) {\n result.setError(object.getAsJsonPrimitive(\"errorMessage\").getAsString());\n }\n\n if (object.has(\"cause\")) {\n result.setError(object.getAsJsonPrimitive(\"cause\").getAsString());\n }\n } else {\n result.profiles = (GameProfile[])context.deserialize(json, GameProfile[].class);\n }\n\n return result;\n }\n }\n}" }, { "identifier": "Response", "path": "src/minecraft/com/mojang/authlib/yggdrasil/response/Response.java", "snippet": "public class Response {\n private String error;\n private String errorMessage;\n private String cause;\n\n public String getError() {\n return this.error;\n }\n\n public String getCause() {\n return this.cause;\n }\n\n public String getErrorMessage() {\n return this.errorMessage;\n }\n\n protected void setError(String error) {\n this.error = error;\n }\n\n protected void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n protected void setCause(String cause) {\n this.cause = cause;\n }\n}" }, { "identifier": "UUIDTypeAdapter", "path": "src/minecraft/com/mojang/util/UUIDTypeAdapter.java", "snippet": "public class UUIDTypeAdapter extends TypeAdapter<UUID> {\n public void write(JsonWriter out, UUID value) throws IOException {\n out.value(fromUUID(value));\n }\n\n public UUID read(JsonReader in) throws IOException {\n return fromString(in.nextString());\n }\n\n public static String fromUUID(UUID value) {\n return value.toString().replace(\"-\", \"\");\n }\n\n public static UUID fromString(String input) {\n return UUID.fromString(input.replaceFirst(\"(\\\\w{8})(\\\\w{4})(\\\\w{4})(\\\\w{4})(\\\\w{12})\", \"$1-$2-$3-$4-$5\"));\n }\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.mojang.authlib.Agent; import com.mojang.authlib.GameProfile; import com.mojang.authlib.GameProfileRepository; import com.mojang.authlib.HttpAuthenticationService; import com.mojang.authlib.UserAuthentication; import com.mojang.authlib.exceptions.AuthenticationException; import com.mojang.authlib.exceptions.AuthenticationUnavailableException; import com.mojang.authlib.exceptions.InvalidCredentialsException; import com.mojang.authlib.exceptions.UserMigratedException; import com.mojang.authlib.minecraft.MinecraftSessionService; import com.mojang.authlib.properties.PropertyMap; import com.mojang.authlib.yggdrasil.response.ProfileSearchResultsResponse; import com.mojang.authlib.yggdrasil.response.Response; import com.mojang.util.UUIDTypeAdapter; import java.io.IOException; import java.lang.reflect.Type; import java.net.Proxy; import java.net.URL; import java.util.UUID; import org.apache.commons.lang3.StringUtils;
4,323
package com.mojang.authlib.yggdrasil; public class YggdrasilAuthenticationService extends HttpAuthenticationService { private final String clientToken; private final Gson gson; public YggdrasilAuthenticationService(Proxy proxy, String clientToken) { super(proxy); this.clientToken = clientToken; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(GameProfile.class, new YggdrasilAuthenticationService.GameProfileSerializer()); builder.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()); builder.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()); builder.registerTypeAdapter(ProfileSearchResultsResponse.class, new ProfileSearchResultsResponse.Serializer()); this.gson = builder.create(); } @Override public UserAuthentication createUserAuthentication(Agent agent) { return new YggdrasilUserAuthentication(this, agent); } @Override public MinecraftSessionService createMinecraftSessionService() { return new YggdrasilMinecraftSessionService(this); } @Override
package com.mojang.authlib.yggdrasil; public class YggdrasilAuthenticationService extends HttpAuthenticationService { private final String clientToken; private final Gson gson; public YggdrasilAuthenticationService(Proxy proxy, String clientToken) { super(proxy); this.clientToken = clientToken; GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(GameProfile.class, new YggdrasilAuthenticationService.GameProfileSerializer()); builder.registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()); builder.registerTypeAdapter(UUID.class, new UUIDTypeAdapter()); builder.registerTypeAdapter(ProfileSearchResultsResponse.class, new ProfileSearchResultsResponse.Serializer()); this.gson = builder.create(); } @Override public UserAuthentication createUserAuthentication(Agent agent) { return new YggdrasilUserAuthentication(this, agent); } @Override public MinecraftSessionService createMinecraftSessionService() { return new YggdrasilMinecraftSessionService(this); } @Override
public GameProfileRepository createProfileRepository() {
2
2023-10-15 00:21:15+00:00
8k
Radekyspec/TasksMaster
src/main/java/app/schedule/add_new_event/AddNewEventUseCaseFactory.java
[ { "identifier": "ScheduleDataAccessInterface", "path": "src/main/java/data_access/schedule/ScheduleDataAccessInterface.java", "snippet": "public interface ScheduleDataAccessInterface {\n List<Event> getEvents(long projectId, long scheduleid);\n\n Event addEvents(long projectId, long scheduleId, String eventName, String notes, Date startAt, Date endAt, boolean isAllDay, List<String> userWith);\n}" }, { "identifier": "ViewManagerModel", "path": "src/main/java/interface_adapter/ViewManagerModel.java", "snippet": "public class ViewManagerModel {\n private final PropertyChangeSupport support = new PropertyChangeSupport(this);\n private String activeViewName;\n\n public String getActiveView() {\n return activeViewName;\n }\n\n public void setActiveView(String activeView) {\n this.activeViewName = activeView;\n }\n\n public void firePropertyChanged() {\n support.firePropertyChange(\"view\", null, this.activeViewName);\n }\n\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n support.addPropertyChangeListener(listener);\n }\n}" }, { "identifier": "ScheduleViewModel", "path": "src/main/java/interface_adapter/schedule/ScheduleViewModel.java", "snippet": "public class ScheduleViewModel extends ViewModel {\n public static final String SCHEDULE_TITLE_LABEL = \"Project Schedule\";\n public static final String SCHEDULE_ADD_NEW_EVENT = \"Add new event\";\n public static final String SCHEDULE_SET_EVENT = \"Set event\";\n public static final String SCHEDULE_NO_EVENT = \"There is no event now\";\n\n private final ScheduleState scheduleState = new ScheduleState();\n\n private final PropertyChangeSupport support = new PropertyChangeSupport(this);\n\n public ScheduleViewModel() {\n super(\"Schedule\");\n }\n\n @Override\n public void firePropertyChanged() {\n support.firePropertyChange(\"new event\", null, scheduleState);\n }\n\n public void firePropertyChanged(String scheduleSetEvent) {\n support.firePropertyChange(scheduleSetEvent, null, scheduleState);\n }\n\n @Override\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n support.addPropertyChangeListener(listener);\n }\n\n public ScheduleState getScheduleState() {\n return scheduleState;\n }\n\n public void setProjectID(long projectID) {\n scheduleState.setProjectId(projectID);\n }\n}" }, { "identifier": "AddEventController", "path": "src/main/java/interface_adapter/schedule/event/AddEventController.java", "snippet": "public class AddEventController {\n final AddNewEventInputBoundary addNewEventInteractor;\n\n public AddEventController(AddNewEventInputBoundary addNewEventInteractor) {\n this.addNewEventInteractor = addNewEventInteractor;\n }\n\n public void postEvent(long projectId, long scheduleId, String eventName, String notes, Date startAt, Date endAt, boolean isAllDay, List<String> userwith) {\n AddNewEventInputData addNewEventInputData = new AddNewEventInputData(projectId, scheduleId, eventName, notes, startAt, endAt, isAllDay, userwith);\n addNewEventInteractor.postEvent(addNewEventInputData);\n }\n}" }, { "identifier": "AddEventPresenter", "path": "src/main/java/interface_adapter/schedule/event/AddEventPresenter.java", "snippet": "public class AddEventPresenter implements AddNewEventOutputBoundary {\n private final ViewManagerModel viewManagerModel;\n private final ScheduleViewModel scheduleViewModel;\n\n public AddEventPresenter(ViewManagerModel viewManagerModel, ScheduleViewModel scheduleViewModel) {\n this.viewManagerModel = viewManagerModel;\n this.scheduleViewModel = scheduleViewModel;\n }\n\n @Override\n public void prepareSuccessView(AddNewEventOutputData addNewEventOutputData) {\n scheduleViewModel.getScheduleState().setEvent(addNewEventOutputData.getEvent());\n scheduleViewModel.firePropertyChanged(ScheduleViewModel.SCHEDULE_ADD_NEW_EVENT);\n viewManagerModel.setActiveView(scheduleViewModel.getViewName());\n viewManagerModel.firePropertyChanged();\n }\n\n @Override\n public void prepareFailView() {\n JOptionPane.showMessageDialog(null, AddEventViewModel.EVENT_POST_FAIL);\n }\n}" }, { "identifier": "AddEventViewModel", "path": "src/main/java/interface_adapter/schedule/event/AddEventViewModel.java", "snippet": "public class AddEventViewModel extends ViewModel {\n public static final String EVENT_NAME = \"Event Title\";\n public static final String EVENT_NOTES = \"Event Notes\";\n public static final String EVENT_STARTDATE = \"Start at (dd-MM-yyyy)\";\n public static final String EVENT_ENDDATE = \"End at (dd-MM-yyyy)\";\n public static final String EVENT_ISALLDAY = \"Is all day? Type 'Y' or 'N'\";\n public static final String EVENT_USERWITH = \"User with? Separate user by using ',' (No space) \";\n public static final String EVENT_POST = \"Post this event\";\n public static final String EVENT_POST_FAIL = \"Fail to post this event\";\n\n private final AddEventState addEventState = new AddEventState();\n private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);\n\n public AddEventViewModel() {\n super(\"Add a new event\");\n }\n\n public void setProjectId(long projectId) {\n addEventState.setProjectId(projectId);\n }\n\n public void setScheduleId(long scheduleId) {\n addEventState.setScheduleId(scheduleId);\n }\n\n public void setEventName(String eventName) {\n addEventState.setEventName(eventName);\n }\n\n public void setNotes(String notes) {\n addEventState.setNotes(notes);\n }\n\n public void setStartAt(Date startAt) {\n addEventState.setStartAt(startAt);\n }\n\n public void setEndAt(Date endAt) {\n addEventState.setEndAt(endAt);\n }\n\n public void setIsAllDay(boolean isAllDay) {\n addEventState.setAllDay(isAllDay);\n }\n\n public void setUserWith(List<String> userWith) {\n addEventState.setUserwith(userWith);\n }\n\n public AddEventState getAddEventState() {\n return addEventState;\n }\n\n @Override\n public void firePropertyChanged() {\n\n }\n\n @Override\n public void addPropertyChangeListener(PropertyChangeListener listener) {\n\n }\n}" }, { "identifier": "AddNewEventInputBoundary", "path": "src/main/java/use_case/schedule/add_new_event/AddNewEventInputBoundary.java", "snippet": "public interface AddNewEventInputBoundary {\n void postEvent(AddNewEventInputData addNewEventInputData);\n}" }, { "identifier": "AddNewEventInteractor", "path": "src/main/java/use_case/schedule/add_new_event/AddNewEventInteractor.java", "snippet": "public class AddNewEventInteractor implements AddNewEventInputBoundary {\n final ScheduleDataAccessInterface scheduleDataAccessInterface;\n final AddNewEventOutputBoundary addNewEventPrensenter;\n\n public AddNewEventInteractor(ScheduleDataAccessInterface scheduleDataAccessInterface, AddNewEventOutputBoundary addNewEventPrensenter) {\n this.scheduleDataAccessInterface = scheduleDataAccessInterface;\n this.addNewEventPrensenter = addNewEventPrensenter;\n }\n\n @Override\n public void postEvent(AddNewEventInputData addNewEventInputData) {\n long projectId = addNewEventInputData.getProjectId();\n long scheduleId = addNewEventInputData.getScheduleId();\n String eventName = addNewEventInputData.getEventname();\n String notes = addNewEventInputData.getNotes();\n Date startAt = addNewEventInputData.getStartAt();\n Date endAt = addNewEventInputData.getEndAt();\n boolean isAllDay = addNewEventInputData.getIsAllDay();\n List<String> userWith = addNewEventInputData.getUserWith();\n\n Event event = scheduleDataAccessInterface.addEvents(projectId, scheduleId, eventName, notes, startAt, endAt, isAllDay, userWith);\n if (event == null) {\n addNewEventPrensenter.prepareFailView();\n } else {\n AddNewEventOutputData addNewEventOutputData = new AddNewEventOutputData(event);\n addNewEventPrensenter.prepareSuccessView(addNewEventOutputData);\n }\n\n }\n}" }, { "identifier": "AddNewEventOutputBoundary", "path": "src/main/java/use_case/schedule/add_new_event/AddNewEventOutputBoundary.java", "snippet": "public interface AddNewEventOutputBoundary {\n public void prepareSuccessView(AddNewEventOutputData addNewEventOutputData);\n\n public void prepareFailView();\n}" }, { "identifier": "AddNewEventView", "path": "src/main/java/view/schedule/AddNewEventView.java", "snippet": "public class AddNewEventView extends JPanel implements ActionListener, PropertyChangeListener {\n private final ViewManagerModel viewManagerModel;\n private final AddEventViewModel addEventViewModel;\n private final AddEventController addEventController;\n private final ScheduleViewModel scheduleViewModel;\n private final JPanel eventNameInfo = new JPanel();\n private final JPanel eventNoteInfo = new JPanel();\n private final JPanel eventStartInfo = new JPanel();\n private final JPanel eventEndInfo = new JPanel();\n private final JPanel eventAllDayInfo = new JPanel();\n private final JPanel eventUserWithInfo = new JPanel();\n private final JTextField eventNameInputField = new JTextField(30);\n private final JTextField eventNoteInputField = new JTextField(30);\n private final JTextField eventStartInputField = new JTextField(30);\n private final JTextField eventEndInputField = new JTextField(30);\n private final JTextField eventAllDayInputField = new JTextField(30);\n private final JTextField eventUserWithInputField = new JTextField(30);\n private final JButton postButton;\n\n public AddNewEventView(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, AddEventController addEventController) {\n this.viewManagerModel = viewManagerModel;\n this.addEventViewModel = addEventViewModel;\n this.addEventController = addEventController;\n this.scheduleViewModel = scheduleViewModel;\n addEventViewModel.addPropertyChangeListener(this);\n\n eventNameInputField.setFont(new Font(\"Times New Roman\", Font.PLAIN, 26));\n eventNoteInputField.setFont(new Font(\"Times New Roman\", Font.PLAIN, 26));\n ;\n eventStartInputField.setFont(new Font(\"Times New Roman\", Font.PLAIN, 26));\n eventEndInputField.setFont(new Font(\"Times New Roman\", Font.PLAIN, 26));\n eventAllDayInputField.setFont(new Font(\"Times New Roman\", Font.PLAIN, 26));\n// eventUserWithInputField.setFont(new Font(\"Times New Roman\", Font.PLAIN, 26));\n\n eventNameInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_NAME));\n eventNameInfo.add(eventNameInputField);\n eventNoteInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_NOTES));\n eventNoteInfo.add(eventNoteInputField);\n eventStartInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_STARTDATE));\n eventStartInfo.add(eventStartInputField);\n eventEndInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_ENDDATE));\n eventEndInfo.add(eventEndInputField);\n eventAllDayInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_ISALLDAY));\n eventAllDayInfo.add(eventAllDayInputField);\n// eventUserWithInfo.add(new JLabelWithFont(AddEventViewModel.EVENT_USERWITH));\n// eventUserWithInfo.add(eventUserWithInputField);\n\n eventNameInputField.addKeyListener(\n new KeyListener() {\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n addEventViewModel.getAddEventState().setEventName(eventNameInputField.getText());\n }\n }\n );\n\n eventNoteInputField.addKeyListener(\n new KeyListener() {\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n addEventViewModel.getAddEventState().setNotes(eventNoteInputField.getText());\n }\n }\n );\n\n final String[] stringStartAt = new String[1];\n eventStartInputField.addKeyListener(\n new KeyListener() {\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n stringStartAt[0] = eventStartInputField.getText();\n }\n }\n );\n\n final String[] stringEndAt = new String[1];\n eventEndInputField.addKeyListener(\n new KeyListener() {\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n stringEndAt[0] = eventEndInputField.getText();\n }\n }\n );\n\n eventAllDayInputField.addKeyListener(\n new KeyListener() {\n @Override\n public void keyTyped(KeyEvent e) {\n\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n boolean allDay;\n if (Objects.equals(eventAllDayInputField.getText(), \"Y\")) {\n allDay = true;\n } else {\n allDay = false;\n }\n addEventViewModel.getAddEventState().setAllDay(allDay);\n }\n }\n );\n\n// eventUserWithInputField.addKeyListener(\n// new KeyListener() {\n// @Override\n// public void keyTyped(KeyEvent e) {\n//\n// }\n//\n// @Override\n// public void keyPressed(KeyEvent e) {\n//\n// }\n//\n// @Override\n// public void keyReleased(KeyEvent e) {\n// List<String> userWith = new ArrayList<String>(Arrays.asList(eventUserWithInputField.getText().split(\",\")));\n// addEventViewModel.getAddEventState().setUserwith(userWith);\n// }\n// }\n// );\n\n postButton = new JButtonWithFont(AddEventViewModel.EVENT_POST);\n postButton.addActionListener(\n e -> {\n if (!e.getSource().equals(postButton)) {\n return;\n }\n SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\", Locale.ENGLISH);\n Date start = null;\n try {\n start = formatter.parse(stringStartAt[0]);\n } catch (ParseException ex) {\n throw new RuntimeException(ex);\n }\n addEventViewModel.getAddEventState().setStartAt(start);\n\n Date end = null;\n try {\n end = formatter.parse(stringEndAt[0]);\n } catch (ParseException ex) {\n throw new RuntimeException(ex);\n }\n addEventViewModel.getAddEventState().setEndAt(end);\n\n AddEventState state = addEventViewModel.getAddEventState();\n addEventController.postEvent(state.getProjectId(), state.getScheduleId(), state.getEventName(), state.getNotes(), state.getStartAt(), state.getEndAt(), state.isAllDay(), state.getUserwith());\n }\n );\n\n JButton back = new JButtonWithFont(\"Back\");\n back.addActionListener(\n e -> {\n viewManagerModel.setActiveView(scheduleViewModel.getViewName());\n viewManagerModel.firePropertyChanged();\n }\n );\n\n this.add(new JLabelWithFont(\"Add a new event\"));\n this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));\n this.add(eventNameInfo);\n eventNameInfo.setAlignmentX(CENTER_ALIGNMENT);\n this.add(eventNoteInfo);\n eventNoteInfo.setAlignmentX(CENTER_ALIGNMENT);\n this.add(eventStartInfo);\n eventStartInfo.setAlignmentX(CENTER_ALIGNMENT);\n this.add(eventEndInfo);\n eventEndInfo.setAlignmentX(CENTER_ALIGNMENT);\n this.add(eventAllDayInfo);\n eventAllDayInfo.setAlignmentX(CENTER_ALIGNMENT);\n// this.add(eventUserWithInfo);\n// eventUserWithInfo.setAlignmentX(CENTER_ALIGNMENT);\n JPanel bottom = new JPanel();\n bottom.add(postButton);\n bottom.add(back);\n this.add(bottom);\n }\n\n @Override\n public void actionPerformed(ActionEvent e) {\n }\n\n @Override\n public void propertyChange(PropertyChangeEvent evt) {\n }\n\n public String getViewName() {\n return addEventViewModel.getViewName();\n }\n}" } ]
import data_access.schedule.ScheduleDataAccessInterface; import interface_adapter.ViewManagerModel; import interface_adapter.schedule.ScheduleViewModel; import interface_adapter.schedule.event.AddEventController; import interface_adapter.schedule.event.AddEventPresenter; import interface_adapter.schedule.event.AddEventViewModel; import use_case.schedule.add_new_event.AddNewEventInputBoundary; import use_case.schedule.add_new_event.AddNewEventInteractor; import use_case.schedule.add_new_event.AddNewEventOutputBoundary; import view.schedule.AddNewEventView;
4,024
package app.schedule.add_new_event; public class AddNewEventUseCaseFactory { private AddNewEventUseCaseFactory() { } public static AddNewEventView create(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, ScheduleDataAccessInterface scheduleDataAccessInterface) { return new AddNewEventView(viewManagerModel, addEventViewModel, scheduleViewModel, AddNewEventUseCaseFactory.createContorller(viewManagerModel, scheduleViewModel, scheduleDataAccessInterface)); }
package app.schedule.add_new_event; public class AddNewEventUseCaseFactory { private AddNewEventUseCaseFactory() { } public static AddNewEventView create(ViewManagerModel viewManagerModel, AddEventViewModel addEventViewModel, ScheduleViewModel scheduleViewModel, ScheduleDataAccessInterface scheduleDataAccessInterface) { return new AddNewEventView(viewManagerModel, addEventViewModel, scheduleViewModel, AddNewEventUseCaseFactory.createContorller(viewManagerModel, scheduleViewModel, scheduleDataAccessInterface)); }
public static AddEventController createContorller(ViewManagerModel viewManagerModel, ScheduleViewModel scheduleViewModel, ScheduleDataAccessInterface scheduleDataAccessInterface) {
3
2023-10-23 15:17:21+00:00
8k
denis-vp/toy-language-interpreter
src/main/java/view/cli/CliInterpreter.java
[ { "identifier": "Controller", "path": "src/main/java/controller/Controller.java", "snippet": "public class Controller {\n private final IRepository repository;\n private Boolean logOutput;\n private final ExecutorService executor = Executors.newFixedThreadPool(8);\n\n public Controller(IRepository repository, Boolean logOutput) {\n this.repository = repository;\n this.logOutput = logOutput;\n this.skipInitialCompoundStatementUnpacking();\n }\n\n public IRepository getRepository() {\n return this.repository;\n }\n\n public ExecutorService getExecutor() {\n return this.executor;\n }\n\n private void skipInitialCompoundStatementUnpacking() {\n boolean aux = logOutput;\n logOutput = false;\n\n List<ProgramState> programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n\n while (!programStates.isEmpty()) {\n IStack<Statement> executionStack = programStates.get(0).getExecutionStack();\n try {\n if (!(executionStack.top() instanceof CompoundStatement)) {\n break;\n }\n } catch (ADTException e) {\n throw new RuntimeException(e);\n }\n\n this.repository.getHeap().setContent(\n this.garbageCollector(\n this.getAddressesFromSymbolTable(this.repository.getSymbolTable().values()),\n this.repository.getHeap().getContent()\n ));\n\n try {\n this.oneStepForAllPrograms(programStates);\n } catch (RuntimeException | ControllerException e) {\n throw new RuntimeException(e);\n }\n\n programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n }\n\n this.repository.setProgramStateList(programStates);\n\n logOutput = aux;\n }\n\n public void oneStepForAllPrograms(List<ProgramState> programStates) throws ControllerException {\n List<Callable<ProgramState>> callList = programStates.stream()\n .map((ProgramState programState) -> (Callable<ProgramState>) programState::oneStep)\n .toList();\n\n try {\n List<ProgramState> newProgramStates = this.executor.invokeAll(callList).stream()\n .map(future -> {\n try {\n return future.get();\n } catch (InterruptedException | ExecutionException e) {\n throw new RuntimeException(e);\n }\n })\n .filter(Objects::nonNull)\n .toList();\n programStates.addAll(newProgramStates);\n } catch (InterruptedException e) {\n throw new ControllerException(e.getMessage());\n }\n\n if (this.logOutput) {\n programStates.forEach(programState -> {\n try {\n this.repository.logProgramStateExecution(programState);\n } catch (RepositoryException e) {\n throw new RuntimeException(e);\n }\n });\n }\n\n this.repository.setProgramStateList(programStates);\n }\n\n public void allSteps() throws ControllerException {\n List<ProgramState> programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n if (this.logOutput) {\n programStates.forEach(programState -> {\n try {\n this.repository.logProgramStateExecution(programState);\n } catch (RepositoryException e) {\n throw new RuntimeException(e);\n }\n });\n }\n\n while (!programStates.isEmpty()) {\n this.repository.getHeap().setContent(\n this.garbageCollector(\n this.getAddressesFromSymbolTable(this.repository.getSymbolTable().values()),\n this.repository.getHeap().getContent()\n ));\n\n try {\n this.oneStepForAllPrograms(programStates);\n } catch (RuntimeException e) {\n throw new ControllerException(e.getMessage());\n }\n\n programStates = this.removeCompletedPrograms(this.repository.getProgramStateList());\n }\n\n this.executor.shutdownNow();\n this.repository.setProgramStateList(programStates);\n }\n\n public List<ProgramState> removeCompletedPrograms(List<ProgramState> programStates) {\n return programStates.stream()\n .filter(ProgramState::isNotCompleted)\n .collect(Collectors.toList());\n }\n\n public Map<Integer, Value> garbageCollector(List<Integer> symbolTableAddresses, Map<Integer, Value> heap) {\n return heap.entrySet().stream()\n .filter(entry -> {\n for (Value value : heap.values()) {\n if (value instanceof ReferenceValue referenceValue) {\n if (referenceValue.getAddress() == entry.getKey()) {\n return true;\n }\n }\n }\n return symbolTableAddresses.contains(entry.getKey());\n })\n .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));\n }\n\n public List<Integer> getAddressesFromSymbolTable(Collection<Value> symbolTableValues) {\n return symbolTableValues.stream()\n .filter(value -> value instanceof ReferenceValue)\n .map(value -> ((ReferenceValue) value).getAddress())\n .toList();\n }\n}" }, { "identifier": "ProgramGenerator", "path": "src/main/java/programgenerator/ProgramGenerator.java", "snippet": "public class ProgramGenerator {\n public static List<Statement> getPrograms() {\n ArrayList<Statement> programs = new ArrayList<>(\n Arrays.asList(\n ProgramGenerator.getProgram1(),\n ProgramGenerator.getProgram2(),\n ProgramGenerator.getProgram3(),\n ProgramGenerator.getProgram4(),\n ProgramGenerator.getProgram5(),\n ProgramGenerator.getProgram6(),\n ProgramGenerator.getProgram7(),\n ProgramGenerator.getProgram8(),\n ProgramGenerator.getProgram9()\n ));\n\n for (int i = 0; i < programs.size(); i++) {\n try {\n IDictionary<String, Type> typeEnvironment = new MyDictionary<>();\n programs.get(i).typeCheck(typeEnvironment);\n } catch (StatementException e) {\n System.out.println(e.getMessage());\n programs.remove(i);\n i--;\n }\n }\n\n return programs;\n }\n\n private static Statement buildProgram(Statement... statements) {\n if (statements.length == 0) {\n return new NopStatement();\n } else if (statements.length == 1) {\n return statements[0];\n }\n\n Statement example = new CompoundStatement(statements[0], statements[1]);\n for (int i = 2; i < statements.length; i++) {\n example = new CompoundStatement(example, statements[i]);\n }\n\n return example;\n }\n\n private static Statement getProgram1() {\n// Basic Example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(2)));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, printingV);\n }\n\n private static Statement getProgram2() {\n// Arithmetic expressions example\n Statement declaringA = new VarDecStatement(\"a\", new IntType());\n Statement declaringB = new VarDecStatement(\"b\", new IntType());\n Statement assigningA = new AssignmentStatement(\"a\",\n new ArithmeticExpression(\"+\", new ValueExpression(new IntValue(2)),\n new ArithmeticExpression(\"*\", new ValueExpression(new IntValue(3)),\n new ValueExpression(new IntValue(5)))));\n Statement assigningB = new AssignmentStatement(\"b\",\n new ArithmeticExpression(\"+\", new VarNameExpression(\"a\"),\n new ValueExpression(new IntValue(1))));\n Statement printingB = new PrintStatement(new VarNameExpression(\"b\"));\n\n return ProgramGenerator.buildProgram(declaringA, declaringB, assigningA, assigningB, printingB);\n }\n\n private static Statement getProgram3() {\n// If statement example\n Statement declaringA = new VarDecStatement(\"a\", new BoolType());\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningA = new AssignmentStatement(\"a\", new ValueExpression(new BoolValue(true)));\n Statement ifStatement = new IfStatement(new VarNameExpression(\"a\"),\n new AssignmentStatement(\"v\", new ValueExpression(new IntValue(2))),\n new AssignmentStatement(\"v\", new ValueExpression(new IntValue(3))));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringA, declaringV, assigningA, ifStatement, printingV);\n }\n\n private static Statement getProgram4() {\n// File handling example\n Statement declaringV = new VarDecStatement(\"v\", new StringType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new StringValue(\"./input/test.in\")));\n Statement openingFile = new OpenFileStatement(new VarNameExpression(\"v\"));\n Statement declaringC = new VarDecStatement(\"c\", new IntType());\n Statement readingC = new FileReadStatement(new VarNameExpression(\"v\"), \"c\");\n Statement printingC = new PrintStatement(new VarNameExpression(\"c\"));\n Statement closingFile = new CloseFileReadStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, openingFile, declaringC, readingC,\n printingC, readingC, printingC, closingFile);\n }\n\n private static Statement getProgram5() {\n// Relational expressions example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(1)));\n Statement ifStatement = new IfStatement(new RelationalExpression(\"<\", new VarNameExpression(\"v\"), new ValueExpression(new IntValue(3))),\n new PrintStatement(new VarNameExpression(\"v\")),\n new NopStatement());\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, ifStatement);\n }\n\n private static Statement getProgram6() {\n// Heap handling example\n Statement declaringV = new VarDecStatement(\"v\", new ReferenceType(new IntType()));\n Statement allocatingV = new HeapAllocationStatement(\"v\", new ValueExpression(new IntValue(20)));\n Statement declaringA = new VarDecStatement(\"a\", new ReferenceType(new ReferenceType(new IntType())));\n Statement allocatingA = new HeapAllocationStatement(\"a\", new VarNameExpression(\"v\"));\n Statement allocatingV2 = new HeapAllocationStatement(\"v\", new ValueExpression(new IntValue(30)));\n Statement printingA = new PrintStatement(new HeapReadExpression(new HeapReadExpression(new VarNameExpression(\"a\"))));\n Statement declaringG = new VarDecStatement(\"g\", new ReferenceType(new IntType()));\n Statement allocatingG = new HeapAllocationStatement(\"g\", new ValueExpression(new IntValue(5)));\n Statement allocatingG2 = new HeapAllocationStatement(\"g\", new ValueExpression(new IntValue(10)));\n Statement printingG = new PrintStatement(new HeapReadExpression(new VarNameExpression(\"g\")));\n\n return ProgramGenerator.buildProgram(declaringV, allocatingV, declaringA, allocatingA,\n allocatingV2, printingA, declaringG, allocatingG, allocatingG2, printingG);\n }\n\n private static Statement getProgram7() {\n// While statement example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(4)));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n Statement decrementingV = new AssignmentStatement(\"v\", new ArithmeticExpression(\"-\",\n new VarNameExpression(\"v\"), new ValueExpression(new IntValue(1))));\n Statement whileStatement = new WhileStatement(new RelationalExpression(\">\",\n new VarNameExpression(\"v\"), new ValueExpression(new IntValue(0))),\n new CompoundStatement(printingV, decrementingV));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, whileStatement);\n }\n\n private static Statement getProgram8() {\n// For statement example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(1)));\n Statement declaringAssigningI = new CompoundStatement(new VarDecStatement(\"i\", new IntType()),\n new AssignmentStatement(\"i\", new ValueExpression(new IntValue(2))));\n Statement incrementingI = new AssignmentStatement(\"i\", new ArithmeticExpression(\"+\",\n new VarNameExpression(\"i\"), new ValueExpression(new IntValue(1))));\n Statement multiplyingV = new AssignmentStatement(\"v\", new ArithmeticExpression(\"*\",\n new VarNameExpression(\"v\"), new VarNameExpression(\"i\")));\n Statement forStatement = new ForStatement(declaringAssigningI, new RelationalExpression(\"<\",\n new VarNameExpression(\"i\"), new ValueExpression(new IntValue(10))), incrementingI, multiplyingV);\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, forStatement, printingV);\n }\n\n private static Statement getProgram9() {\n// Threading example\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement declaringA = new VarDecStatement(\"a\", new ReferenceType(new IntType()));\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(10)));\n Statement allocatingA = new HeapAllocationStatement(\"a\", new ValueExpression(new IntValue(22)));\n Statement writingA = new HeapWriteStatement(\"a\", new ValueExpression(new IntValue(30)));\n Statement assigningV2 = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(32)));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n Statement printingA = new PrintStatement(new HeapReadExpression(new VarNameExpression(\"a\")));\n Statement thread1 = new ForkStatement(new CompoundStatement(writingA,\n new CompoundStatement(assigningV2, new CompoundStatement(printingV, printingA))));\n\n return ProgramGenerator.buildProgram(declaringV, declaringA, assigningV, allocatingA, thread1, printingV, printingA);\n }\n\n private static Statement getProgram10() {\n Statement declaringV = new VarDecStatement(\"v\", new IntType());\n Statement assigningV = new AssignmentStatement(\"v\", new ValueExpression(new IntValue(10)));\n Statement thread1 = new ForkStatement(new ForkStatement(new PrintStatement(new VarNameExpression(\"v\"))));\n Statement printingV = new PrintStatement(new VarNameExpression(\"v\"));\n\n return ProgramGenerator.buildProgram(declaringV, assigningV, thread1, printingV);\n }\n}" }, { "identifier": "ProgramState", "path": "src/main/java/model/ProgramState.java", "snippet": "public class ProgramState {\n private final Statement originalProgram;\n private final IStack<Statement> executionStack;\n private final IDictionary<String, Value> symbolTable;\n private final IHeap heap;\n private final IDictionary<String, BufferedReader> fileTable;\n private final IList<Value> output;\n private final int id;\n private static final Set<Integer> ids = new HashSet<>();\n\n public ProgramState(Statement originalProgram,\n IStack<Statement> executionStack, IDictionary<String, Value> symbolTable,\n IHeap heap, IDictionary<String, BufferedReader> fileTable,\n IList<Value> output) {\n\n this.originalProgram = originalProgram.deepCopy();\n this.executionStack = executionStack;\n this.symbolTable = symbolTable;\n this.heap = heap;\n this.fileTable = fileTable;\n this.output = output;\n\n this.id = ProgramState.generateNewId();\n executionStack.push(originalProgram);\n }\n\n private static int generateNewId() {\n Random random = new Random();\n int id;\n synchronized (ProgramState.ids) {\n do {\n id = random.nextInt();\n } while (ProgramState.ids.contains(id));\n ProgramState.ids.add(id);\n }\n return id;\n }\n\n public int getId() {\n return this.id;\n }\n\n public Statement getOriginalProgram() {\n return this.originalProgram;\n }\n\n public IStack<Statement> getExecutionStack() {\n return this.executionStack;\n }\n\n public IDictionary<String, Value> getSymbolTable() {\n return this.symbolTable;\n }\n\n public IHeap getHeap() {\n return this.heap;\n }\n\n public IDictionary<String, BufferedReader> getFileTable() {\n return this.fileTable;\n }\n\n public IList<Value> getOutput() {\n return this.output;\n }\n\n public boolean isNotCompleted() {\n return !this.executionStack.isEmpty();\n }\n\n public ProgramState oneStep() throws ProgramStateException {\n if (this.executionStack.isEmpty()) {\n throw new ProgramStateException(\"Execution stack is empty!\");\n }\n\n try {\n Statement currentStatement = this.executionStack.pop();\n return currentStatement.execute(this);\n } catch (StatementException | ADTException e) {\n throw new ProgramStateException(e.getMessage());\n }\n }\n\n public String toString() {\n StringBuilder stringBuilder = new StringBuilder();\n\n stringBuilder.append(\"Program State: \").append(this.id).append(\"\\n\");\n stringBuilder.append(\"Execution Stack:\\n\");\n if (this.executionStack.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.executionStack);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Symbol Table:\\n\");\n if (this.symbolTable.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.symbolTable);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Heap:\\n\");\n if (this.heap.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.heap);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"File Table:\\n\");\n if (this.fileTable.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.fileTable);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n stringBuilder.append(\"Output:\\n\");\n if (this.output.isEmpty()) {\n stringBuilder.append(\"----------Empty----------\\n\");\n } else {\n stringBuilder.append(this.output);\n }\n stringBuilder.append(\"-------------------------------------------\\n\");\n\n return stringBuilder.toString();\n }\n}" }, { "identifier": "Statement", "path": "src/main/java/model/statement/Statement.java", "snippet": "public interface Statement {\n ProgramState execute(ProgramState state) throws StatementException;\n\n IDictionary<String, Type> typeCheck(IDictionary<String, Type> typeEnvironment) throws StatementException;\n\n Statement deepCopy();\n}" }, { "identifier": "IRepository", "path": "src/main/java/repository/IRepository.java", "snippet": "public interface IRepository {\n\n List<ProgramState> getProgramStateList();\n\n void setProgramStateList(List<ProgramState> programStateList);\n\n IHeap getHeap();\n\n IDictionary<String, Value> getSymbolTable();\n\n void logProgramStateExecution(ProgramState programState) throws RepositoryException;\n}" }, { "identifier": "Repository", "path": "src/main/java/repository/Repository.java", "snippet": "public class Repository implements IRepository {\n private final List<ProgramState> programStateList = new ArrayList<ProgramState>();\n private final String logFilePath;\n\n public Repository(ProgramState initialProgram, String logFilePath) {\n this.programStateList.add(initialProgram);\n this.logFilePath = logFilePath;\n }\n\n @Override\n public List<ProgramState> getProgramStateList() {\n return List.copyOf(this.programStateList);\n }\n\n @Override\n public void setProgramStateList(List<ProgramState> programStateList) {\n this.programStateList.clear();\n this.programStateList.addAll(programStateList);\n }\n\n @Override\n public IHeap getHeap() {\n return this.programStateList.get(0).getHeap();\n }\n\n @Override\n public IDictionary<String, Value> getSymbolTable() {\n return this.programStateList.get(0).getSymbolTable();\n }\n\n @Override\n public void logProgramStateExecution(ProgramState programState) throws RepositoryException {\n try (PrintWriter logFile = new PrintWriter(new BufferedWriter(new FileWriter(this.logFilePath, true)))) {\n logFile.println(programState);\n } catch (IOException e) {\n throw new RepositoryException(\"Could not open log file!\");\n }\n }\n}" }, { "identifier": "ExitCommand", "path": "src/main/java/view/cli/commands/ExitCommand.java", "snippet": "public class ExitCommand extends Command {\n public ExitCommand(String id, String description) {\n super(id, description);\n }\n\n @Override\n public void execute() {\n System.exit(0);\n }\n}" }, { "identifier": "RunExampleCommand", "path": "src/main/java/view/cli/commands/RunExampleCommand.java", "snippet": "public class RunExampleCommand extends Command {\n private final Controller controller;\n\n public RunExampleCommand(String id, String description, Controller controller) {\n super(id, description);\n this.controller = controller;\n }\n\n @Override\n public void execute() {\n try {\n this.controller.allSteps();\n } catch (InterpreterException e) {\n System.out.println(\"Something went wrong! \" + e.getMessage());\n }\n }\n}" } ]
import adt.*; import controller.Controller; import programgenerator.ProgramGenerator; import model.ProgramState; import model.statement.Statement; import repository.IRepository; import repository.Repository; import view.cli.commands.ExitCommand; import view.cli.commands.RunExampleCommand; import java.util.List; import java.util.Objects; import java.util.Scanner;
5,097
package view.cli; public class CliInterpreter { public static void main(String[] args) { TextMenu menu = new TextMenu(); CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu); menu.show(); } private static String getLogFile() { String logFilePath = "./logs/"; Scanner scanner = new Scanner(System.in); System.out.print("Please enter the log file name: "); String input = scanner.nextLine(); if (Objects.equals(input, "")) { logFilePath += "log.txt"; } else { logFilePath += input; } return logFilePath; } private static void addCommands(String logFilePath, TextMenu menu) {
package view.cli; public class CliInterpreter { public static void main(String[] args) { TextMenu menu = new TextMenu(); CliInterpreter.addCommands(CliInterpreter.getLogFile(), menu); menu.show(); } private static String getLogFile() { String logFilePath = "./logs/"; Scanner scanner = new Scanner(System.in); System.out.print("Please enter the log file name: "); String input = scanner.nextLine(); if (Objects.equals(input, "")) { logFilePath += "log.txt"; } else { logFilePath += input; } return logFilePath; } private static void addCommands(String logFilePath, TextMenu menu) {
List<Statement> programs = ProgramGenerator.getPrograms();
1
2023-10-21 18:08:59+00:00
8k
NewStudyGround/NewStudyGround
server/src/main/java/com/codestates/server/domain/member/controller/MemberController.java
[ { "identifier": "MemberPatchDto", "path": "server/src/main/java/com/codestates/server/domain/member/dto/MemberPatchDto.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\npublic class MemberPatchDto {\n\n private Long memberId;\n\n private String name;\n\n @Pattern(regexp = \"^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,20}$\",\n message = \"비밀번호는 8자리 이상 숫자, 문자, 특수문자 조합으로 입력해야 합니다.\")\n private String password;\n\n @Pattern(regexp = \"^010\\\\d{4}\\\\d{4}$\",\n message = \"휴대폰 번호는 010으로 시작하는 11자리 숫자로 구성되어야 합니다.\")\n private String phone;\n}" }, { "identifier": "MemberPostDto", "path": "server/src/main/java/com/codestates/server/domain/member/dto/MemberPostDto.java", "snippet": "@Getter\n@Setter\npublic class MemberPostDto {\n\n @NotBlank(message = \"이름은 필수값입니다.\")\n private String name;\n\n @Email(message = \"이메일 형식으로 작성해주세요. [email protected]\")\n @NotNull(message = \"이메일은 필수값입니다.\")\n private String email;\n\n @Pattern(regexp = \"^010\\\\d{4}\\\\d{4}$\",\n message = \"휴대폰 번호는 010으로 시작하는 11자리 숫자로 구성되어야 합니다.\")\n private String phone;\n\n @NotBlank(message = \"비밀번호는 필수값입니다.\")\n @Pattern(regexp = \"^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,20}$\",\n message = \"비밀번호는 8자리 이상 숫자, 문자, 특수문자 조합으로 입력해야 합니다.\")\n private String password;\n\n}" }, { "identifier": "MemberResponseDto", "path": "server/src/main/java/com/codestates/server/domain/member/dto/MemberResponseDto.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\npublic class MemberResponseDto {\n\n private String memberId;\n\n private String email;\n\n private String name;\n\n private String phone;\n\n private String password;\n\n private String profileImage;\n\n private List<Bookmark> Bookmarks;\n\n private List<Board> boards;\n\n private List<String> roles;\n}" }, { "identifier": "Member", "path": "server/src/main/java/com/codestates/server/domain/member/entity/Member.java", "snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\n@Entity\npublic class Member {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long memberId;\n\n private String email;\n\n private String name; // 닉네임\n\n private String phone;\n\n private String password;\n\n private String profileImage;\n\n // 멤버 당 하나의 권한을 가지기 때문에 즉시 로딩 괜찮음 (즉시로딩 N : 1은 괜찮으나 1:N은 안됨)\n // 사용자 등록 시 사용자의 권한 등록을 위해 권한 테이블 생성\n @ElementCollection(fetch = FetchType.EAGER)\n private List<String> roles = new ArrayList<>();\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Board> boards;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Answer> answers;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Comment> comments;\n\n @JsonIgnore\n @OneToMany(mappedBy = \"member\", cascade = CascadeType.ALL)\n private List<Bookmark> Bookmarks;\n\n}" }, { "identifier": "MemberMapper", "path": "server/src/main/java/com/codestates/server/domain/member/mapper/MemberMapper.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface MemberMapper {\n\n Member memberPostDtoToMember(MemberPostDto memberPostDto);\n\n Member memberPatchDtoToMember(MemberPatchDto memberPatchDto);\n\n Member memberImagePatchDtoToMember(MemberImagePatchDto memberImagePatchDto);\n\n MemberResponseDto memberToMemberResponseDto(Member member);\n\n List<MemberResponseDto> membersTomemberResponseDto(List<Member> members);\n\n MemberBoardResponseDto memberToMemberBoardResponseDto(Member member);\n}" }, { "identifier": "MultiResponseDto", "path": "server/src/main/java/com/codestates/server/global/dto/MultiResponseDto.java", "snippet": "@Getter\npublic class MultiResponseDto<T> {\n\n private List<T> data; // 응답 데이터 목록 담는 필드\n private PageInfo pageInfo; // 페이지 정보 담는 필드\n\n public MultiResponseDto(List<T> data, Page page) {\n\n this.data = data;\n\n // 페이지 번호 0부터 시작하기 때문에 1부터 시작하는 걸로 변경\n this.pageInfo = new PageInfo(page.getNumber() + 1,\n page.getSize(), page.getTotalElements(), page.getTotalPages());\n\n }\n}" }, { "identifier": "MemberService", "path": "server/src/main/java/com/codestates/server/domain/member/service/MemberService.java", "snippet": "@Service\n@AllArgsConstructor\n@Transactional\npublic class MemberService {\n\n private final MemberRepository memberRepository;\n private final BoardRepository boardRepository;\n\n private final PasswordEncoder passwordEncoder; // 비밀번호 암호화\n private final CustomAuthorityUtils customAuthorityUtils; // 사용자 권한 설정\n private final S3UploadService s3UploadService;\n private final ApplicationEventPublisher eventPublisher;\n\n private static final String DEFAULT_IMAGE = \"http://bit.ly/46a2mSp\"; // 회원 기본 이미지\n private static final String MEMBER_IMAGE_PROCESS_TYPE = \"profile-image\";\n\n /**\n * 회원 가입 로직\n * 존재하는 회원인지 확인한다.\n *\n * @param member\n * @return\n */\n public Member createMember(Member member) {\n\n // 가입된 이메일인지 확인\n verifiyExistedMember(member.getEmail());\n\n // 비밀번호 암호화\n String encrpytedPassword = passwordEncoder.encode(member.getPassword());\n member.setPassword(encrpytedPassword);\n\n // 이메일로 사용자 역할 DB에 저장\n List<String> roles;\n roles = customAuthorityUtils.createRoles(member.getEmail());\n member.setRoles(roles);\n\n if(member.getProfileImage() == null) {\n member.setProfileImage(DEFAULT_IMAGE);\n } else {\n member.setProfileImage(member.getProfileImage());\n }\n\n // 예외 발생 안 시키면 저장\n Member savedMember = memberRepository.save(member);\n\n MemberRegistrationEvent event = new MemberRegistrationEvent(member);\n eventPublisher.publishEvent(event);\n\n return savedMember;\n }\n\n public Member updateMember(Member member){\n\n Member getMember = verifyAuthorizedUser(member.getMemberId());\n\n if(member.getName() != null ) { // 입력받은 닉네임이 null 이 아니면\n getMember.setName(member.getName()); // getMember 에 입력받은 name 대체 -> null 이면 유지\n }\n if(member.getPhone() != null) { // 입력받은 폰이 null이 아니면\n getMember.setPhone(member.getPhone()); // getMember에 입력받은 phone 대체\n }\n if(member.getPassword() != null) { // 입력받은 password null 이 아니면\n getMember.setPassword(passwordEncoder.encode(member.getPassword())); // getPassword에 입력받은 password 대체 -> 인코딩\n }\n\n // 필드가 모두 null인 경우 예외 처리\n if(member.getName() == null && member.getPhone() == null && member.getPassword() == null) {\n throw new RuntimeException(\"수정할 정보가 없습니다.\");\n }\n\n return memberRepository.save(getMember);\n }\n\n public String uploadImage(Long memberId, MultipartFile file) {\n// public String uploadImage(Long memberId, MultipartFile file, int x, int y, int width, int height) throws IOException {\n\n Member member = verifyAuthorizedUser(memberId);\n\n // 현재 프로필 이미지 가지고 오기\n String presentProfileImage = member.getProfileImage();\n // 만약에 현재 파일이 있으면 현재 파일 삭제\n if (presentProfileImage != null && !presentProfileImage.equals(DEFAULT_IMAGE)) {\n s3UploadService.deleteImageFromS3(presentProfileImage, MEMBER_IMAGE_PROCESS_TYPE);\n// s3UploadService.deleteImageFromS3(presentProfileImage);\n }\n // profileImage 새로운 imgae로 upload 하기\n String newProfileImage = null;\n newProfileImage = s3UploadService.uploadProfileImage(file, MEMBER_IMAGE_PROCESS_TYPE);\n\n if(newProfileImage == null) {\n // 새로운 파일 업로드 하는 메서드 (파일, x좌표, y좌표, 가로, 세로)\n newProfileImage = DEFAULT_IMAGE;\n // newProfileImage = s3UploadService.uploadProfileImage(file, x, y, width, height);\n }\n // 회원 profileImage에 set 하고 save\n member.setProfileImage(newProfileImage);\n // 새로운 이미지 URL을 멤버 객체에 설정\n member.setProfileImage(newProfileImage);\n\n // 회원 정보 업데이트\n memberRepository.save(member);\n\n return newProfileImage;\n }\n\n public String deleteProfileImage(Long memberId) {\n\n Member member = verifyAuthorizedUser(memberId);\n\n // 현재 프로필 이미지 URL을 가져옵니다.\n String currentProfileImage = member.getProfileImage();\n\n // S3에서 현재 이미지 삭제\n if (currentProfileImage != null && !currentProfileImage.equals(DEFAULT_IMAGE)) {\n s3UploadService.deleteImageFromS3(currentProfileImage, MEMBER_IMAGE_PROCESS_TYPE);\n// s3UploadService.deleteImageFromS3(currentProfileImage);\n }\n\n // DB에서 프로필 이미지 URL 기본 설정\n member.setProfileImage(DEFAULT_IMAGE);\n memberRepository.save(member);\n\n return DEFAULT_IMAGE;\n }\n\n // member 마이페이지에서 사용자 정보 가지고 오는 메서드\n public Member getMember(Long memberId) {\n Member member = getVerifiedMember(memberId);\n\n return member;\n }\n\n // member 전체 정보 가지고 오는 메서드로 pagination\n public Page<Member> getMembers(int page, int size) {\n return memberRepository.findAll(PageRequest.of(page, size,\n Sort.by(\"memberId\").descending()));\n }\n\n // member 삭제하는 deleteMember 메서드\n public void deleteMember(Long memberId) {\n\n Member member = getVerifiedMember(memberId);\n\n memberRepository.delete(member);\n\n }\n\n /**\n * 등록된 회원인지 확인 (로그인 안 했으면 사용 불가)\n *\n * @param memberId\n * @return\n */\n public Member getVerifiedMember(Long memberId) {\n\n Optional<Member> member = memberRepository.findById(memberId);\n\n // 회원이 아니면 예외 발생\n Member getMember =\n member.orElseThrow(() -> new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n\n return getMember;\n }\n\n\n /**\n * 이미 가입한 회원인지 확인하는 메서드\n * 만약 가입 되어있으면 예외 던지기\n * @param email\n */\n private void verifiyExistedMember(String email) {\n\n Optional<Member> optionalMember = memberRepository.findByEmail(email);\n\n if(optionalMember.isPresent())\n throw new BusinessLogicException(ExceptionCode.USER_EXISTS);\n }\n\n /**\n * 로그인한 Member를 가지고 오는 메서드\n * @return\n */\n public Member getLoginMember() {\n return memberRepository.findByEmail(AuthUserUtils.getAuthUser().getName())\n .orElseThrow(()-> new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n }\n\n public Long getLoginMemberId(){\n\n try {\n Member member = memberRepository.findByEmail(AuthUserUtils.getAuthUser().getName()).orElseThrow(() ->\n new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n Long memberId = member.getMemberId();\n return memberId;\n\n }catch (Exception e){\n return 0L;\n }\n }\n\n public Member findMember(Long memberId){\n Member member = memberRepository.findById(memberId).orElseThrow(\n () -> new BusinessLogicException(ExceptionCode.USER_NOT_FOUND));\n return member;\n }\n\n /**\n * 현재 멤버 아이디랑 로그인한 객체의 아이디랑 비교해서 같은지 확인하는 메서드\n * @param memberId\n */\n public Member verifyAuthorizedUser(Long memberId) {\n Member getMember = getVerifiedMember(memberId);\n\n if (!getLoginMember().getMemberId().equals(memberId)) {\n throw new BusinessLogicException(ExceptionCode.UNAUTHORIZED_USER);\n }\n return getMember;\n }\n}" }, { "identifier": "UriCreator", "path": "server/src/main/java/com/codestates/server/global/uri/UriCreator.java", "snippet": "public class UriCreator {\n // URI 를 만드는 createUri 메서드\n public static URI createUri(String defaultUri, Long resourceId) {\n return UriComponentsBuilder\n .newInstance()\n .path(defaultUri + \"/{resourceId}\")// URI 경로 설정, resourceId 변수에는 값을 대체\n .buildAndExpand(resourceId) // 경로 변수를 실제 값으로 대체해서 URI 생성\n .toUri(); // 최종 URI로 변환하여 반환합니다.\n }\n}" } ]
import com.codestates.server.domain.member.dto.MemberPatchDto; import com.codestates.server.domain.member.dto.MemberPostDto; import com.codestates.server.domain.member.dto.MemberResponseDto; import com.codestates.server.domain.member.entity.Member; import com.codestates.server.domain.member.mapper.MemberMapper; import com.codestates.server.global.dto.MultiResponseDto; import com.codestates.server.domain.member.service.MemberService; import com.codestates.server.global.uri.UriCreator; import lombok.AllArgsConstructor; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.Positive; import java.io.IOException; import java.net.URI; import java.util.List;
3,685
package com.codestates.server.domain.member.controller; @AllArgsConstructor @RestController @RequestMapping("/members") @Validated @CrossOrigin(origins = "*", allowedHeaders = "*") public class MemberController { private final MemberMapper mapper;
package com.codestates.server.domain.member.controller; @AllArgsConstructor @RestController @RequestMapping("/members") @Validated @CrossOrigin(origins = "*", allowedHeaders = "*") public class MemberController { private final MemberMapper mapper;
private final MemberService memberService;
6
2023-10-23 09:41:00+00:00
8k
LeGhast/Miniaturise
src/main/java/de/leghast/miniaturise/listener/PlayerInteractListener.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 @Override\n public void onEnable() {\n ConfigManager.setupConfig(this);\n initialiseManagers();\n registerListeners();\n setCommands();\n setTabCompleters();\n }\n\n @Override\n public void onDisable() {\n saveConfig();\n }\n\n private void initialiseManagers(){\n miniatureManager = new MiniatureManager(this);\n regionManager = new RegionManager(this);\n settingsManager = new SettingsManager(this);\n }\n\n private void registerListeners(){\n Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(this), this);\n Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(this), this);\n Bukkit.getPluginManager().registerEvents(new InventoryClickListener(this), this);\n }\n\n private void setCommands(){\n getCommand(\"select\").setExecutor(new SelectCommand(this));\n getCommand(\"scale\").setExecutor(new ScaleCommand(this));\n getCommand(\"cut\").setExecutor(new CutCommand(this));\n getCommand(\"tools\").setExecutor(new ToolsCommand(this));\n getCommand(\"paste\").setExecutor(new PasteCommand(this));\n getCommand(\"tool\").setExecutor(new ToolCommand(this));\n getCommand(\"delete\").setExecutor(new DeleteCommand(this));\n getCommand(\"copy\").setExecutor(new CopyCommand(this));\n getCommand(\"position\").setExecutor(new PositionCommand(this));\n getCommand(\"clear\").setExecutor(new ClearCommand(this));\n getCommand(\"adjust\").setExecutor(new AdjustCommand(this));\n getCommand(\"rotate\").setExecutor(new RotateCommand(this));\n }\n\n public void setTabCompleters(){\n getCommand(\"position\").setTabCompleter(new PositionTabCompleter());\n getCommand(\"scale\").setTabCompleter(new ScaleTabCompleter());\n getCommand(\"tool\").setTabCompleter(new ToolTabCompleter());\n getCommand(\"rotate\").setTabCompleter(new RotateTabCompleter());\n }\n\n /**\n * @return The MiniatureManager instance\n */\n public MiniatureManager getMiniatureManager(){\n return miniatureManager;\n }\n\n /**\n * @return The RegionManager instance\n */\n public RegionManager getRegionManager(){\n return regionManager;\n }\n\n public SettingsManager getSettingsManager(){\n return settingsManager;\n }\n\n}" }, { "identifier": "PlacedMiniature", "path": "src/main/java/de/leghast/miniaturise/instance/miniature/PlacedMiniature.java", "snippet": "public class PlacedMiniature {\n\n private List<BlockDisplay> blockDisplays;\n private double blockSize;\n\n public PlacedMiniature(List<MiniatureBlock> blocks, Location origin) throws InvalidParameterException {\n if(!blocks.isEmpty()){\n blockDisplays = new ArrayList<>();\n blockSize = blocks.get(0).getSize();\n\n for(MiniatureBlock mb : blocks) {\n BlockDisplay bd;\n bd = (BlockDisplay) origin.getWorld().spawnEntity(new Location(\n origin.getWorld(),\n mb.getX() + ceil(origin.getX()),\n mb.getY() + ceil(origin.getY()),\n mb.getZ() + ceil(origin.getZ())),\n EntityType.BLOCK_DISPLAY);\n bd.setBlock(mb.getBlockData());\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n blockDisplays.add(bd);\n }\n }else{\n throw new InvalidParameterException(\"The miniature block list is empty\");\n }\n }\n\n public PlacedMiniature(List<BlockDisplay> blockDisplays) throws InvalidParameterException{\n this.blockDisplays = blockDisplays;\n if(!blockDisplays.isEmpty()){\n blockSize = blockDisplays.get(0).getTransformation().getScale().x;\n }else{\n throw new InvalidParameterException(\"The block display list is empty\");\n }\n }\n\n public void remove(){\n for(BlockDisplay bd : blockDisplays){\n bd.remove();\n }\n }\n\n public void scaleUp(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleUp(scale);\n rearrange(origin, miniature);\n blockSize *= scale;\n });\n }\n\n public void scaleDown(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleDown(scale);\n rearrange(origin, miniature);\n blockSize /= scale;\n });\n }\n\n private void rearrange(Location origin, Miniature miniature) {\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n for(int i = 0; i < getBlockCount(); i++){\n BlockDisplay bd = blockDisplays.get(i);\n MiniatureBlock mb = miniature.getBlocks().get(i);\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.teleport(new Location( bd.getWorld(),\n mb.getX() + origin.getX(),\n mb.getY() + origin.getY(),\n mb.getZ() + origin.getZ()));\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n });\n }\n });\n }\n\n public void rotate(Axis axis, float angle){\n Location origin = blockDisplays.get(0).getLocation();\n float finalAngle = (float) Math.toRadians(angle);\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n\n for(BlockDisplay bd : blockDisplays){\n\n Transformation transformation = bd.getTransformation();\n\n switch (axis){\n case X -> transformation.getLeftRotation().rotateX(finalAngle);\n case Y -> transformation.getLeftRotation().rotateY(finalAngle);\n case Z -> transformation.getLeftRotation().rotateZ(finalAngle);\n }\n\n Vector3f newPositionVector = getRotatedPosition(\n bd.getLocation().toVector().toVector3f(),\n origin.toVector().toVector3f(),\n axis,\n finalAngle\n );\n\n Location newLocation = new Location(\n bd.getLocation().getWorld(),\n newPositionVector.x,\n newPositionVector.y,\n newPositionVector.z\n );\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.setTransformation(transformation);\n bd.teleport(newLocation);\n });\n\n }\n });\n\n\n\n }\n\n private Vector3f getRotatedPosition(Vector3f pointToRotate, Vector3f origin, Axis axis, float angle){\n pointToRotate.sub(origin);\n Matrix3f rotationMatrix = new Matrix3f();\n\n switch (axis){\n case X -> rotationMatrix.rotationX(angle);\n case Y -> rotationMatrix.rotationY(angle);\n case Z -> rotationMatrix.rotationZ(angle);\n }\n\n rotationMatrix.transform(pointToRotate);\n\n pointToRotate.add(origin);\n\n return pointToRotate;\n }\n\n public void move(Vector addition){\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n for(BlockDisplay bd : blockDisplays){\n bd.teleport(bd.getLocation().add(addition));\n }\n });\n }\n\n public void move(Axis axis, double addition){\n switch (axis){\n case X -> move(new Vector(addition, 0, 0));\n case Y -> move(new Vector(0, addition, 0));\n case Z -> move(new Vector(0, 0, addition));\n }\n }\n\n public double getBlockSize() {\n return blockSize;\n }\n\n public int getBlockCount(){\n return blockDisplays.size();\n }\n\n public List<BlockDisplay> getBlockDisplays(){\n return blockDisplays;\n }\n\n private Miniaturise getMain(){\n return (Miniaturise) Bukkit.getPluginManager().getPlugin(\"Miniaturise\");\n }\n\n}" }, { "identifier": "SelectedLocations", "path": "src/main/java/de/leghast/miniaturise/instance/region/SelectedLocations.java", "snippet": "public class SelectedLocations {\n\n private Location loc1;\n private Location loc2;\n\n public SelectedLocations(Location loc1, Location loc2){\n this.loc1 = loc1;\n this.loc2 = loc2;\n }\n\n public SelectedLocations(){\n this.loc1 = null;\n this.loc2 = null;\n }\n\n /**\n * @return The first location, that was selected\n * */\n public Location getLoc1(){\n return loc1;\n }\n\n /**\n * @return The second location, that was selected\n * */\n public Location getLoc2(){\n return loc2;\n }\n\n /**\n * Sets the first location\n *\n * @param loc1 The location to replace the old selected location\n * */\n public void setLoc1(Location loc1){\n this.loc1 = loc1;\n }\n\n /**\n * Sets the second location\n *\n * @param loc2 The location to replace the old selected location\n * */\n public void setLoc2(Location loc2){\n this.loc2 = loc2;\n }\n\n /**\n * @return If both locations are set\n */\n public boolean isValid(){\n return loc1 != null && loc2 != null;\n }\n\n}" }, { "identifier": "AdjusterSettings", "path": "src/main/java/de/leghast/miniaturise/instance/settings/AdjusterSettings.java", "snippet": "public class AdjusterSettings {\n\n private Player player;\n\n private PositionSettings positionSettings;\n private SizeSettings sizeSettings;\n private RotationSettings rotationSettings;\n\n private Page page;\n\n public AdjusterSettings(Player player){\n this.player = player;\n\n positionSettings = new PositionSettings(this);\n sizeSettings = new SizeSettings(this);\n rotationSettings = new RotationSettings(this);\n\n page = Page.POSITION;\n }\n\n public PositionSettings getPositionSettings(){\n return positionSettings;\n }\n\n public SizeSettings getSizeSettings(){\n return sizeSettings;\n }\n\n public RotationSettings getRotationSettings(){\n return rotationSettings;\n }\n\n public Page getPage(){\n return page;\n }\n\n public void setPage(Page page){\n this.page = page;\n }\n\n public Player getPlayer(){\n return player;\n }\n\n}" }, { "identifier": "ConfigManager", "path": "src/main/java/de/leghast/miniaturise/manager/ConfigManager.java", "snippet": "public class ConfigManager {\n\n private static FileConfiguration config;\n\n //Setup/Initialise the ConfigManager\n public static void setupConfig(Miniaturise main){\n ConfigManager.config = main.getConfig();\n main.saveDefaultConfig();\n }\n\n /**\n * @return The selector tool material\n */\n public static Material getSelectorToolMaterial(){\n return Material.matchMaterial(config.getString(\"selector-tool\"));\n }\n\n /**\n * Set a new material as the selector tool\n *\n * @param material - The material, you want the selector tool to be\n */\n public static void setSelectorToolMaterial(Material material){\n config.set(\"selector-tool\", material.name());\n\n }\n\n /**\n * @return The maximum amount of blocks that are allowed in one miniature\n */\n public static int getMaxEntityLimit(){\n return config.getInt(\"max-entity-limit\");\n }\n\n /**\n * Set the maximum amount of blocks that are allowed in one miniature\n * NOTE: Higher numbers than the default value(1500) can lead to various performance issues. Handle with care and responsibility\n *\n * @param maxBlockLimit The new maximum amount of blocks that are allowed in one miniature\n */\n public static void setMaxEntityLimit(int maxBlockLimit){\n config.set(\"max-entity-limit\", maxBlockLimit);\n }\n\n /**\n * @return The default size of a block in a newly instanced miniature\n */\n public static double getDefaultSize(){\n return config.getDouble(\"default-size\");\n }\n\n /**\n * Set the default size of a block in a newly instanced miniature\n *\n * @param size The new default size of a block in a newly instanced miniature\n */\n public static void setDefaultSize(double size){\n config.set(\"default-size\", size);\n }\n\n public static Material getAdjusterToolMaterial(){\n return Material.matchMaterial(config.getString(\"adjuster-tool\"));\n }\n\n public static void setAdjusterToolMaterial(Material material){\n config.set(\"adjuster-tool\", material.name());\n }\n\n}" }, { "identifier": "UserInterface", "path": "src/main/java/de/leghast/miniaturise/ui/UserInterface.java", "snippet": "public class UserInterface {\n\n public UserInterface(Miniaturise main, Player player, Page page){\n Inventory inv = Bukkit.createInventory(null, 45, page.getTitle());\n switch (page){\n case POSITION -> {\n inv.setContents(PositionPage.getPositionPage(main, player));\n }\n case SIZE -> {\n inv.setContents(SizePage.getSizePage(main, player));\n }\n case ROTATION -> {\n inv.setContents(RotationPage.getRotationPage(main, player));\n }\n }\n player.openInventory(inv);\n }\n\n}" }, { "identifier": "Util", "path": "src/main/java/de/leghast/miniaturise/util/Util.java", "snippet": "public class Util {\n\n public static final String PREFIX = \"§7[§eMiniaturise§7] \";\n\n public static String getDimensionName(String string){\n switch (string){\n case \"NORMAL\" -> {\n return \"minecraft:overworld\";\n }\n case \"NETHER\" -> {\n return \"minecraft:the_nether\";\n }\n case \"THE_END\" -> {\n return \"minecraft:the_end\";\n }\n default -> {\n return \"Invalid dimension\";\n }\n }\n }\n\n public static List<BlockDisplay> getBlockDisplaysFromRegion(Player player, Region region){\n List<BlockDisplay> blockDisplays = new ArrayList<>();\n for(Chunk chunk : player.getWorld().getLoadedChunks()){\n for(Entity entity : chunk.getEntities()){\n if(entity instanceof BlockDisplay && region.contains(entity.getLocation())){\n blockDisplays.add((BlockDisplay) entity);\n }\n }\n }\n return blockDisplays;\n }\n\n public static void setCustomNumberInput(Miniaturise main, Player player, Page page){\n ItemStack output = new ItemStack(Material.PAPER);\n ItemMeta meta = output.getItemMeta();\n meta.setDisplayName(\"§eSet custom factor\");\n output.setItemMeta(meta);\n PageUtil.addGlint(output);\n\n new AnvilGUI.Builder()\n .title(\"§eEnter custom factor\")\n .text(\"1\")\n .onClick((slot, stateSnapshot) -> {\n if(slot == AnvilGUI.Slot.OUTPUT){\n AdjusterSettings settings = main.getSettingsManager().getAdjusterSettings(player.getUniqueId());\n switch (page){\n case POSITION -> settings.getPositionSettings().setFactor(stateSnapshot.getText());\n case SIZE -> settings.getSizeSettings().setFactor(stateSnapshot.getText());\n case ROTATION -> settings.getRotationSettings().setFactor(stateSnapshot.getText());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.close());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.updateTitle(\"§eEnter custom factor\", false));\n })\n .preventClose()\n .itemOutput(output)\n .plugin(main)\n .open(player);\n\n }\n\n}" } ]
import de.leghast.miniaturise.Miniaturise; import de.leghast.miniaturise.instance.miniature.PlacedMiniature; import de.leghast.miniaturise.instance.region.SelectedLocations; import de.leghast.miniaturise.instance.settings.AdjusterSettings; import de.leghast.miniaturise.manager.ConfigManager; import de.leghast.miniaturise.ui.UserInterface; import de.leghast.miniaturise.util.Util; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot;
4,133
package de.leghast.miniaturise.listener; /** * This class listens for player interactions, that are relevant for the Miniaturise plugin * @author GhastCraftHD * */ public class PlayerInteractListener implements Listener { private Miniaturise main; public PlayerInteractListener(Miniaturise main){ this.main = main; } @EventHandler public void onPlayerInteract(PlayerInteractEvent e){ Player player = e.getPlayer(); Material material = player.getInventory().getItemInMainHand().getType(); if(player.hasPermission("miniaturise.use")){ if(material == ConfigManager.getSelectorToolMaterial()){ e.setCancelled(true); handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand()); }else if(material == ConfigManager.getAdjusterToolMaterial()){ e.setCancelled(true); if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){ handleAdjusterInteraction(player, e.getAction(), e.getHand()); }else{
package de.leghast.miniaturise.listener; /** * This class listens for player interactions, that are relevant for the Miniaturise plugin * @author GhastCraftHD * */ public class PlayerInteractListener implements Listener { private Miniaturise main; public PlayerInteractListener(Miniaturise main){ this.main = main; } @EventHandler public void onPlayerInteract(PlayerInteractEvent e){ Player player = e.getPlayer(); Material material = player.getInventory().getItemInMainHand().getType(); if(player.hasPermission("miniaturise.use")){ if(material == ConfigManager.getSelectorToolMaterial()){ e.setCancelled(true); handleSelectorInteraction(player, e.getAction(), e.getClickedBlock(), e.getHand()); }else if(material == ConfigManager.getAdjusterToolMaterial()){ e.setCancelled(true); if(main.getMiniatureManager().hasPlacedMiniature(player.getUniqueId())){ handleAdjusterInteraction(player, e.getAction(), e.getHand()); }else{
player.sendMessage(Util.PREFIX + "§cYou have not selected a placed miniature");
6
2023-10-15 09:08:33+00:00
8k
zendo-games/zenlib
src/main/java/zendo/games/zenlib/screens/transitions/Transition.java
[ { "identifier": "ZenConfig", "path": "src/main/java/zendo/games/zenlib/ZenConfig.java", "snippet": "public class ZenConfig {\n\n public final Window window;\n public final UI ui;\n\n public ZenConfig() {\n this(\"zenlib\", 1280, 720, null);\n }\n\n public ZenConfig(String title, int width, int height) {\n this(title, width, height, null);\n }\n\n public ZenConfig(String title, int width, int height, String uiSkinPath) {\n this.window = new Window(title, width, height);\n this.ui = new UI(uiSkinPath);\n }\n\n public static class Window {\n public final String title;\n public final int width;\n public final int height;\n\n public Window(String title, int width, int height) {\n this.title = title;\n this.width = width;\n this.height = height;\n }\n }\n\n public static class UI {\n public final String skinPath;\n\n public UI() {\n this(null);\n }\n\n public UI(String skinPath) {\n this.skinPath = skinPath;\n }\n }\n}" }, { "identifier": "ZenMain", "path": "src/main/java/zendo/games/zenlib/ZenMain.java", "snippet": "public abstract class ZenMain<AssetsType extends ZenAssets> extends ApplicationAdapter {\n\n /**\n * Debug flags, toggle these values as needed, or override in project's ZenMain subclass\n */\n public static class Debug {\n public static boolean general = false;\n public static boolean shaders = false;\n public static boolean ui = false;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static ZenMain instance;\n\n public ZenConfig config;\n public AssetsType assets;\n public TweenManager tween;\n public FrameBuffer frameBuffer;\n public TextureRegion frameBufferRegion;\n public OrthographicCamera windowCamera;\n\n private Transition transition;\n\n public ZenMain(ZenConfig config) {\n ZenMain.instance = this;\n this.config = config;\n }\n\n /**\n * Override to create project-specific ZenAssets subclass instance\n */\n public abstract AssetsType createAssets();\n\n /**\n * Override to create project-specific ZenScreen subclass instance that will be used as the starting screen\n */\n public abstract ZenScreen createStartScreen();\n\n @Override\n public void create() {\n Time.init();\n\n // TODO - consider moving to ZenAssets\n tween = new TweenManager();\n Tween.setWaypointsLimit(4);\n Tween.setCombinedAttributesLimit(4);\n Tween.registerAccessor(Color.class, new ColorAccessor());\n Tween.registerAccessor(Rectangle.class, new RectangleAccessor());\n Tween.registerAccessor(Vector2.class, new Vector2Accessor());\n Tween.registerAccessor(Vector3.class, new Vector3Accessor());\n Tween.registerAccessor(OrthographicCamera.class, new CameraAccessor());\n\n frameBuffer = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, true);\n var texture = frameBuffer.getColorBufferTexture();\n texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);\n frameBufferRegion = new TextureRegion(texture);\n frameBufferRegion.flip(false, true);\n\n windowCamera = new OrthographicCamera();\n windowCamera.setToOrtho(false, config.window.width, config.window.height);\n windowCamera.update();\n\n assets = createAssets();\n\n transition = new Transition(config);\n setScreen(createStartScreen());\n }\n\n @Override\n public void dispose() {\n frameBuffer.dispose();\n transition.dispose();\n assets.dispose();\n }\n\n @Override\n public void resize(int width, int height) {\n var screen = currentScreen();\n if (screen != null) {\n screen.resize(width, height);\n }\n }\n\n public ZenScreen currentScreen() {\n return transition.screens.current;\n }\n\n public void update() {\n // handle global input\n // TODO - might not want to keep these in library code\n {\n if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {\n Gdx.app.exit();\n }\n if (Gdx.input.isKeyJustPressed(Input.Keys.F1)) {\n Debug.general = !Debug.general;\n Debug.ui = !Debug.ui;\n }\n }\n\n // update things that must update every tick\n {\n Time.update();\n tween.update(Time.delta);\n transition.alwaysUpdate(Time.delta);\n }\n\n // handle a pause\n if (Time.pause_timer > 0) {\n Time.pause_timer -= Time.delta;\n if (Time.pause_timer <= -0.0001f) {\n Time.delta = -Time.pause_timer;\n } else {\n // skip updates if we're paused\n return;\n }\n }\n Time.millis += (long) Time.delta;\n Time.previous_elapsed = Time.elapsed_millis();\n\n // update normally (if not paused)\n transition.update(Time.delta);\n }\n\n @Override\n public void render() {\n update();\n var batch = assets.batch;\n var screens = transition.screens;\n\n screens.current.renderFrameBuffers(batch);\n if (screens.next == null) {\n screens.current.render(batch);\n } else {\n transition.render(batch, windowCamera);\n }\n }\n\n public void setScreen(ZenScreen currentScreen) {\n setScreen(currentScreen, null, Transition.DEFAULT_SPEED);\n }\n\n public void setScreen(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) {\n // only one transition at a time\n if (transition.active) return;\n if (transition.screens.next != null) return;\n\n var screens = transition.screens;\n if (screens.current == null) {\n // no current screen set, go ahead and set it\n screens.current = newScreen;\n } else {\n // current screen is set, so trigger transition to new screen\n transition.startTransition(newScreen, type, transitionSpeed);\n }\n }\n}" }, { "identifier": "ZenTransition", "path": "src/main/java/zendo/games/zenlib/assets/ZenTransition.java", "snippet": "public enum ZenTransition {\n // spotless:off\n blinds\n , circle_crop\n , crosshatch\n , cube\n , dissolve\n , doom_drip\n , dreamy\n , heart\n , pixelize\n , radial\n , ripple\n , simple_zoom\n , stereo\n ;\n // spotless:on\n\n public ShaderProgram shader;\n public static boolean initialized = false;\n\n ZenTransition() {\n this.shader = null;\n }\n\n public static void init() {\n var vertSrcPath = \"shaders/transitions/default.vert\";\n for (var value : values()) {\n var fragSrcPath = \"shaders/transitions/\" + value.name() + \".frag\";\n value.shader = loadShader(vertSrcPath, fragSrcPath);\n }\n initialized = true;\n }\n\n public static ShaderProgram random() {\n if (!initialized) {\n throw new GdxRuntimeException(\n \"Failed to get random screen transition shader, ScreenTransitions is not initialized\");\n }\n\n var random = (int) (Math.random() * values().length);\n return values()[random].shader;\n }\n\n public static ShaderProgram loadShader(String vertSourcePath, String fragSourcePath) {\n ShaderProgram.pedantic = false;\n var shaderProgram = new ShaderProgram(\n Gdx.files.classpath(\"zendo/games/zenlib/assets/\" + vertSourcePath),\n Gdx.files.classpath(\"zendo/games/zenlib/assets/\" + fragSourcePath));\n var log = shaderProgram.getLog();\n\n if (!shaderProgram.isCompiled()) {\n throw new GdxRuntimeException(\"LoadShader: compilation failed for \" + \"'\" + vertSourcePath + \"' and '\"\n + fragSourcePath + \"':\\n\" + log);\n } else if (ZenMain.Debug.shaders) {\n Gdx.app.debug(\"LoadShader\", \"ShaderProgram compilation log: \" + log);\n }\n\n return shaderProgram;\n }\n}" }, { "identifier": "ZenScreen", "path": "src/main/java/zendo/games/zenlib/screens/ZenScreen.java", "snippet": "public abstract class ZenScreen implements Disposable {\n\n public final SpriteBatch batch;\n public final TweenManager tween;\n public final OrthographicCamera windowCamera;\n public final Vector3 pointerPos;\n\n protected OrthographicCamera worldCamera;\n protected Viewport viewport;\n protected Stage uiStage;\n protected Skin skin;\n protected boolean exitingScreen;\n\n public ZenScreen() {\n var main = ZenMain.instance;\n\n this.batch = main.assets.batch;\n this.tween = main.tween;\n this.windowCamera = main.windowCamera;\n this.pointerPos = new Vector3();\n this.worldCamera = new OrthographicCamera();\n this.viewport = new ScreenViewport(worldCamera);\n this.viewport.update(main.config.window.width, main.config.window.height, true);\n this.exitingScreen = false;\n\n initializeUI();\n }\n\n @Override\n public void dispose() {}\n\n public void resize(int width, int height) {\n viewport.update(width, height, true);\n }\n\n /**\n * Update something in the screen even when\n * {@code Time.pause_for()} is being processed\n * @param dt the time in seconds since the last frame\n */\n public void alwaysUpdate(float dt) {}\n\n public void update(float dt) {\n windowCamera.update();\n worldCamera.update();\n uiStage.act(dt);\n }\n\n public void renderFrameBuffers(SpriteBatch batch) {}\n\n public abstract void render(SpriteBatch batch);\n\n protected void initializeUI() {\n skin = VisUI.getSkin();\n\n var viewport = new ScreenViewport(windowCamera);\n uiStage = new Stage(viewport, batch);\n\n // extend and setup any per-screen ui widgets in here...\n }\n}" }, { "identifier": "Time", "path": "src/main/java/zendo/games/zenlib/utils/Time.java", "snippet": "public class Time {\n\n private static class CallbackInfo {\n private final Callback callback;\n private final Object[] params;\n private float timer;\n\n public float timeout = 0;\n public float interval = 0;\n\n CallbackInfo(Callback callback, Object... params) {\n this.callback = callback;\n this.params = params;\n this.timer = 0;\n }\n\n boolean isInterval() {\n return (interval > 0);\n }\n\n boolean isTimeout() {\n return (timeout > 0);\n }\n\n boolean update(float dt) {\n boolean called = false;\n\n timer += dt;\n\n if (interval > 0) {\n if (timer >= interval) {\n timer -= interval;\n if (callback != null) {\n callback.run(params);\n called = true;\n }\n }\n } else {\n if (timer >= timeout) {\n if (callback != null) {\n callback.run(params);\n called = true;\n }\n }\n }\n\n return called;\n }\n }\n\n private static long start_millis = 0;\n\n public static long millis = 0;\n public static long previous_elapsed = 0;\n public static float delta = 0;\n public static float pause_timer = 0;\n\n private static Array<CallbackInfo> callbacks;\n\n public static void init() {\n start_millis = TimeUtils.millis();\n callbacks = new Array<>();\n }\n\n public static void update() {\n Time.delta = Calc.min(1 / 30f, Gdx.graphics.getDeltaTime());\n\n for (int i = callbacks.size - 1; i >= 0; i--) {\n CallbackInfo info = callbacks.get(i);\n boolean wasCalled = info.update(Time.delta);\n if (wasCalled && info.isTimeout()) {\n callbacks.removeIndex(i);\n }\n }\n }\n\n public static void do_after_delay(float seconds, Callback callback) {\n CallbackInfo info = new CallbackInfo(callback);\n info.timeout = seconds;\n callbacks.add(info);\n }\n\n public static void do_at_interval(float seconds, Callback callback) {\n CallbackInfo info = new CallbackInfo(callback);\n info.interval = seconds;\n callbacks.add(info);\n }\n\n public static long elapsed_millis() {\n return TimeUtils.timeSinceMillis(start_millis);\n }\n\n public static void pause_for(float time) {\n if (time >= pause_timer) {\n pause_timer = time;\n }\n }\n\n public static boolean on_time(float time, float timestamp) {\n return (time >= timestamp) && ((time - Time.delta) < timestamp);\n }\n\n public static boolean on_interval(float time, float delta, float interval, float offset) {\n return Calc.floor((time - offset - delta) / interval) < Calc.floor((time - offset) / interval);\n }\n\n public static boolean on_interval(float delta, float interval, float offset) {\n return Time.on_interval(Time.elapsed_millis(), delta, interval, offset);\n }\n\n public static boolean on_interval(float interval, float offset) {\n return Time.on_interval(Time.elapsed_millis(), Time.delta, interval, offset);\n }\n\n public static boolean on_interval(float interval) {\n return Time.on_interval(interval, 0);\n }\n\n public static boolean between_interval(float time, float interval, float offset) {\n return Calc.modf(time - offset, interval * 2) >= interval;\n }\n\n public static boolean between_interval(float interval, float offset) {\n return Time.between_interval(Time.elapsed_millis(), interval, offset);\n }\n\n public static boolean between_interval(float interval) {\n return Time.between_interval(interval, 0);\n }\n}" } ]
import aurelienribon.tweenengine.Timeline; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.primitives.MutableFloat; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.Disposable; import zendo.games.zenlib.ZenConfig; import zendo.games.zenlib.ZenMain; import zendo.games.zenlib.assets.ZenTransition; import zendo.games.zenlib.screens.ZenScreen; import zendo.games.zenlib.utils.Time;
4,220
package zendo.games.zenlib.screens.transitions; public class Transition implements Disposable { public static final float DEFAULT_SPEED = 0.66f; public boolean active; public MutableFloat percent; public ShaderProgram shader; public final Screens screens = new Screens(); public final FrameBuffers fbo = new FrameBuffers(); public final Textures tex = new Textures(); private final ZenConfig config; public Transition(ZenConfig config) { this.config = config; this.active = false; this.percent = new MutableFloat(0); this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.tex.from = this.fbo.from.getColorBufferTexture(); this.tex.to = this.fbo.to.getColorBufferTexture(); } @Override public void dispose() { screens.dispose(); fbo.dispose(); // no need to dispose textures here, // they are owned by the frame buffers } public void alwaysUpdate(float dt) { screens.current.alwaysUpdate(dt); if (screens.next != null) { screens.next.alwaysUpdate(dt); } } public void update(float dt) { screens.current.update(dt); if (screens.next != null) { screens.next.update(dt); } } public void render(SpriteBatch batch, OrthographicCamera windowCamera) { screens.next.update(Time.delta); screens.next.renderFrameBuffers(batch); // draw the next screen to the 'to' buffer fbo.to.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.next.render(batch); } fbo.to.end(); // draw the current screen to the 'from' buffer fbo.from.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.current.render(batch); } fbo.from.end(); // draw the transition buffer to the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setShader(shader); batch.setProjectionMatrix(windowCamera.combined); batch.begin(); { tex.from.bind(1); shader.setUniformi("u_texture1", 1); tex.to.bind(0); shader.setUniformi("u_texture", 0); shader.setUniformf("u_percent", percent.floatValue()); batch.setColor(Color.WHITE); batch.draw(tex.to, 0, 0, config.window.width, config.window.height); } batch.end(); batch.setShader(null); } public void startTransition(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) { // current screen is active, so trigger transition to new screen active = true; percent.setValue(0); shader = (type != null) ? type.shader : ZenTransition.random(); Timeline.createSequence() .pushPause(.1f) .push(Tween.call((i, baseTween) -> screens.next = newScreen)) .push(Tween.to(percent, 0, transitionSpeed).target(1)) .push(Tween.call((i, baseTween) -> { screens.current = screens.next; screens.next = null; active = false; }))
package zendo.games.zenlib.screens.transitions; public class Transition implements Disposable { public static final float DEFAULT_SPEED = 0.66f; public boolean active; public MutableFloat percent; public ShaderProgram shader; public final Screens screens = new Screens(); public final FrameBuffers fbo = new FrameBuffers(); public final Textures tex = new Textures(); private final ZenConfig config; public Transition(ZenConfig config) { this.config = config; this.active = false; this.percent = new MutableFloat(0); this.fbo.from = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.fbo.to = new FrameBuffer(Pixmap.Format.RGBA8888, config.window.width, config.window.height, false); this.tex.from = this.fbo.from.getColorBufferTexture(); this.tex.to = this.fbo.to.getColorBufferTexture(); } @Override public void dispose() { screens.dispose(); fbo.dispose(); // no need to dispose textures here, // they are owned by the frame buffers } public void alwaysUpdate(float dt) { screens.current.alwaysUpdate(dt); if (screens.next != null) { screens.next.alwaysUpdate(dt); } } public void update(float dt) { screens.current.update(dt); if (screens.next != null) { screens.next.update(dt); } } public void render(SpriteBatch batch, OrthographicCamera windowCamera) { screens.next.update(Time.delta); screens.next.renderFrameBuffers(batch); // draw the next screen to the 'to' buffer fbo.to.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.next.render(batch); } fbo.to.end(); // draw the current screen to the 'from' buffer fbo.from.begin(); { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); screens.current.render(batch); } fbo.from.end(); // draw the transition buffer to the screen Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.setShader(shader); batch.setProjectionMatrix(windowCamera.combined); batch.begin(); { tex.from.bind(1); shader.setUniformi("u_texture1", 1); tex.to.bind(0); shader.setUniformi("u_texture", 0); shader.setUniformf("u_percent", percent.floatValue()); batch.setColor(Color.WHITE); batch.draw(tex.to, 0, 0, config.window.width, config.window.height); } batch.end(); batch.setShader(null); } public void startTransition(final ZenScreen newScreen, ZenTransition type, float transitionSpeed) { // current screen is active, so trigger transition to new screen active = true; percent.setValue(0); shader = (type != null) ? type.shader : ZenTransition.random(); Timeline.createSequence() .pushPause(.1f) .push(Tween.call((i, baseTween) -> screens.next = newScreen)) .push(Tween.to(percent, 0, transitionSpeed).target(1)) .push(Tween.call((i, baseTween) -> { screens.current = screens.next; screens.next = null; active = false; }))
.start(ZenMain.instance.tween);
1
2023-10-21 19:36:50+00:00
8k
tuna-pizza/GraphXings
src/GraphXings/Legacy/Game/Game.java
[ { "identifier": "CrossingCalculator", "path": "src/GraphXings/Algorithms/CrossingCalculator.java", "snippet": "public class CrossingCalculator\r\n{\r\n /**\r\n * The graph g.\r\n */\r\n private Graph g;\r\n /**\r\n * The positions of the already placed vertices.\r\n */\r\n private HashMap<Vertex, Coordinate> vertexCoordinates;\r\n\r\n /**\r\n * Constructs a CrossingCalculator object.\r\n * @param g The partially embedded graph.\r\n * @param vertexCoordinates The coordinates of the already placed vertices.\r\n */\r\n public CrossingCalculator(Graph g, HashMap<Vertex,Coordinate> vertexCoordinates)\r\n {\r\n this.g = g;\r\n this.vertexCoordinates = vertexCoordinates;\r\n }\r\n\r\n /**\r\n * Computes the number of crossings. The implementation is not efficient and iterates over all pairs of edges resulting in quadratic time.\r\n * @return The number of crossings.\r\n */\r\n public int computeCrossingNumber()\r\n {\r\n int crossingNumber = 0;\r\n for (Edge e1 : g.getEdges())\r\n {\r\n for (Edge e2 : g.getEdges())\r\n {\r\n if (!e1.equals(e2))\r\n {\r\n if (!e1.isAdjacent(e2))\r\n {\r\n if (!vertexCoordinates.containsKey(e1.getS()) || !vertexCoordinates.containsKey(e1.getT()) || !vertexCoordinates.containsKey(e2.getS())|| !vertexCoordinates.containsKey(e2.getT()))\r\n {\r\n continue;\r\n }\r\n Segment s1 = new Segment(vertexCoordinates.get(e1.getS()),vertexCoordinates.get(e1.getT()));\r\n Segment s2 = new Segment(vertexCoordinates.get(e2.getS()),vertexCoordinates.get(e2.getT()));\r\n if (Segment.intersect(s1,s2))\r\n {\r\n crossingNumber++;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return crossingNumber/2;\r\n }\r\n\r\n /**\r\n * Computes the sum of the squared cosines of crossing angles. The implementation is not efficient and iterates over all pairs of edges resulting in quadratic time.\r\n * @return The sum of the squared cosines of crossing angles.\r\n */\r\n public double computeSumOfSquaredCosinesOfCrossingAngles()\r\n {\r\n int comp = 0;\r\n double result = 0;\r\n for (Edge e1 : g.getEdges())\r\n {\r\n for (Edge e2 : g.getEdges())\r\n {\r\n if (!e1.equals(e2))\r\n {\r\n if (!e1.isAdjacent(e2))\r\n {\r\n if (!vertexCoordinates.containsKey(e1.getS()) || !vertexCoordinates.containsKey(e1.getT()) || !vertexCoordinates.containsKey(e2.getS())|| !vertexCoordinates.containsKey(e2.getT()))\r\n {\r\n continue;\r\n }\r\n Segment s1 = new Segment(vertexCoordinates.get(e1.getS()),vertexCoordinates.get(e1.getT()));\r\n Segment s2 = new Segment(vertexCoordinates.get(e2.getS()),vertexCoordinates.get(e2.getT()));\r\n if (Segment.intersect(s1,s2))\r\n {\r\n result+=Segment.squaredCosineOfAngle(s1,s2);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n return result/2;\r\n }\r\n}\r" }, { "identifier": "GameMove", "path": "src/GraphXings/Game/GameMove.java", "snippet": "public class GameMove\r\n{\r\n /**\r\n * The vertex to be placed.\r\n */\r\n private Vertex v;\r\n /**\r\n * The coordinate to place the vertex to.\r\n */\r\n private Coordinate c;\r\n /**\r\n * Constructs a GameMove object.\r\n * @param v The vertex to be placed at c.\r\n * @param c The coordinate where v is to be placed.\r\n */\r\n public GameMove(Vertex v, Coordinate c)\r\n {\r\n this.v = v;\r\n this.c = c;\r\n }\r\n\r\n /**\r\n * Returns the vertex to be placed.\r\n * @return The vertex to be placed.\r\n */\r\n public Vertex getVertex()\r\n {\r\n return v;\r\n }\r\n\r\n /**\r\n * Returns the coordinate to be used.\r\n * @return The coordinate to be used.\r\n */\r\n public Coordinate getCoordinate()\r\n {\r\n return c;\r\n }\r\n}\r" }, { "identifier": "GameState", "path": "src/GraphXings/Game/GameState.java", "snippet": "public class GameState\n{\n\t/**\n\t * The set of vertices contained in the graph.\n\t */\n\tprivate HashSet<Vertex> vertices;\n\t/**\n\t * A HashMap mapping vertices to their coordinates if already placed.\n\t */\n\tprivate HashMap<Vertex, Coordinate> vertexCoordinates;\n\t/**\n\t * A collection of vertices that have already been placed.\n\t */\n\tprivate HashSet<Vertex> placedVertices;\n\t/**\n\t * The width of the drawing.\n\t */\n\tprivate int width;\n\t/**\n\t * The height of the drawing.\n\t */\n\tprivate int height;\n\t/**\n\t * A 0-1 map describing which coordinates have already been used.\n\t */\n\tprivate int[][] usedCoordinates;\n\n\t/**\n\t * Creates a new GameState object describing the initial empty game board.\n\t * @param g The graph to be drawn.\n\t * @param width The width of the game board.\n\t * @param height The height of the game board.\n\t */\n\tpublic GameState(Graph g, int width, int height)\n\t{\n\t\tvertices = new HashSet<>();\n\t\tfor (Vertex v : g.getVertices())\n\t\t{\n\t\t\tvertices.add(v);\n\t\t}\n\t\tvertexCoordinates = new HashMap<>();\n\t\tplacedVertices = new HashSet<>();\n\t\tusedCoordinates = new int[width][height];\n\t\tfor (int x = 0; x < width; x++)\n\t\t{\n\t\t\tfor (int y=0; y < height; y++)\n\t\t\t{\n\t\t\t\tusedCoordinates[x][y] = 0;\n\t\t\t}\n\t\t}\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n\n\t/**\n\t * Checks if a move is valid given the current state of the game.\n\t * @param newMove The potential move to be performed.\n\t * @return True if the move is valid, false if it is invalid.\n\t */\n\tpublic boolean checkMoveValidity(GameMove newMove)\n\t{\n\t\tif (newMove.getVertex() == null ||newMove.getCoordinate() == null)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (!vertices.contains(newMove.getVertex()))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (placedVertices.contains(newMove.getVertex()))\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tint x = newMove.getCoordinate().getX();\n\t\tint y = newMove.getCoordinate().getY();\n\t\tif (x >= width || y >= height)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (usedCoordinates[x][y] != 0)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies changes to the game state according to the new move.\n\t * @param newMove The new move to be performed.\n\t */\n\tpublic void applyMove(GameMove newMove)\n\t{\n\t\tusedCoordinates[newMove.getCoordinate().getX()][newMove.getCoordinate().getY()]=1;\n placedVertices.add(newMove.getVertex());\n vertexCoordinates.put(newMove.getVertex(), newMove.getCoordinate());\n\t}\n\n\t/**\n\t * Gets the set of placed vertices.\n\t * @return The set of placed vertices.\n\t */\n\tpublic HashSet<Vertex> getPlacedVertices()\n\t{\n\t\treturn placedVertices;\n\t}\n\n\t/**\n\t * Gets the coordinates assigned to vertices.\n\t * @return A HashMap describing the coordinate of vertices.\n\t */\n\tpublic HashMap<Vertex, Coordinate> getVertexCoordinates()\n\t{\n\t\treturn vertexCoordinates;\n\t}\n\n\t/**\n\t * Gets a 0-1 map of the already used vertices.\n\t * @return\n\t */\n\tpublic int[][] getUsedCoordinates()\n\t{\n\t\treturn usedCoordinates;\n\t}\n}" }, { "identifier": "Player", "path": "src/GraphXings/Legacy/Algorithms/Player.java", "snippet": "public interface Player\n{\n /**\n * Tells the player to perform the next move where the objective is to create crossings! In a valid move, a vertex of g that is not belonging to placedVertices is positioned onto a coordinate that is\n * not marked with a 1 in usedCoordinates. In addition, only the x-coordinates 0 to width-1 and the y-coordinates 0 to height-1 are allowed.\n * @param g The graph to be drawn.\n * @param vertexCoordinates The coordinates of the already placed vertices. Implemented as a HashMap mapping the Vertex object to its Coordinate.\n * @param gameMoves A sorted list of the already performed game moves.\n * @param usedCoordinates A 0-1 map of the coordinates of the allowed grid. Coordinates that have been used contain a 1 in the map, otherwise 0.\n * @param placedVertices A set of the already placed vertices.\n * @param width The width of the game board.\n * @param height The height of the game board.\n * @return The move to be performed.\n */\n public GameMove maximizeCrossings(Graph g, HashMap<Vertex,Coordinate> vertexCoordinates, List<GameMove> gameMoves, int[][] usedCoordinates, HashSet<Vertex> placedVertices, int width, int height);\n /**\n * Tells the player to perform the next move where the objective is to avoid crossings! In a valid move, a vertex of g that is not belonging to placedVertices is positioned onto a coordinate that is\n * not marked with a 1 in usedCoordinates. In addition, only the x-coordinates 0 to width-1 and the y-coordinates 0 to height-1 are allowed.\n * @param g The graph to be drawn.\n * @param vertexCoordinates The coordinates of the already placed vertices. Implemented as a HashMap mapping the Vertex object to its Coordinate.\n * @param gameMoves A sorted list of the already performed game moves.\n * @param usedCoordinates A 0-1 map of the coordinates of the allowed grid. Coordinates that have been used contain a 1 in the map, otherwise 0.\n * @param placedVertices A set of the already placed vertices.\n * @param width The width of the game board.\n * @param height The height of the game board.\n * @return The move to be performed.\n */\n public GameMove minimizeCrossings(Graph g, HashMap<Vertex,Coordinate> vertexCoordinates, List<GameMove> gameMoves, int[][] usedCoordinates, HashSet<Vertex> placedVertices, int width, int height);\n\n /**\n * Tells the player to get ready for the next round.\n * @param g The graph to be drawn in the next round.\n * @param width The width of the game board.\n * @param height The height of the game board.\n * @param role The role in the next round, either MAX or MIN.\n */\n public void initializeNextRound(Graph g, int width, int height, Role role);\n /**\n * Gets the name of the player.\n * @return The player's name.\n */\n public String getName();\n\n /**\n * An enum describing the role of the player in the next round.\n */\n public enum Role {MAX,MIN};\n}" }, { "identifier": "Graph", "path": "src/GraphXings/Data/Graph.java", "snippet": "public class Graph\r\n{\r\n /**\r\n * The vertex set.\r\n */\r\n private HashSet<Vertex> vertices;\r\n /**\r\n * The edge set.\r\n */\r\n private HashSet<Edge> edges;\r\n /**\r\n * The adjacency list representation.\r\n */\r\n private HashMap<Vertex,HashSet<Edge>> adjacentEdges;\r\n /**\r\n * The number of vertices.\r\n */\r\n private int n;\r\n /**\r\n * The number of edges.\r\n */\r\n private int m;\r\n\r\n /**\r\n * Initializes an empty graph.\r\n */\r\n public Graph()\r\n {\r\n vertices = new HashSet<>();\r\n edges = new HashSet<>();\r\n adjacentEdges = new HashMap<>();\r\n n = 0;\r\n m = 0;\r\n }\r\n\r\n /**\r\n * Adds a vertex to the graph.\r\n * @param v The vertex to be added.\r\n */\r\n public void addVertex(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n vertices.add(v);\r\n adjacentEdges.put(v,new HashSet<>());\r\n n++;\r\n }\r\n }\r\n\r\n /**\r\n * Add an edge to the graph.\r\n * @param e The edge to be added.\r\n * @return True, if the edge was successfully added, false otherwise.\r\n */\r\n public boolean addEdge(Edge e)\r\n {\r\n if (vertices.contains(e.getS())&&vertices.contains(e.getT()))\r\n {\r\n if (!adjacentEdges.get(e.getS()).contains(e))\r\n {\r\n adjacentEdges.get(e.getS()).add(e);\r\n adjacentEdges.get(e.getT()).add(e);\r\n edges.add(e);\r\n m++;\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Gets the vertex set.\r\n * @return An Iterable over the vertex set.\r\n */\r\n public Iterable<Vertex> getVertices()\r\n {\r\n return vertices;\r\n }\r\n\r\n /**\r\n * Returns the edges incident to a specified vertex.\r\n * @param v The vertex whose adjacent edges are queried.\r\n * @return An Iterable over the edges incident to Vertex v.\r\n */\r\n public Iterable<Edge> getIncidentEdges(Vertex v)\r\n {\r\n if (!vertices.contains(v))\r\n {\r\n return null;\r\n }\r\n return adjacentEdges.get(v);\r\n }\r\n\r\n /**\r\n * Returns the edges of the graph.\r\n * @return An Iterable over the edge set.\r\n */\r\n public Iterable<Edge> getEdges()\r\n {\r\n return edges;\r\n }\r\n\r\n /**\r\n * Get the number of vertices.\r\n * @return The number of vertices.\r\n */\r\n public int getN()\r\n {\r\n return n;\r\n }\r\n\r\n /**\r\n * Gets the number of edges.\r\n * @return The number of edges.\r\n */\r\n public int getM()\r\n {\r\n return m;\r\n }\r\n\r\n /**\r\n * Creates a functionally equivalent copy of the graph that uses different references.\r\n * @return A Graph object containing a copy of the graph.\r\n */\r\n public Graph copy()\r\n {\r\n Graph copy = new Graph();\r\n for (Vertex v : vertices)\r\n {\r\n copy.addVertex(v);\r\n }\r\n for (Edge e : edges)\r\n {\r\n copy.addEdge(e);\r\n }\r\n return copy;\r\n }\r\n\r\n /**\r\n * Shuffles the order of vertices in the vertex set.\r\n */\r\n public void shuffleIndices()\r\n {\r\n List<Vertex> toBeShuffled = new ArrayList<>(vertices);\r\n Collections.shuffle(toBeShuffled);\r\n vertices = new HashSet<>(toBeShuffled);\r\n }\r\n\r\n /**\r\n * Provides the adjacency list representation of the graph.\r\n * @return The adjacency list representation.\r\n */\r\n @Override\r\n public String toString()\r\n {\r\n String out = \"\";\r\n for (Vertex v : vertices)\r\n {\r\n out += v.getId() + \": [\";\r\n for (Edge e: adjacentEdges.get(v))\r\n {\r\n out += \"(\" + e.getS().getId() +\",\" + e.getT().getId() +\"),\";\r\n }\r\n out += \"]\\n\";\r\n }\r\n return out;\r\n }\r\n}\r" } ]
import GraphXings.Algorithms.CrossingCalculator; import GraphXings.Game.GameMove; import GraphXings.Game.GameState; import GraphXings.Legacy.Algorithms.Player; import GraphXings.Data.Graph; import java.util.*;
4,762
package GraphXings.Legacy.Game; /** * A class for managing a game of GraphXings! */ public class Game { /** * Decides whether or not data is copied before being passed on to players. */ public static boolean safeMode = true; /** * The width of the game board. */ private int width; /** * The height of the game board. */ private int height; /** * The graph to be drawn. */ private Graph g; /** * The first player. */ private Player player1; /** * The second player. */ private Player player2; /** * The time limit for players. */ private long timeLimit; /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. */ public Game(Graph g, int width, int height, Player player1, Player player2) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = Long.MAX_VALUE; } /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. * @param timeLimit The time limit for players. */ public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = timeLimit; } /** * Runs the full game of GraphXings. * @return Provides a GameResult Object containing the game's results. */ public GameResult play() { Random r = new Random(System.nanoTime()); if (r.nextBoolean()) { Player swap = player1; player1 = player2; player2 = swap; } try { player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX); player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN); int crossingsGame1 = playRound(player1, player2); player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN); player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX); int crossingsGame2 = playRound(player2, player1); return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false); } catch (InvalidMoveException ex) { System.err.println(ex.getCheater().getName() + " cheated!"); if (ex.getCheater().equals(player1)) { return new GameResult(0, 0, player1, player2,true,false,false,false); } else if (ex.getCheater().equals(player2)) { return new GameResult(0,0,player1,player2,false,true,false,false); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } catch (TimeOutException ex) { System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!"); if (ex.getTimeOutPlayer().equals(player1)) { return new GameResult(0, 0, player1, player2,false,false,true,false); } else if (ex.getTimeOutPlayer().equals(player2)) { return new GameResult(0,0,player1,player2,false,false,false,true); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } } /** * Plays a single round of the game. * @param maximizer The player with the goal to maximize the number of crossings. * @param minimizer The player with the goal to minimize the number of crossings * @return The number of crossings yielded in the final drawing. * @throws InvalidMoveException An exception caused by cheating. */ private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException { int turn = 0;
package GraphXings.Legacy.Game; /** * A class for managing a game of GraphXings! */ public class Game { /** * Decides whether or not data is copied before being passed on to players. */ public static boolean safeMode = true; /** * The width of the game board. */ private int width; /** * The height of the game board. */ private int height; /** * The graph to be drawn. */ private Graph g; /** * The first player. */ private Player player1; /** * The second player. */ private Player player2; /** * The time limit for players. */ private long timeLimit; /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. */ public Game(Graph g, int width, int height, Player player1, Player player2) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = Long.MAX_VALUE; } /** * Instantiates a game of GraphXings. * @param g The graph to be drawn. * @param width The width of the game board. * @param height The height of the game board. * @param player1 The first player. Plays as the maximizer in round one. * @param player2 The second player. Plays as the minimizer in round one. * @param timeLimit The time limit for players. */ public Game(Graph g, int width, int height, Player player1, Player player2, long timeLimit) { this.g = g; this.width = width; this.height = height; this.player1 = player1; this.player2 = player2; this.timeLimit = timeLimit; } /** * Runs the full game of GraphXings. * @return Provides a GameResult Object containing the game's results. */ public GameResult play() { Random r = new Random(System.nanoTime()); if (r.nextBoolean()) { Player swap = player1; player1 = player2; player2 = swap; } try { player1.initializeNextRound(g.copy(),width,height, Player.Role.MAX); player2.initializeNextRound(g.copy(),width,height, Player.Role.MIN); int crossingsGame1 = playRound(player1, player2); player1.initializeNextRound(g.copy(),width,height, Player.Role.MIN); player2.initializeNextRound(g.copy(),width,height, Player.Role.MAX); int crossingsGame2 = playRound(player2, player1); return new GameResult(crossingsGame1,crossingsGame2,player1,player2,false,false,false,false); } catch (InvalidMoveException ex) { System.err.println(ex.getCheater().getName() + " cheated!"); if (ex.getCheater().equals(player1)) { return new GameResult(0, 0, player1, player2,true,false,false,false); } else if (ex.getCheater().equals(player2)) { return new GameResult(0,0,player1,player2,false,true,false,false); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } catch (TimeOutException ex) { System.err.println(ex.getTimeOutPlayer().getName() + " ran out of time!"); if (ex.getTimeOutPlayer().equals(player1)) { return new GameResult(0, 0, player1, player2,false,false,true,false); } else if (ex.getTimeOutPlayer().equals(player2)) { return new GameResult(0,0,player1,player2,false,false,false,true); } else { return new GameResult(0,0,player1,player2,false,false,false,false); } } } /** * Plays a single round of the game. * @param maximizer The player with the goal to maximize the number of crossings. * @param minimizer The player with the goal to minimize the number of crossings * @return The number of crossings yielded in the final drawing. * @throws InvalidMoveException An exception caused by cheating. */ private int playRound(Player maximizer, Player minimizer) throws InvalidMoveException, TimeOutException { int turn = 0;
GameState gs = new GameState(g,width,height);
2
2023-10-18 12:11:38+00:00
8k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/FxdKernel.java
[ { "identifier": "FxdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdRecord.java", "snippet": "public abstract class FxdRecord implements Serializable {\n\n /**\n * Time at record creation. [ns]\n */\n protected final long timeStamp;\n /**\n * Position at record creation.\n */\n protected final GeoPoint position;\n /**\n * Connection at record creation.\n */\n protected final String connectionId;\n /**\n * Speed at record creation. [m/s]\n */\n protected final double speed;\n /**\n * Distance driven on current connection. [m]\n */\n protected final double offset;\n /**\n * Heading of the unit. [°]\n */\n protected final double heading;\n\n /**\n * A {@link FxdRecord} represents a snapshot of a units current spatio-temporal data, including time, position, and connection id.\n * Based on a collection of these records, different traffic state estimation (TSE) algorithms can be applied\n */\n protected FxdRecord(long timeStamp, GeoPoint position, String connectionId, double speed, double offset, double heading) {\n this.timeStamp = timeStamp;\n this.position = position;\n this.connectionId = connectionId;\n this.speed = speed;\n this.offset = offset;\n this.heading = heading;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public GeoPoint getPosition() {\n return position;\n }\n\n public String getConnectionId() {\n return connectionId;\n }\n\n public double getSpeed() {\n return speed;\n }\n\n public double getOffset() {\n return offset;\n }\n\n public double getHeading() {\n return heading;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, SHORT_PREFIX_STYLE)\n .appendSuper(super.toString())\n .append(\"timestamp\", timeStamp)\n .append(\"position\", position)\n .append(\"connectionId\", connectionId)\n .append(\"speed\", speed)\n .append(\"offset\", offset)\n .append(\"heading\", heading)\n .toString();\n }\n\n /**\n * Method that estimates the size in Bytes for an {@link FxdRecord}.\n */\n public long calculateRecordSize() {\n return 4L // time stamp\n + 8L * 3L // position (three doubles: lat, lon, ele)\n + 10L // average connection id 10 chars, 1 byte per char\n + 8L // speed\n + 8L // offset\n + 8L; // heading\n }\n\n /**\n * Interface for the record builder class. Concrete implementations will extend the {@link AbstractRecordBuilder}-class.\n *\n * @param <BuilderT> concrete type of the builder\n * @param <RecordT> concrete type of the record\n */\n public interface RecordBuilder<BuilderT extends RecordBuilder<BuilderT, RecordT>, RecordT extends FxdRecord> {\n\n BuilderT withOffset(double offset);\n\n BuilderT withSpeed(double speed);\n\n BuilderT withHeading(double heading);\n }\n}" }, { "identifier": "FxdTraversal", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FxdTraversal.java", "snippet": "public abstract class FxdTraversal<RecordT extends FxdRecord, TraversalT extends FxdTraversal<RecordT, TraversalT>> {\n\n protected final String connectionId;\n protected final List<RecordT> traversal;\n /**\n * Last record of previous traversal.\n */\n protected final RecordT previousRecord;\n /**\n * First record of previous following traversal.\n */\n protected final RecordT followingRecord;\n\n /**\n * Constructor for an {@link FxdTraversal}.\n */\n public FxdTraversal(String connectionId, List<RecordT> traversal, @Nullable RecordT previousRecord, @Nullable RecordT followingRecord) {\n this.connectionId = connectionId;\n this.traversal = traversal;\n this.previousRecord = previousRecord;\n this.followingRecord = followingRecord;\n }\n\n /**\n * Returns the id of the traversed connection.\n */\n public String getConnectionId() {\n return connectionId;\n }\n\n /**\n * Returns a list of all {@link RecordT Records} on the traversed connection.\n */\n public List<RecordT> getTraversal() {\n return traversal;\n }\n\n /**\n * Returns the last record of the previous traversal.\n * Note: {@link RecordT#getConnectionId()} will be different from {@link #getConnectionId()}\n */\n @Nullable\n public RecordT getPreviousRecord() {\n return previousRecord;\n }\n\n /**\n * Returns the first record of the following traversal.\n * Note: {@link RecordT#getConnectionId()} will be different from {@link #getConnectionId()}\n */\n @Nullable\n public RecordT getFollowingRecord() {\n return followingRecord;\n }\n\n /**\n * Method to create a deep copy of the {@link FxdTraversal}, needs to be implemented by child classes.\n */\n public abstract TraversalT copy();\n}" }, { "identifier": "FxdUpdateMessage", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/messages/FxdUpdateMessage.java", "snippet": "public abstract class FxdUpdateMessage<RecordT extends FxdRecord> extends V2xMessage {\n\n private final long timeStamp;\n private final SortedMap<Long, RecordT> records;\n private final boolean isFinal;\n\n protected FxdUpdateMessage(MessageRouting messageRouting, long timeStamp, SortedMap<Long, RecordT> records, boolean isFinal) {\n super(messageRouting);\n this.timeStamp = timeStamp;\n this.records = records;\n this.isFinal = isFinal;\n }\n\n public long getTimeStamp() {\n return timeStamp;\n }\n\n public final SortedMap<Long, RecordT> getRecords() {\n // always return copy of records, in case list is processed by multiple processors\n return Maps.newTreeMap(records);\n }\n\n public boolean isFinal() {\n return isFinal;\n }\n\n @Nonnull\n @Override\n public EncodedPayload getPayLoad() {\n return new EncodedPayload(calculateMessageLength());\n }\n\n /**\n * Method that estimates the length of an average {@link FxdUpdateMessage UpdateMessage} adding the baseline length of required fields with\n * the length of the specialized {@link FxdUpdateMessage FxdUpdateMessages}.\n */\n public long calculateMessageLength() {\n return 10 // \"header size\"\n + 8 // for time stamp\n + 1 // for isFinal flag\n + getRecords().values().stream().mapToLong(FxdRecord::calculateRecordSize).sum(); // size for each record\n }\n\n /**\n * Interface for the builder of {@link FxdUpdateMessage FxdUpdateMessages}.\n *\n * @param <BuilderT> concrete type of the builder\n * @param <RecordT> concrete type of the records\n * @param <UpdateT> concrete type of the updates being built\n */\n interface FxdUpdateMessageBuilder<\n BuilderT extends FxdUpdateMessageBuilder<BuilderT, RecordT, UpdateT>,\n RecordT extends FxdRecord,\n UpdateT extends FxdUpdateMessage<RecordT>> {\n\n BuilderT addRecords(SortedMap<Long, RecordT> records);\n\n BuilderT isFinal();\n }\n\n}" }, { "identifier": "CFxdReceiverApp", "path": "src/main/java/com/dcaiti/mosaic/app/tse/config/CFxdReceiverApp.java", "snippet": "public class CFxdReceiverApp<\n RecordT extends FxdRecord,\n TraversalT extends FxdTraversal<RecordT, TraversalT>,\n UpdateT extends FxdUpdateMessage<RecordT>> {\n /**\n * Within this period the {@link FxdKernel FxdKernel} will look for outdated/inactive sender trajectories and\n * remove them. [ns]\n */\n @JsonAdapter(TimeFieldAdapter.NanoSeconds.class)\n public long unitRemovalInterval = 30 * TIME.MINUTE;\n /**\n * Time after which a unit is treated as outdated.\n * This time is measured from the reception of newest received {@link FxdRecord FxdRecord} for each unit.\n * If a unit hasn't sent a message for this time, it will be removed with the next {@link #unitRemovalInterval}. [ns]\n */\n @JsonAdapter(TimeFieldAdapter.NanoSeconds.class)\n public long unitExpirationTime = 60 * TIME.MINUTE;\n /**\n * A list of configurable {@link TraversalBasedProcessor TraversalBasedProcessors}\n * which are managed by the {@link FxdKernel FxdKernel}.\n */\n public List<TraversalBasedProcessor<RecordT, TraversalT>> traversalBasedProcessors;\n /**\n * A list of configurable {@link TimeBasedProcessor TimeBasedProcessors} which are managed by the\n * {@link FxdKernel FxdKernel}.\n */\n public List<TimeBasedProcessor<RecordT, UpdateT>> timeBasedProcessors;\n /**\n * A list of configurable {@link MessageBasedProcessor MessageBasedProcessors}\n * which are managed by the {@link FxdKernel FxdKernel}.\n */\n public List<MessageBasedProcessor> messageBasedProcessors;\n}" }, { "identifier": "ExpiredUnitRemovalEvent", "path": "src/main/java/com/dcaiti/mosaic/app/tse/events/ExpiredUnitRemovalEvent.java", "snippet": "public class ExpiredUnitRemovalEvent extends Event {\n public ExpiredUnitRemovalEvent(long time, @Nonnull EventProcessor processor) {\n super(time, processor);\n }\n}" }, { "identifier": "FxdProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/FxdProcessor.java", "snippet": "public interface FxdProcessor {\n\n void initialize(UnitLogger logger);\n\n /**\n * Finalize all processor computations and clear used memory.\n *\n * @param shutdownTime time of shutdown\n */\n void shutdown(long shutdownTime);\n}" }, { "identifier": "MessageBasedProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/MessageBasedProcessor.java", "snippet": "@JsonAdapter(MessageBasedProcessorTypeAdapterFactory.class)\npublic interface MessageBasedProcessor extends FxdProcessor {\n\n /**\n * Handles the reception of {@link V2xMessage V2xMessages} that clear the {@link #isInstanceOfMessage} check.\n * Furthermore, this method allows building a response, which will be transmitted to the sender of the\n * original message.\n *\n * @param message the message container including a {@link V2xMessage} and additional information\n * @param responseRouting {@link MessageRouting} pointing back to the original sender (Required for building the response)\n * @return A response in the form of a {@link V2xMessage}\n */\n V2xMessage handleReceivedMessage(ReceivedV2xMessage message, MessageRouting responseRouting);\n\n /**\n * This method is used to validate that a {@link MessageBasedProcessor} can handle the specified message.\n * Implementations will usually look like {@code message.getMessage() instanceof <message-type>}\n *\n * @param message the message to check\n * @return a flag indicating whether the message can be processed or not\n */\n boolean isInstanceOfMessage(ReceivedV2xMessage message);\n}" }, { "identifier": "TimeBasedProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/TimeBasedProcessor.java", "snippet": "@JsonAdapter(TimeBasedProcessorTypeAdapterFactory.class)\npublic abstract class TimeBasedProcessor<RecordT extends FxdRecord, UpdateT extends FxdUpdateMessage<RecordT>> implements FxdProcessor {\n\n /**\n * Sets the time interval at which the {@link #triggerEvent} function is being called.\n */\n @JsonAdapter(TimeFieldAdapter.NanoSeconds.class)\n public long triggerInterval = 30 * TIME.MINUTE;\n /**\n * Logger class that allows writing to application logs.\n */\n protected UnitLogger logger;\n private long nextTriggerTime;\n private long previousTriggerTime;\n\n @Override\n public void initialize(UnitLogger logger) {\n this.logger = logger;\n previousTriggerTime = 0;\n nextTriggerTime = 0;\n }\n\n public long getAndIncrementNextTriggerTime() {\n previousTriggerTime = nextTriggerTime;\n return nextTriggerTime += triggerInterval;\n }\n\n public long getPreviousTriggerTime() {\n return previousTriggerTime;\n }\n\n public abstract String getIdentifier();\n\n public abstract void handleUpdate(UpdateT update);\n\n /**\n * This method will handle the execution of the event.\n * And will be called by the kernel based on {@link #triggerInterval}.\n *\n * @param eventTime simulation time at event trigger\n */\n public abstract void triggerEvent(long eventTime);\n\n\n @SuppressWarnings(\"rawtypes\")\n public static String createIdentifier(Class<? extends TimeBasedProcessor> processorClass) {\n return ClassUtils.getShortClassName(processorClass);\n }\n}" }, { "identifier": "TraversalBasedProcessor", "path": "src/main/java/com/dcaiti/mosaic/app/tse/processors/TraversalBasedProcessor.java", "snippet": "@JsonAdapter(TraversalBasedProcessorTypeAdapterFactory.class)\npublic interface TraversalBasedProcessor<RecordT extends FxdRecord, TraversalT extends FxdTraversal<RecordT, TraversalT>>\n extends FxdProcessor {\n\n void onConnectionTraversal(String unitId, TraversalT traversal);\n}" } ]
import com.dcaiti.mosaic.app.fxd.data.FxdRecord; import com.dcaiti.mosaic.app.fxd.data.FxdTraversal; import com.dcaiti.mosaic.app.fxd.messages.FxdUpdateMessage; import com.dcaiti.mosaic.app.tse.config.CFxdReceiverApp; import com.dcaiti.mosaic.app.tse.events.ExpiredUnitRemovalEvent; import com.dcaiti.mosaic.app.tse.processors.FxdProcessor; import com.dcaiti.mosaic.app.tse.processors.MessageBasedProcessor; import com.dcaiti.mosaic.app.tse.processors.TimeBasedProcessor; import com.dcaiti.mosaic.app.tse.processors.TraversalBasedProcessor; import org.eclipse.mosaic.fed.application.ambassador.simulation.communication.ReceivedV2xMessage; import org.eclipse.mosaic.fed.application.ambassador.util.UnitLogger; import org.eclipse.mosaic.lib.objects.v2x.MessageRouting; import org.eclipse.mosaic.lib.objects.v2x.V2xMessage; import org.eclipse.mosaic.lib.util.scheduling.Event; import org.eclipse.mosaic.lib.util.scheduling.EventManager; import org.eclipse.mosaic.lib.util.scheduling.EventProcessor; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.stream.Collectors; import javax.annotation.Nullable;
3,835
/* * Copyright (c) 2021 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: [email protected] */ package com.dcaiti.mosaic.app.tse; /** * The {@link FxdKernel} and all its inheriting classes handle traversal recognition, event management, initializing and execution of * the {@link FxdProcessor FxdProcessors}. * * @param <RecordT> Record type (extension of {@link FxdRecord}) containing all spatio-temporal information that units * periodically transmit to the server * @param <TraversalT> Traversal type (extension of {@link FxdTraversal}) containing the traversal of a single connection consisting of a * list of {@link RecordT Records}. * @param <UpdateT> Updated type (extension of {@link FxdUpdateMessage}) representing the actual messages send by units. * The most generic implementation contains a collection of records sampled by a unit. * @param <ConfigT> Type of the configuration (extension of {@link CFxdReceiverApp}) in its generic form this class contains * configuration parameters for the expired unit removal and the configured {@link FxdProcessor FxdProcessors}. */ public abstract class FxdKernel< RecordT extends FxdRecord,
/* * Copyright (c) 2021 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: [email protected] */ package com.dcaiti.mosaic.app.tse; /** * The {@link FxdKernel} and all its inheriting classes handle traversal recognition, event management, initializing and execution of * the {@link FxdProcessor FxdProcessors}. * * @param <RecordT> Record type (extension of {@link FxdRecord}) containing all spatio-temporal information that units * periodically transmit to the server * @param <TraversalT> Traversal type (extension of {@link FxdTraversal}) containing the traversal of a single connection consisting of a * list of {@link RecordT Records}. * @param <UpdateT> Updated type (extension of {@link FxdUpdateMessage}) representing the actual messages send by units. * The most generic implementation contains a collection of records sampled by a unit. * @param <ConfigT> Type of the configuration (extension of {@link CFxdReceiverApp}) in its generic form this class contains * configuration parameters for the expired unit removal and the configured {@link FxdProcessor FxdProcessors}. */ public abstract class FxdKernel< RecordT extends FxdRecord,
TraversalT extends FxdTraversal<RecordT, TraversalT>,
1
2023-10-23 16:39:40+00:00
8k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/blocks/PrimogemCraftBlocks.java
[ { "identifier": "AgnidusAgateBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/agnidus/AgnidusAgateBlock.java", "snippet": "public class AgnidusAgateBlock extends Block {\n public AgnidusAgateBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GLASS).strength(3f, 18f).requiresCorrectToolForDrops().noOcclusion().isRedstoneConductor((bs, br, bp) -> false));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n\n @Override\n public @NotNull VoxelShape getVisualShape(BlockState state, BlockGetter world, BlockPos pos, CollisionContext context) {\n return Shapes.empty();\n }\n\n @Override\n public void stepOn(Level world, BlockPos pos, BlockState blockstate, Entity entity) {\n super.stepOn(world, pos, blockstate, entity);\n entity.setSecondsOnFire(15);\n }\n}" }, { "identifier": "AgnidusAgateOreBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/agnidus/AgnidusAgateOreBlock.java", "snippet": "public class AgnidusAgateOreBlock extends Block {\n public AgnidusAgateOreBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.NETHER_ORE).strength(1f, 5f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.agnidus_agate_ore.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "NagadusEmeraldBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/nagadus/NagadusEmeraldBlock.java", "snippet": "public class NagadusEmeraldBlock extends Block {\n public NagadusEmeraldBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GLASS).strength(3f, 15f));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "NagadusEmeraldOreBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/nagadus/NagadusEmeraldOreBlock.java", "snippet": "public class NagadusEmeraldOreBlock extends Block implements BlockExtension {\n public NagadusEmeraldOreBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GRAVEL).strength(2f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.nagadus_emerald_ore.line1\"));\n }\n\n @Override\n public boolean canSustainPlant(BlockState state, BlockGetter world, BlockPos pos, Direction facing) {\n return true;\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n\n @Override\n public void onDestroyedByPlayer(Level level, Player player, BlockPos pos, BlockState state, BlockEntity blockEntity, ItemStack tool) {\n if (!level.isClientSide()) {\n level.playSound(null, pos, SoundEvents.GLASS_BREAK, SoundSource.BLOCKS, (float) 0.5, 1);\n }\n }\n}" }, { "identifier": "PrithvaTopazBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/prithva/PrithvaTopazBlock.java", "snippet": "public class PrithvaTopazBlock extends Block {\n public PrithvaTopazBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.GLASS).strength(3f, 100f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.prithva_topaz_block.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "PrithvaTopazOreBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/prithva/PrithvaTopazOreBlock.java", "snippet": "public class PrithvaTopazOreBlock extends Block {\n public PrithvaTopazOreBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.STONE).strength(4f, 15f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.prithva_topaz_ore.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VajradaAmethystBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vajrada/VajradaAmethystBlock.java", "snippet": "public class VajradaAmethystBlock extends Block {\n public VajradaAmethystBlock() {\n super(BlockBehaviour.Properties.of().sound(SoundType.GLASS).strength(3f, 11f));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VajradaAmethystOre", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vajrada/VajradaAmethystOre.java", "snippet": "public class VajradaAmethystOre extends Block {\n public VajradaAmethystOre() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.STONE).strength(3f, 10f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.vajrada_amethyst_ore.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VayudaTurquoiseGemstoneBlock", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vayuda/VayudaTurquoiseGemstoneBlock.java", "snippet": "public class VayudaTurquoiseGemstoneBlock extends Block {\n public VayudaTurquoiseGemstoneBlock() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.GLASS).strength(3f, 10f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.vayuda_turquoise_gemstone_block.line1\"));\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "VayudaTurquoiseGemstoneOre", "path": "src/main/java/com/primogemstudio/primogemcraft/blocks/instances/materials/vayuda/VayudaTurquoiseGemstoneOre.java", "snippet": "public class VayudaTurquoiseGemstoneOre extends Block {\n public VayudaTurquoiseGemstoneOre() {\n super(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.GLASS).strength(3f, 10f).requiresCorrectToolForDrops());\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, BlockGetter world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.vayuda_turquoise_gemstone_ore.line1\"));\n }\n\n @Override\n public boolean skipRendering(BlockState state, BlockState adjacentBlockState, Direction side) {\n return adjacentBlockState.getBlock() == this || super.skipRendering(state, adjacentBlockState, side);\n }\n\n @Override\n public int getLightBlock(BlockState state, BlockGetter worldIn, BlockPos pos) {\n return 15;\n }\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/com/primogemstudio/primogemcraft/PrimogemCraftFabric.java", "snippet": "public static final String MOD_ID = \"primogemcraft\";" } ]
import com.primogemstudio.primogemcraft.blocks.instances.*; import com.primogemstudio.primogemcraft.blocks.instances.dendrocore.*; import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.agnidus.AgnidusAgateOreBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.nagadus.NagadusEmeraldOreBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.prithva.PrithvaTopazOreBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.vajrada.VajradaAmethystOre; import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneBlock; import com.primogemstudio.primogemcraft.blocks.instances.materials.vayuda.VayudaTurquoiseGemstoneOre; import com.primogemstudio.primogemcraft.blocks.instances.mora.*; import com.primogemstudio.primogemcraft.blocks.instances.planks.*; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.renderer.RenderType; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraft.world.level.block.state.properties.NoteBlockInstrument; import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID;
4,517
package com.primogemstudio.primogemcraft.blocks; public class PrimogemCraftBlocks { public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock()); public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock()); public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre()); public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops())); public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock()); public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock()); public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock()); public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock()); public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock()); public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock()); public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock()); public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock()); public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock()); public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock()); public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock()); public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock()); public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock()); public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock()); public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock()); public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock()); public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock()); public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock()); public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock()); public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre()); public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock()); public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre()); public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem("vajrada_amethyst_block", new VajradaAmethystBlock()); public static final March7thStatueBlock MARCH_7TH_STATUE_BLOCK = registerWithItem("march_7th_statue", new March7thStatueBlock()); public static final NagadusEmeraldOreBlock NAGADUS_EMERALD_ORE_BLOCK = registerWithItem("nagadus_emerald_ore", new NagadusEmeraldOreBlock());
package com.primogemstudio.primogemcraft.blocks; public class PrimogemCraftBlocks { public static final DendroCoreBlock DENDRO_CORE_BLOCK = registerWithItem("dendro_core_block", new DendroCoreBlock()); public static final PrimogemBlock PRIMOGEM_BLOCK = registerWithItem("primogem_block", new PrimogemBlock()); public static final PrimogemOre PRIMOGEM_ORE = registerWithItem("primogem_ore", new PrimogemOre()); public static final Block DEEP_SLATE_PRIMOGEM_ORE = registerWithItem("deep_slate_primogem_ore", new Block(BlockBehaviour.Properties.of().instrument(NoteBlockInstrument.BASEDRUM).sound(SoundType.POLISHED_DEEPSLATE).strength(5f, 10f).lightLevel(s -> 1).requiresCorrectToolForDrops())); public static final IntertwinedFateBlock INTERTWINED_FATE_BLOCK = registerWithItem("intertwined_fate_block", new IntertwinedFateBlock()); public static final MoraBunchBlock MORA_BUNCH_BLOCK = registerWithItem("mora_bunch_block", new MoraBunchBlock()); public static final MoraBlock MORA_BLOCK = registerWithItem("mora_block", new MoraBlock()); public static final ExquisiteMoraBlock EXQUISITE_MORA_BLOCK = registerWithItem("exquisite_mora_block", new ExquisiteMoraBlock()); public static final CheapMoraBlock CHEAP_MORA_BLOCK = registerWithItem("cheap_mora_block", new CheapMoraBlock()); public static final CheapMoraSlabBlock CHEAP_MORA_SLAB_BLOCK = registerWithItem("cheap_mora_slab", new CheapMoraSlabBlock()); public static final CheapMoraStairBlock CHEAP_MORA_STAIR_BLOCK = registerWithItem("cheap_mora_stair", new CheapMoraStairBlock()); public static final CheapMoraWallBlock CHEAP_MORA_WALL_BLOCK = registerWithItem("cheap_mora_wall", new CheapMoraWallBlock()); public static final TeyvatPlanksBlock TEYVAT_PLANKS_BLOCK = registerWithItem("teyvat_planks", new TeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final BlueTeyvatPlanksBlock BLUE_TEYVAT_PLANKS_BLOCK = registerWithItem("blue_teyvat_planks", new BlueTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock BLUE_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("blue_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock BLUE_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("blue_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock BLUE_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("blue_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock BLUE_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("blue_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final PinkTeyvatPlanksBlock PINK_TEYVAT_PLANKS_BLOCK = registerWithItem("pink_teyvat_planks", new PinkTeyvatPlanksBlock()); public static final TeyvatPlankSlabBlock PINK_TEYVAT_PLANK_SLAB_BLOCK = registerWithItem("pink_teyvat_plank_slab", new TeyvatPlankSlabBlock()); public static final TeyvatPlankStairBlock PINK_TEYVAT_PLANK_STAIR_BLOCK = registerWithItem("pink_teyvat_plank_stair", new TeyvatPlankStairBlock()); public static final TeyvatPlankFenceBlock PINK_TEYVAT_PLANK_FENCE_BLOCK = registerWithItem("pink_teyvat_plank_fence", new TeyvatPlankFenceBlock()); public static final TeyvatPlankFenceGateBlock PINK_TEYVAT_PLANK_FENCE_GATE_BLOCK = registerWithItem("pink_teyvat_plank_fence_gate", new TeyvatPlankFenceGateBlock()); public static final CharCoalBlock CHAR_COAL_BLOCK = registerWithItem("charcoal_block", new CharCoalBlock()); public static final RustedPlankBlock RUSTED_PLANK_BLOCK = registerWithItem("rusted_plank", new RustedPlankBlock()); public static final RustedPlankStairsBlock RUSTED_PLANK_STAIR_BLOCK = registerWithItem("rusted_plank_stairs", new RustedPlankStairsBlock()); public static final RustIronBarBlock RUST_IRON_BAR_BLOCK = registerWithItem("rust_iron_bar", new RustIronBarBlock()); public static final DendroCorePlanksBlock DENDRO_CORE_PLANKS_BLOCK = registerWithItem("dendro_core_planks", new DendroCorePlanksBlock()); public static final DendroCorePlankSlabBlock DENDRO_CORE_PLANK_SLAB_BLOCK = registerWithItem("dendro_core_plank_slab", new DendroCorePlankSlabBlock()); public static final DendroCorePlankStairsBlock DENDRO_CORE_PLANK_STAIRS_BLOCK = registerWithItem("dendro_core_plank_stairs", new DendroCorePlankStairsBlock()); public static final DendroCorePlankPressurePlateBlock DENDRO_CORE_PLANK_PRESSURE_PLATE_BLOCK = registerWithItem("dendro_core_plank_pressure_plate", new DendroCorePlankPressurePlateBlock()); public static final DendroCodePlankButtonBlock DENDRO_CORE_PLANK_BUTTON_BLOCK = registerWithItem("dendro_core_plank_button", new DendroCodePlankButtonBlock()); public static final DendroCorePlanksFenceGateBlock DENDRO_CORE_PLANK_FENCE_GATE_BLOCK = registerWithItem("dendro_core_plank_fence_gate", new DendroCorePlanksFenceGateBlock()); public static final DendroCorePlankFenceBlock DENDRO_CORE_PLANK_FENCE_BLOCK = registerWithItem("dendro_core_plank_fence", new DendroCorePlankFenceBlock()); public static final VayudaTurquoiseGemstoneOre VAYUDA_TURQUOISE_GEMSTONE_ORE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_ore", new VayudaTurquoiseGemstoneOre()); public static final VayudaTurquoiseGemstoneBlock VAYUDA_TURQUOISE_GEMSTONE_BLOCK = registerWithItem("vayuda_turquoise_gemstone_block", new VayudaTurquoiseGemstoneBlock()); public static final VajradaAmethystOre VAJRADA_AMETHYST_ORE_BLOCK = registerWithItem("vajrada_amethyst_ore", new VajradaAmethystOre()); public static final VajradaAmethystBlock VAJRADA_AMETHYST_BLOCK = registerWithItem("vajrada_amethyst_block", new VajradaAmethystBlock()); public static final March7thStatueBlock MARCH_7TH_STATUE_BLOCK = registerWithItem("march_7th_statue", new March7thStatueBlock()); public static final NagadusEmeraldOreBlock NAGADUS_EMERALD_ORE_BLOCK = registerWithItem("nagadus_emerald_ore", new NagadusEmeraldOreBlock());
public static final NagadusEmeraldBlock NAGADUS_EMERALD_BLOCK = registerWithItem("nagadus_emerald_block", new NagadusEmeraldBlock());
2
2023-10-15 08:07:06+00:00
8k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/DefaultDataEditorPanel.java
[ { "identifier": "ComboBoxItem", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/EditorComboBox.java", "snippet": "public static class ComboBoxItem\n{\n private String str;\n\n public ComboBoxItem(String str)\n {\n this.str= str;\n }\n\n public ComboBoxItem(int num)\n {\n str= \"\" + num;\n }\n\n public void setName(String str) {this.str= str;}\n\n @Override\n public String toString()\n {\n return str;\n }\n}" }, { "identifier": "EditorComboBox", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/EditorComboBox.java", "snippet": "public class EditorComboBox extends JComboBox<EditorComboBox.ComboBoxItem>\n{\n private final ComboBoxSearchable searchable;\n\n public EditorComboBox()\n {\n super();\n searchable= new ComboBoxSearchable(this);\n }\n\n public EditorComboBox(String[] items)\n {\n super(Arrays.stream(items).map(ComboBoxItem::new).toArray(ComboBoxItem[]::new));\n searchable= new ComboBoxSearchable(this);\n }\n\n public EditorComboBox(ComboBoxItem[] model)\n {\n super(model);\n searchable= new ComboBoxSearchable(this);\n }\n\n public EditorComboBox(ComboBoxModel<ComboBoxItem> model)\n {\n super(model);\n searchable= new ComboBoxSearchable(this);\n }\n\n public static class ComboBoxItem\n {\n private String str;\n\n public ComboBoxItem(String str)\n {\n this.str= str;\n }\n\n public ComboBoxItem(int num)\n {\n str= \"\" + num;\n }\n\n public void setName(String str) {this.str= str;}\n\n @Override\n public String toString()\n {\n return str;\n }\n }\n}" }, { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetExportIcon;\n public static final FlatSVGIcon sheetImportIcon;\n public static final FlatSVGIcon rowRemoveIcon;\n public static final FlatSVGIcon rowInsertIcon;\n public static final FlatSVGIcon searchIcon;\n public static final FlatSVGIcon clipboardIcon;\n public static final FlatSVGIcon copyIcon;\n\n public static final Color[] typeColors = new Color[]{new Color(201, 201, 201),\n new Color(173, 96, 94),\n new Color(165, 218, 218),\n new Color(184, 121, 240),\n new Color(200, 164, 117),\n new Color(184, 146, 48),\n new Color(157, 195, 132),\n new Color(139, 125, 190),\n new Color(153, 153, 153),\n new Color(230, 199, 255),\n new Color(189, 75, 49),\n new Color(88, 132, 225),\n new Color(120, 166, 90),\n new Color(249, 218, 120),\n new Color(223, 151, 143),\n new Color(70, 185, 185),\n new Color(98, 98, 246),\n new Color(102, 102, 102),\n };\n\n public static final Color[] darkModeTypeColors = new Color[]{new Color(116, 116, 116),\n new Color(130, 72, 71),\n new Color(101, 133, 133),\n new Color(86, 57, 112),\n new Color(157, 129, 92),\n new Color(99, 79, 26),\n new Color(123, 152, 103),\n new Color(77, 69, 105),\n new Color(68, 68, 68),\n new Color(192, 166, 212), //\n new Color(61, 24, 16), //\n new Color(55, 82, 140), //\n new Color(59, 81, 44),\n new Color(163, 144, 79),\n new Color(180, 122, 116),\n new Color(38, 100, 100),\n new Color(30, 30, 76),\n new Color(17, 17, 17),\n };\n\n static {\n try {\n sheetExportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/table-export.svg\"));\n sheetImportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/table-import.svg\"));\n rowRemoveIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/row-remove.svg\"));\n rowInsertIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/row-insert-bottom.svg\"));\n searchIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/list-search.svg\"));\n clipboardIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/clipboard-copy.svg\"));\n copyIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/copy.svg\"));\n\n sheetExportIcon.setColorFilter(ThemeUtils.iconColorFilter);\n sheetImportIcon.setColorFilter(ThemeUtils.iconColorFilter);\n rowRemoveIcon.setColorFilter(ThemeUtils.iconColorFilter);\n rowInsertIcon.setColorFilter(ThemeUtils.iconColorFilter);\n searchIcon.setColorFilter(ThemeUtils.iconColorFilter);\n clipboardIcon.setColorFilter(ThemeUtils.iconColorFilter);\n copyIcon.setColorFilter(ThemeUtils.iconColorFilter);\n\n /*\n this code determines if the label foreground color is closer to/further from black/white, then uses that\n to select which set of colors to use for the types on the sheets (lighter or darker)\n (the idea being a darker theme tends to have a lighter text foreground color)\n */\n Color c = UIManager.getColor(\"Label.foreground\");\n double diff = (double) (c.getRed() + c.getBlue() + c.getGreen()) / 3;\n if (Math.max(diff, 255 - diff) == diff)\n {\n System.arraycopy(darkModeTypeColors, 0, typeColors, 0, typeColors.length);\n }\n }\n catch(IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n private List<JPanel> panels;\n\n private NintendoDsRom rom;\n private Game baseRom;\n private boolean gitEnabled;\n\n public PokeditorManager(Tool tool)\n {\n super(tool, \"PokEditor\");\n\n rom = tool.getRom();\n baseRom = Game.parseBaseRom(rom.getGameCode());\n gitEnabled = tool.isGitEnabled();\n GameFiles.initialize(baseRom);\n TextFiles.initialize(baseRom);\n GameCodeBinaries.initialize(baseRom);\n Tables.initialize(baseRom);\n\n DataManager.codeBinarySetup(rom);\n\n// sheetPanels = new HashMap<>();\n panels = new ArrayList<>();\n// JPanel placeholder = new JPanel();\n// placeholder.setName(\"Test panel\");\n//\n// placeholder.setPreferredSize(dimension);\n// placeholder.setMinimumSize(dimension);\n\n DefaultDataEditorPanel<PokemonSpriteData, ?> battleSpriteEditor = DataManager.createPokemonSpriteEditor(this, rom);\n battleSpriteEditor.setName(\"Pokemon Sprites\");\n battleSpriteEditor.setPreferredSize(battleSpriteEditor.getPreferredSize());\n\n DefaultSheetPanel<PersonalData, ?> personalPanel = DataManager.createPersonalSheet(this, rom);\n personalPanel.setName(\"Personal Sheet\");\n\n DefaultSheetPanel<PersonalData, ?> tmCompatibilityPanel = DataManager.createTmCompatibilitySheet(this, rom);\n tmCompatibilityPanel.setName(\"TMs Sheet\");\n// panels.add(personalPanel);\n\n DefaultSheetPanel<EvolutionData, ?> evolutionsPanel = DataManager.createEvolutionSheet(this, rom);\n evolutionsPanel.setName(\"Evolutions Sheet\");\n// panels.add(evolutionsPanel);\n\n DefaultSheetPanel<LearnsetData, ?> learnsetsPanel = DataManager.createLearnsetSheet(this, rom);\n learnsetsPanel.setName(\"Learnsets Sheet\");\n// panels.add(evolutionsPanel);\n\n DefaultSheetPanel<MoveData, ?> movesPanel = DataManager.createMoveSheet(this, rom);\n movesPanel.setName(\"Moves Sheet\");\n\n DefaultDataEditorPanel<GenericScriptData, ?> fieldScriptEditor = DataManager.createFieldScriptEditor(this, rom);\n fieldScriptEditor.setName(\"Field Scripts\");\n fieldScriptEditor.setPreferredSize(fieldScriptEditor.getPreferredSize());\n\n\n// JPanel fieldPanel = new JPanel();\n// fieldPanel.setName(\"Field\");\n// JPanel waterPanel = new JPanel();\n// waterPanel.setName(\"Water\");\n// PanelGroup encounters = new PanelGroup(\"Encounters\", fieldPanel, waterPanel);\n\n PanelGroup pokemonGroup = new PanelGroup(\"Pokémon Editing\", personalPanel, tmCompatibilityPanel, learnsetsPanel, evolutionsPanel, battleSpriteEditor);\n panels.add(pokemonGroup);\n// panels.add(battleSpriteEditor);\n panels.add(movesPanel);\n// panels.add(encounters);\n panels.add(fieldScriptEditor);\n// panels.add(placeholder);\n }\n\n public <E extends GenericFileData> void saveData(Class<E> dataClass)\n {\n DataManager.saveData(rom, dataClass);\n DataManager.saveData(rom, TextBankData.class);\n// DataManager.saveCodeBinaries(rom, List.of(GameCodeBinaries.ARM9));\n\n// if (!wipeAndWriteUnpacked())\n// throw new RuntimeException(\"An error occurred while deleting or writing a file, please check write permissions\");\n String message = null;\n if (gitEnabled)\n {\n message = JOptionPane.showInputDialog(null, \"Enter commit message:\", \"Save & Commit Changes\", JOptionPane.INFORMATION_MESSAGE);\n if (message == null)\n {\n JOptionPane.showMessageDialog(null, \"Save aborted\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n else if (message.isEmpty())\n {\n message = null;\n }\n }\n\n wipeAndWriteUnpacked(message);\n }\n\n public <E extends GenericFileData> void resetData(Class<E> dataClass)\n {\n DataManager.resetData(rom, dataClass);\n }\n\n public void resetAllIndexedCellRendererText()\n {\n for (JPanel panel : panels)\n {\n if (panel instanceof DefaultSheetPanel<?,?> sheetPanel)\n {\n sheetPanel.getTable().resetIndexedCellRendererText();\n }\n else if (panel instanceof PanelGroup panelGroup)\n {\n for (JPanel groupPanel : panelGroup.getPanels())\n {\n if (groupPanel instanceof DefaultSheetPanel<?,?> sheetPanel)\n {\n sheetPanel.getTable().resetIndexedCellRendererText();\n }\n }\n }\n }\n }\n\n public void writeSheet(String[][] data)\n {\n JFileChooser fc = new JFileChooser(System.getProperty(\"user.dir\"));\n fc.setDialogTitle(\"Export Sheet\");\n fc.setAcceptAllFileFilterUsed(false);\n\n fc.setFileSelectionMode(JFileChooser.FILES_ONLY);\n fc.addChoosableFileFilter(new FileFilter()\n {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".csv\");\n }\n\n @Override\n public String getDescription()\n {\n return \"CSV file (*.csv)\";\n }\n });\n\n int returnVal = fc.showSaveDialog(null);\n\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File selected = fc.getSelectedFile();\n String path = selected.getAbsolutePath();\n if (!path.endsWith(\".csv\"))\n path = path + \".csv\";\n try\n {\n BufferedWriter writer = new BufferedWriter(new FileWriter(path));\n for (String[] row : data) {\n for (String s : row)\n writer.write(s + \",\");\n writer.write(\"\\n\");\n }\n\n writer.close();\n }\n catch(IOException e) {\n throw new RuntimeException(e);\n }\n\n }\n }\n\n private static JFileChooser prepareImageChooser(String title, boolean allowPalette)\n {\n String lastPath = Tool.preferences.get(\"pokeditor.imagePath\", null);\n if (lastPath == null) {\n lastPath = System.getProperty(\"user.dir\");\n }\n\n JFileChooser fc = new JFileChooser(lastPath);\n fc.setDialogTitle(title);\n fc.setAcceptAllFileFilterUsed(false);\n\n fc.setFileSelectionMode(JFileChooser.FILES_ONLY);\n\n fc.addChoosableFileFilter(pngFilter);\n fc.addChoosableFileFilter(ncgrFilter);\n if (allowPalette)\n fc.addChoosableFileFilter(nclrFilter);\n return fc;\n }\n\n public static void writeIndexedImage(IndexedImage image)\n {\n JFileChooser fc = prepareImageChooser(\"Export Sprite\", true);\n int returnVal = fc.showSaveDialog(null);\n\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File selected = fc.getSelectedFile();\n\n String extension;\n if (fc.getFileFilter().equals(pngFilter))\n extension = \"png\";\n else if (fc.getFileFilter().equals(ncgrFilter))\n extension = \"NCGR\";\n else\n extension = \"NCLR\";\n\n String path = selected.getAbsolutePath();\n if (!path.endsWith(\".\" + extension))\n path = path + \".\" + extension;\n\n Tool.preferences.put(\"pokeditor.imagePath\", selected.getParentFile().getAbsolutePath());\n\n try\n {\n if (extension.equals(\"png\"))\n image.saveToIndexedPngFile(path);\n else if (extension.equals(\"NCGR\"))\n image.saveToFile(path);\n else\n image.getPalette().saveToFile(path);\n }\n catch(IOException e) {\n JOptionPane.showMessageDialog(null, \"A fatal error occurred while writing an indexed PNG to disk. See command-line for details.\", \"Error\", JOptionPane.ERROR_MESSAGE);\n throw new RuntimeException(e);\n }\n\n }\n }\n\n public static GenericNtrFile readIndexedImage(boolean allowPalette)\n {\n JFileChooser fc = prepareImageChooser(\"Import Sprite\", allowPalette);\n int returnVal = fc.showOpenDialog(null);\n\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File selected = fc.getSelectedFile();\n\n String path = selected.getAbsolutePath();\n\n Tool.preferences.put(\"pokeditor.imagePath\", selected.getParentFile().getAbsolutePath());\n\n try\n {\n if (fc.getFileFilter().equals(pngFilter))\n return IndexedImage.fromIndexedPngFile(path);\n else if (fc.getFileFilter().equals(ncgrFilter))\n return IndexedImage.fromFile(path, 0, 0, 1, 1, true); //todo revisit if implementing DP support\n else\n return Palette.fromFile(path, 4);\n }\n catch(IOException e) {\n JOptionPane.showMessageDialog(null, \"A fatal error occurred while writing an indexed PNG to disk. See command-line for details.\", \"Error\", JOptionPane.ERROR_MESSAGE);\n throw new RuntimeException(e);\n }\n }\n\n return new GenericNtrFile();\n }\n\n @Override\n public List<JPanel> getPanels()\n {\n return panels;\n }\n\n @Override\n public boolean hasUnsavedChanges()\n {\n //todo\n return false;\n }\n\n @Override\n public void doInfoButtonAction(ActionEvent actionEvent)\n {\n //todo\n JOptionPane.showMessageDialog(null, \"Not yet implemented\", \"Sorry\", JOptionPane.ERROR_MESSAGE);\n }\n\n private static final FileFilter pngFilter = new FileFilter() {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".png\");\n }\n\n @Override\n public String getDescription()\n {\n return \"Portable Network Graphics file (*.png)\";\n }\n };\n\n private static final FileFilter ncgrFilter = new FileFilter()\n {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".NCGR\");\n }\n\n @Override\n public String getDescription()\n {\n return \"Nitro Character Graphics Resource (*.NCGR)\";\n }\n };\n\n private static final FileFilter nclrFilter = new FileFilter()\n {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".NCLR\");\n }\n\n @Override\n public String getDescription()\n {\n return \"Nitro Color Resource (*.NCLR)\";\n }\n };\n}" } ]
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import io.github.turtleisaac.nds4j.ui.ThemeUtils; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.gui.EditorComboBox.ComboBoxItem; import io.github.turtleisaac.pokeditor.gui.EditorComboBox; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import net.miginfocom.swing.*;
4,182
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data; /** * @author turtleisaac */ public class DefaultDataEditorPanel<G extends GenericFileData, E extends Enum<E>> extends JPanel { private final DefaultDataEditor<G, E> editor;
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data; /** * @author turtleisaac */ public class DefaultDataEditorPanel<G extends GenericFileData, E extends Enum<E>> extends JPanel { private final DefaultDataEditor<G, E> editor;
private final PokeditorManager manager;
2
2023-10-15 05:00:57+00:00
8k
xiezhihui98/GAT1400
src/main/java/com/cz/viid/kafka/listener/AbstractMessageListener.java
[ { "identifier": "WebSocketEndpoint", "path": "src/main/java/com/cz/viid/be/socket/WebSocketEndpoint.java", "snippet": "@ServerEndpoint(\"/VIID/Subscribe/WebSocket\")\n@Component\npublic class WebSocketEndpoint {\n private static final Logger log = LoggerFactory.getLogger(WebSocketEndpoint.class);\n\n /**\n * concurrent包的线程安全Set, 用来存放每个客户端对应的MyWebSocket对象.\n */\n private static CopyOnWriteArraySet<WebSocketEndpoint> webSocketSet = new CopyOnWriteArraySet<>();\n /**\n * 与某个客户端的连接会话, 需要通过它来给客户端发送数据.\n */\n private Session session;\n\n private VIIDServer loginUser;\n\n /**\n * 连接建立成功调用的方法\n */\n @OnOpen\n public void onOpen(Session session) {\n\n //webSocket中继过来的security认证状态\n this.loginUser = (VIIDServer) ((Authentication) session.getUserPrincipal()).getPrincipal();\n this.session = session;\n webSocketSet.add(this);\n log.info(\"有新连接加入! 客户端组ID为: \" + this.loginUser.getServerId());\n try {\n sendMessage(\"连接成功xxx\");\n } catch (IOException e) {\n log.error(\"web-socket IO异常\", e);\n }\n }\n\n /**\n * 连接关闭调用的方法\n */\n @OnClose\n public void onClose() {\n AppContextHolder.publishEvent(new WebSocketCloseEvent(loginUser));\n // 从set中删除\n webSocketSet.remove(this);\n log.info(\"有一连接关闭!\");\n }\n\n /**\n * 收到客户端消息后转发消息\n *\n * @param message 客户端发送过来的消息, 格式要求为: {\"msg\":\"测试\",\"groupId\":1}\n * @param session 客户端session\n */\n @OnMessage(maxMessageSize = 999999L)\n public void onMessage(String message, Session session) throws IOException {\n log.info(\"来自客户端(sessionId为: \" + session.getId() + \")的消息: \" + message);\n }\n\n /**\n * web-socket发生错误\n *\n * @param session 某个session\n * @param error 错误\n */\n @OnError\n public void onError(Session session, Throwable error) {\n log.error(\"sessionId为:{}视图库ID:{}的session发生错误:{}\", session.getId(), loginUser.getServerId(), error.getMessage());\n }\n\n /**\n * 向客户端发送消息\n *\n * @param message 消息\n */\n public void sendMessage(String message) throws IOException {\n this.session.getBasicRemote().sendText(message);\n }\n\n public String getServerId() {\n return this.loginUser.getServerId();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n WebSocketEndpoint webSocket = (WebSocketEndpoint) o;\n return Objects.equals(session, webSocket.session) &&\n Objects.equals(getServerId(), webSocket.getServerId());\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(session, getServerId());\n }\n\n public static void sendMessageToServerId(String serverId, String message) throws IOException {\n Objects.requireNonNull(serverId, \"缺少发送目标\");\n log.info(\"send message:{} to: {}\", message, serverId);\n for (WebSocketEndpoint webSocketEndpoint : webSocketSet) {\n if (webSocketEndpoint.getServerId().startsWith(serverId)) {\n webSocketEndpoint.sendMessage(message);\n }\n }\n }\n}" }, { "identifier": "KeepaliveAction", "path": "src/main/java/com/cz/viid/be/task/action/KeepaliveAction.java", "snippet": "@Component\npublic class KeepaliveAction {\n\n private final Cache<String, VIIDServer> KEEPALIVE_VIID_SERVERS = CacheBuilder.newBuilder()\n// .expireAfterAccess(Duration.ofSeconds(120))\n .build();\n\n @Lazy\n @Autowired\n VIIDServerService viidServerService;\n\n public VIIDServer get(String serverId) {\n return KEEPALIVE_VIID_SERVERS.getIfPresent(serverId);\n }\n\n public void refresh(VIIDServer domain) {\n VIIDServer viidServer = KEEPALIVE_VIID_SERVERS.getIfPresent(domain.getServerId());\n if (Objects.nonNull(viidServer)) {\n domain.setOnline(viidServer.getOnline());\n KEEPALIVE_VIID_SERVERS.put(domain.getServerId(), domain);\n }\n }\n\n public VIIDServer keepalive(String serverId) {\n return KEEPALIVE_VIID_SERVERS.getIfPresent(serverId);\n }\n\n public void register(VIIDServer domain) {\n KEEPALIVE_VIID_SERVERS.put(domain.getServerId(), domain);\n }\n\n public void unregister(String serverId) {\n KEEPALIVE_VIID_SERVERS.invalidate(serverId);\n }\n\n public Map<String, VIIDServer> allServer() {\n return KEEPALIVE_VIID_SERVERS.asMap();\n }\n\n public long size() {\n return KEEPALIVE_VIID_SERVERS.size();\n }\n\n public boolean online(String serverId) {\n VIIDServer viewLibrary = this.get(serverId);\n if (Objects.nonNull(viewLibrary)) {\n return viewLibrary.getOnline();\n }\n VIIDServer server = getCurrentServer();\n return StringUtils.equals(server.getServerId(), serverId);\n }\n\n public VIIDServer getCurrentServer() {\n return viidServerService.getCurrentServer();\n }\n\n public VIIDServer getCurrentServer(boolean useCache) {\n return viidServerService.getCurrentServer(useCache);\n }\n}" }, { "identifier": "Constants", "path": "src/main/java/com/cz/viid/framework/config/Constants.java", "snippet": "public class Constants {\n public static class KAFKA_CONSUMER {\n public static final String APP_DEFAULT_GROUP = \"GA1400_BACKEND\";\n\n //消费失败重试topic\n public static final String FACE_INFO_RETRY_TOPIC = APP_DEFAULT_GROUP + \"_FACE_INFO_RETRY\";\n public static final String MOTOR_VEHICLE_RETRY_TOPIC = APP_DEFAULT_GROUP + \"_MOTOR_VEHICLE_RETRY\";\n }\n\n public static class DEFAULT_TOPIC_PREFIX {\n //卡口设备前缀\n public static final String TOLLGATE_DEVICE = \"GA1400-TOLLGATE_DEVICE-\";\n //车辆抓拍前缀\n public static final String MOTOR_VEHICLE = \"GA1400-MOTOR_VEHICLE-\";\n //采集设备前缀\n public static final String APE_DEVICE = \"GA1400-APE_DEVICE-\";\n //人脸抓拍前缀\n public static final String FACE_RECORD = \"GA1400-FACE_RECORD-\";\n //非机动车前缀\n public static final String NON_MOTOR_VEHICLE = \"GA1400-NON_MOTOR_VEHICLE-\";\n //人员抓拍前缀\n public static final String PERSON_RECORD = \"GA1400-PERSON_RECORD-\";\n\n public static final String RAW = \"GA1400-RAW-\";\n }\n\n public static class VIID_SERVER {\n public static class TRANSMISSION {\n public static final String HTTP = \"http\";\n public static final String WEBSOCKET = \"websocket\";\n }\n public static class SERVER_CATEGORY {\n //自己\n public static final String GATEWAY = \"0\";\n //下级\n public static final String DOWN_DOMAIN = \"1\";\n public static final String UP_DOMAIN = \"2\";\n }\n public static class RESOURCE_CLASS {\n //卡口ID\n public static final Integer TOLLGATE = 0;\n //视图库ID\n public static final Integer VIEW_LIBRARY = 4;\n }\n\n public static class SUBSCRIBE_DETAIL {\n //案(事)件目录\n public static final String AN_JIANG_DIR = \"1\";\n //单个案(事)件目录\n public static final String AN_JIANG = \"2\";\n //采集设备目录\n public static final String DEVICE_DIR = \"3\";\n //采集设备状态\n public static final String DEVICE_STATUS = \"4\";\n //采集系统目录\n public static final String SYSTEM_DIR = \"5\";\n //采集系统状态\n public static final String SYSTEM_STATUS = \"6\";\n //视频卡口目录\n public static final String VIDEO_TOLLGATE_DIR = \"7\";\n //单个卡口记录\n public static final String TOLLGATE_RECORD = \"8\";\n //车道目录\n public static final String CHE_DAO_DIR = \"9\";\n //单个车道记录\n public static final String CHE_DAO = \"10\";\n //自动采集的人员信息\n public static final String PERSON_INFO = \"11\";\n //自动采集的人脸信息\n public static final String FACE_INFO = \"12\";\n //自动采集的车辆信息\n public static final String PLATE_INFO = \"13\";\n //自动采集的非机动车辆信息\n public static final String PLATE_MIRCO_INFO = \"14\";\n //自动采集的物品信息\n public static final String SUBSTANCE_INFO = \"15\";\n //自动采集的文件信息\n public static final String FILE_INFO = \"16\";\n\n public static final String RAW = \"999\";\n }\n }\n\n public static class SUBSCRIBE {\n public static class OPERATE_TYPE {\n public static final Integer CONTINUE = 0;\n public static final Integer CANCEL = 1;\n }\n\n public static class STATUS {\n public static final Integer CONTINUE = 0;\n public static final Integer CANCEL = 1;\n public static final Integer EXPIRE = 2;\n public static final Integer INACTIVE = 9;\n }\n }\n}" }, { "identifier": "AppContextHolder", "path": "src/main/java/com/cz/viid/framework/context/AppContextHolder.java", "snippet": "@Component\npublic class AppContextHolder implements ApplicationContextAware {\n private volatile static ApplicationContext context;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n setContext(applicationContext);\n }\n\n public static void setContext(ApplicationContext applicationContext) {\n context = applicationContext;\n }\n\n public static <T> T getBean(Class<T> clz) {\n return context.getBean(clz);\n }\n\n public static <T> T getBean(String beanName) {\n return (T) context.getBean(beanName);\n }\n\n public static void publishEvent(ApplicationEvent event) {\n context.publishEvent(event);\n }\n}" }, { "identifier": "VIIDPublish", "path": "src/main/java/com/cz/viid/framework/domain/entity/VIIDPublish.java", "snippet": "@Data\n@EqualsAndHashCode\n@ToString\n@TableName(value = \"viid_publish\", autoResultMap = true)\npublic class VIIDPublish {\n\n @ApiModelProperty(\"订阅标识符\")\n @TableId(value = \"subscribe_id\", type = IdType.NONE)\n private String subscribeId;\n @ApiModelProperty(\"订阅标题\")\n @TableField(\"title\")\n private String title;\n @ApiModelProperty(\"订阅类型\")\n @TableField(\"subscribe_detail\")\n private String subscribeDetail;\n @ApiModelProperty(\"资源ID\")\n @TableField(value = \"resource_uri\", typeHandler = StringToArrayTypeHandler.class, jdbcType = JdbcType.ARRAY)\n private String resourceUri;\n @ApiModelProperty(\"申请人\")\n @TableField(\"application_name\")\n private String applicationName;\n @ApiModelProperty(\"申请单位\")\n @TableField(\"application_org\")\n private String applicationOrg;\n @ApiModelProperty(\"开始时间\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n @TableField(\"begin_time\")\n private Date beginTime;\n @ApiModelProperty(\"结束时间\")\n @JsonFormat(pattern = \"yyyyMMddHHmmss\")\n @TableField(\"end_time\")\n private Date endTime;\n @ApiModelProperty(\"订阅回调地址\")\n @TableField(\"receive_addr\")\n private String receiveAddr;\n @ApiModelProperty(\"数据上报间隔\")\n @TableField(\"report_interval\")\n private Integer reportInterval;\n @ApiModelProperty(\"理由\")\n @TableField(\"reason\")\n private String reason;\n @ApiModelProperty(value = \"操作类型\",notes = \"0=订阅,1=取消订阅\")\n @TableField(\"operate_type\")\n private Integer operateType;\n @ApiModelProperty(value = \"订阅状态\", notes = \"0=订阅中,1=已取消订阅,2=订阅到期,9=未订阅\")\n @TableField(\"subscribe_status\")\n private Integer subscribeStatus;\n @TableField(\"resource_class\")\n private Integer resourceClass;\n @JsonIgnore\n @ApiModelProperty(value = \"未知\")\n @TableField(\"result_image_declare\")\n private String resultImageDeclare;\n @JsonIgnore\n @ApiModelProperty(value = \"未知\")\n @TableField(\"result_feature_declare\")\n private Integer resultFeatureDeclare;\n @ApiModelProperty(value = \"发布节点ID\")\n @TableField(\"server_id\")\n private String serverId;\n @JsonIgnore\n @TableField(\"create_time\")\n private Date createTime;\n @JsonIgnore\n @TableField(\"update_time\")\n private Date updateTime;\n}" }, { "identifier": "VIIDServer", "path": "src/main/java/com/cz/viid/framework/domain/entity/VIIDServer.java", "snippet": "@Data\n@TableName(\"viid_server\")\npublic class VIIDServer {\n\n @ApiModelProperty(value = \"视图库编号\")\n @TableId(value = \"server_id\",type = IdType.NONE)\n private String serverId;\n @ApiModelProperty(value = \"视图库名称\")\n @TableField(value = \"server_name\")\n private String serverName;\n @ApiModelProperty(value = \"交互协议\")\n @TableField(\"scheme\")\n private String scheme = \"http\";\n @ApiModelProperty(value = \"视图库地址\")\n @TableField(value = \"host\")\n private String host;\n @ApiModelProperty(value = \"视图库端口\")\n @TableField(value = \"port\")\n private Integer port;\n @ApiModelProperty(value = \"授权用户\")\n @TableField(value = \"username\")\n private String username;\n @ApiModelProperty(value = \"授权用户凭证\")\n @TableField(value = \"authenticate\")\n private String authenticate;\n @ApiModelProperty(value = \"是否启用\")\n @TableField(value = \"enabled\")\n private Boolean enabled;\n @ApiModelProperty(value = \"服务类别\", notes = \"0=自己,1=下级,2=上级\")\n @TableField(value = \"category\")\n private String category;\n @ApiModelProperty(\"创建时间\")\n @TableField(value = \"create_time\")\n private Date createTime;\n @ApiModelProperty(\"是否开启双向保活\")\n @TableField(value = \"keepalive\")\n private Boolean keepalive;\n @ApiModelProperty(value = \"数据传输类型\", example = \"HTTP\")\n @TableField(\"transmission\")\n private String transmission = Constants.VIID_SERVER.TRANSMISSION.HTTP;\n @ApiModelProperty(\"在线状态\")\n @TableField(value = \"online\", exist = false)\n private Boolean online = false;\n\n public String httpUrlBuilder() {\n return scheme + \"://\" + host + \":\" + port;\n }\n}" }, { "identifier": "SubscribeNotificationRequest", "path": "src/main/java/com/cz/viid/framework/domain/vo/SubscribeNotificationRequest.java", "snippet": "@Data\npublic class SubscribeNotificationRequest {\n\n @JsonProperty(\"SubscribeNotificationListObject\")\n private SubscribeNotifications subscribeNotificationListObject;\n}" }, { "identifier": "KafkaStartupService", "path": "src/main/java/com/cz/viid/kafka/KafkaStartupService.java", "snippet": "@Component\npublic class KafkaStartupService implements ApplicationContextAware {\n private final Logger log = LoggerFactory.getLogger(getClass());\n private final DefaultKafkaListenerErrorHandler errorHandler = new DefaultKafkaListenerErrorHandler();\n private final StringMessageConverter converter = new StringMessageConverter();\n private final MessageHandlerMethodFactory methodFactory = new DefaultMessageHandlerMethodFactory();\n @Autowired\n KafkaListenerEndpointRegistry registry;\n @Autowired\n KafkaListenerContainerFactory<MessageListenerContainer> factory;\n @Autowired\n VIIDPublishService viidPublishService;\n @Autowired\n VIIDServerService viidServerService;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n AppContextHolder.setContext(applicationContext);\n viidServerService.afterPropertiesSet();\n }\n\n public void register(VIIDPublish publish) {\n if (Constants.SUBSCRIBE.STATUS.CONTINUE.equals(publish.getSubscribeStatus())) {\n doRegister(publish);\n }\n }\n\n public void serverPublishIdle(String serverId) {\n List<VIIDPublish> publishList = viidPublishService.findListByServerId(serverId);\n publishList.forEach(this::startPublish);\n }\n\n public void serverPublishStop(String serverId) {\n log.info(\"视图库{}数据发布停止\", serverId);\n List<VIIDPublish> publishList = viidPublishService.findListByServerId(serverId);\n publishList.forEach(this::stopPublish);\n }\n\n public void startPublish(VIIDPublish publish) {\n Set<String> details = Stream.of(StringUtils.split(publish.getSubscribeDetail())).collect(Collectors.toSet());\n for (String detail : details) {\n String id = this.listenerIdBuilder(publish.getSubscribeId(), detail);\n MessageListenerContainer listenerContainer = registry.getListenerContainer(id);\n if (Objects.isNull(listenerContainer)) {\n this.register(publish);\n listenerContainer = registry.getListenerContainer(id);\n if (Objects.isNull(listenerContainer))\n continue;\n }\n boolean running = listenerContainer.isRunning();\n if (!running) {\n listenerContainer.start();\n }\n }\n\n }\n\n public void stopPublish(VIIDPublish publish) {\n Set<String> containerIds = registry.getListenerContainerIds();\n for (String containerId : containerIds) {\n if (containerId.startsWith(publish.getSubscribeId())) {\n MessageListenerContainer listenerContainer = registry.getListenerContainer(containerId);\n if (Objects.nonNull(listenerContainer) && listenerContainer.isRunning()) {\n listenerContainer.stop();\n }\n registry.unregisterListenerContainer(containerId);\n }\n }\n }\n\n public void delayPublish(VIIDPublish publish) {\n this.stopPublish(publish);\n CompletableFuture.runAsync(() -> {\n try {\n Thread.sleep(60000);\n this.startPublish(publish);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }, AppConfig.GLOBAL_EXECUTOR);\n }\n\n private synchronized void doRegister(VIIDPublish publish) {\n VIIDServer setting = viidServerService.getCurrentServer();\n Set<String> details = Stream.of(StringUtils.split(publish.getSubscribeDetail())).collect(Collectors.toSet());\n for (String detail : details) {\n String endpointId = this.listenerIdBuilder(publish.getSubscribeId(), detail);\n Set<String> containerIds = registry.getListenerContainerIds();\n if (containerIds.contains(endpointId))\n continue;\n MethodKafkaListenerEndpoint<String, String> endpoint = new MethodKafkaListenerEndpoint<>();\n CustomMessageListener messageListener;\n String prefix;\n switch (detail) {\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.DEVICE_DIR:\n messageListener = new APEMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.APE_DEVICE;\n break;\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.VIDEO_TOLLGATE_DIR:\n messageListener = new TollgateMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.TOLLGATE_DEVICE;\n break;\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.FACE_INFO:\n messageListener = new FaceMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.FACE_RECORD;\n break;\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.PERSON_INFO:\n messageListener = new PersonMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.PERSON_RECORD;\n break;\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.PLATE_INFO:\n messageListener = new MotorVehicleMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.MOTOR_VEHICLE;\n break;\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.PLATE_MIRCO_INFO:\n messageListener = new NonMotorVehicleMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.NON_MOTOR_VEHICLE;\n break;\n case Constants.VIID_SERVER.SUBSCRIBE_DETAIL.RAW:\n messageListener = new RawMessageListener(publish);\n prefix = Constants.DEFAULT_TOPIC_PREFIX.RAW;\n break;\n default:\n throw new RuntimeException(\"没有指定resourceClass\");\n }\n messageListener.configure();\n Set<String> resourceUri = Arrays.stream(\n StringUtils.split(publish.getResourceUri(), \",\")\n ).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toSet());\n if (resourceUri.contains(setting.getServerId())) {\n endpoint.setTopicPattern(Pattern.compile(\"^\" + prefix + \".*\"));\n } else {\n endpoint.setTopics(resourceUri.stream()\n .map(prefix::concat)\n .toArray(String[]::new));\n }\n endpoint.setBean(messageListener);\n Method method = ReflectionUtils.findMethod(messageListener.getClass(), \"consumer\", List.class, Acknowledgment.class);\n if (Objects.isNull(method))\n throw new RuntimeException(\"消费者没有实现消费方法\");\n endpoint.setMethod(method);\n endpoint.setId(endpointId);\n endpoint.setGroupId(publish.getSubscribeId());\n endpoint.setMessagingConverter(converter);\n endpoint.setErrorHandler(errorHandler);\n endpoint.setMessageHandlerMethodFactory(methodFactory);\n if (Objects.nonNull(publish.getReportInterval())) {\n Properties properties = new Properties();\n properties.put(\"group.instance.id\", publish.getSubscribeId());\n properties.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, publish.getReportInterval() * 1000);\n endpoint.setConsumerProperties(properties);\n }\n\n registry.registerListenerContainer(endpoint, factory);\n log.info(\"视图库{}注册Kafka消费端点,消费类型{}\", publish.getServerId(), detail);\n }\n }\n\n public String listenerIdBuilder(String subscribeId, String detail) {\n return StringUtils.join(subscribeId, \"::\", detail);\n }\n}" }, { "identifier": "VIIDServerClient", "path": "src/main/java/com/cz/viid/rpc/VIIDServerClient.java", "snippet": "@FeignClient(name = \"VIIDServerClient\", url = \"http://127.0.0.254\")\npublic interface VIIDServerClient {\n\n @PostMapping(\"/VIID/System/Register\")\n Response register(URI uri, @RequestBody RegisterRequest request,\n @RequestHeader(HttpHeaders.AUTHORIZATION) String authorization);\n\n @PostMapping(\"/VIID/System/UnRegister\")\n VIIDBaseResponse unRegister(URI uri, @RequestBody UnRegisterRequest request,\n @RequestHeader(\"User-Identify\") String authorization);\n\n @PostMapping(\"/VIID/System/Keepalive\")\n VIIDBaseResponse keepalive(URI uri, @RequestBody KeepaliveRequest keepaliveRequest,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @PostMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse addSubscribes(URI uri, @RequestBody SubscribesRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @PutMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse updateSubscribes(URI uri, @RequestBody SubscribesRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n @DeleteMapping(\"/VIID/Subscribes\")\n VIIDSubscribesResponse cancelSubscribes(URI uri, @RequestParam(\"IDList\") List<String> resourceIds,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n\n// @PostMapping(\"/VIID/SubscribeNotifications\")\n @PostMapping\n VIIDNotificationResponse subscribeNotifications(URI uri, @RequestBody SubscribeNotificationRequest request,\n @RequestHeader(\"User-Identify\") String userIdentifier);\n}" } ]
import com.alibaba.fastjson.JSONObject; import com.cz.viid.be.socket.WebSocketEndpoint; import com.cz.viid.be.task.action.KeepaliveAction; import com.cz.viid.framework.config.Constants; import com.cz.viid.framework.context.AppContextHolder; import com.cz.viid.framework.domain.entity.VIIDPublish; import com.cz.viid.framework.domain.entity.VIIDServer; import com.cz.viid.framework.domain.vo.SubscribeNotificationRequest; import com.cz.viid.kafka.KafkaStartupService; import com.cz.viid.rpc.VIIDServerClient; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.kafka.support.Acknowledgment; import java.net.URI; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
6,013
package com.cz.viid.kafka.listener; public abstract class AbstractMessageListener<T> implements CustomMessageListener { private final Logger log = LoggerFactory.getLogger(getClass());
package com.cz.viid.kafka.listener; public abstract class AbstractMessageListener<T> implements CustomMessageListener { private final Logger log = LoggerFactory.getLogger(getClass());
protected VIIDPublish publish;
4
2023-10-23 11:25:43+00:00
8k
eclipse-egit/egit
org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/GitRemoteResourceVariantTree.java
[ { "identifier": "GitSynchronizeData", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeData.java", "snippet": "public class GitSynchronizeData {\n\n\tprivate static final IWorkspaceRoot ROOT = ResourcesPlugin.getWorkspace()\n\t\t\t\t\t.getRoot();\n\n\t/**\n\t * Matches all strings that start from R_HEADS\n\t */\n\tpublic static final Pattern BRANCH_NAME_PATTERN = Pattern.compile(\"^\" + R_HEADS + \".*?\"); //$NON-NLS-1$ //$NON-NLS-2$\n\n\tprivate final boolean includeLocal;\n\n\tprivate final Repository repo;\n\n\tprivate final String dstRemote;\n\n\tprivate final String dstMerge;\n\n\tprivate RevCommit srcRevCommit;\n\n\tprivate RevCommit dstRevCommit;\n\n\tprivate RevCommit ancestorRevCommit;\n\n\tprivate final Set<IProject> projects;\n\n\tprivate final String repoParentPath;\n\n\tprivate final String srcRev;\n\n\tprivate final String dstRev;\n\n\tprivate TreeFilter pathFilter;\n\n\tprivate Set<IResource> includedResources;\n\n\tprivate static class RemoteAndMerge {\n\t\tfinal String remote;\n\t\tfinal String merge;\n\n\t\tpublic RemoteAndMerge(String remote, String merge) {\n\t\t\tthis.remote = remote;\n\t\t\tthis.merge = merge;\n\t\t}\n\t}\n\n\t/**\n\t * Constructs {@link GitSynchronizeData} object for all resources.\n\t * Equivalent to\n\t * <code>new GitSynchronizeData(repository, srcRev, dstRev, includeLocal, null)</code>\n\t * .\n\t *\n\t * @param repository\n\t * @param srcRev\n\t * @param dstRev\n\t * @param includeLocal\n\t * <code>true</code> if local changes should be included in\n\t * comparison\n\t * @throws IOException\n\t */\n\tpublic GitSynchronizeData(Repository repository, String srcRev,\n\t\t\tString dstRev, boolean includeLocal) throws IOException {\n\t\tthis(repository, srcRev, dstRev, includeLocal, null);\n\t}\n\n\t/**\n\t * Constructs a {@link GitSynchronizeData} object while restricting it to a\n\t * set of resources.\n\t *\n\t * @param repository\n\t * @param srcRev\n\t * @param dstRev\n\t * @param includeLocal\n\t * @param includedResources\n\t * either the set of resources to include in synchronization or\n\t * {@code null} to synchronize all resources.\n\t * @throws IOException\n\t */\n\tpublic GitSynchronizeData(Repository repository, String srcRev,\n\t\t\tString dstRev, boolean includeLocal,\n\t\t\tSet<IResource> includedResources) throws IOException {\n\t\tisNotNull(repository);\n\t\tisNotNull(srcRev);\n\t\tisNotNull(dstRev);\n\t\tthis.repo = repository;\n\t\tthis.srcRev = srcRev;\n\t\tthis.dstRev = dstRev;\n\t\tthis.includeLocal = includeLocal;\n\n\t\tRemoteAndMerge dstRemoteAndMerge = extractRemoteAndMergeForDst(dstRev);\n\n\t\tdstRemote = dstRemoteAndMerge.remote;\n\t\tdstMerge = dstRemoteAndMerge.merge;\n\n\t\trepoParentPath = repo.getDirectory().getParentFile().getAbsolutePath();\n\n\t\tprojects = new HashSet<>();\n\t\tfinal Iterable<? extends IResource> includedResourceIterable;\n\t\tif (includedResources == null)\n\t\t\t// include all project in synchronization\n\t\t\tincludedResourceIterable = Arrays.asList(ROOT.getProjects());\n\t\telse\n\t\t\tincludedResourceIterable = includedResources;\n\t\tfor (IResource res : includedResourceIterable) {\n\t\t\tIProject project = res.getProject();\n\t\t\tRepositoryMapping mapping = RepositoryMapping.getMapping(project);\n\t\t\tif (mapping != null && mapping.getRepository() == repo)\n\t\t\t\tprojects.add(project);\n\t\t}\n\n\t\t// do not set field if includedResources is null, some methods expect\n\t\t// #getIncludedResources() to return <null> to know it should\n\t\t// synchronize all resources.\n\t\tif (includedResources != null)\n\t\t\tsetIncludedResources(includedResources);\n\n\t\tupdateRevs();\n\t}\n\n\t/**\n\t * Recalculates source, destination and ancestor Rev commits\n\t *\n\t * @throws IOException\n\t */\n\tpublic void updateRevs() throws IOException {\n\t\ttry (ObjectWalk ow = new ObjectWalk(repo)) {\n\t\t\tow.setRetainBody(true);\n\t\t\tsrcRevCommit = getCommit(srcRev, ow);\n\t\t\tdstRevCommit = getCommit(dstRev, ow);\n\t\t}\n\n\t\tif (this.dstRevCommit != null && this.srcRevCommit != null)\n\t\t\tthis.ancestorRevCommit = getCommonAncestor(repo, this.srcRevCommit,\n\t\t\t\t\tthis.dstRevCommit);\n\t\telse\n\t\t\tthis.ancestorRevCommit = null;\n\t}\n\n\t/**\n\t * @return instance of repository that should be synchronized\n\t */\n\tpublic Repository getRepository() {\n\t\treturn repo;\n\t}\n\n\t/**\n\t * @return ref specification of destination merge branch\n\t */\n\tpublic String getDstMerge() {\n\t\treturn dstMerge;\n\t}\n\n\t/**\n\t * @return name of destination remote or {@code null} when destination\n\t * branch is not a remote branch\n\t */\n\tpublic String getDstRemoteName() {\n\t\treturn dstRemote;\n\t}\n\n\t/**\n\t * @return synchronize source rev name\n\t */\n\tpublic RevCommit getSrcRevCommit() {\n\t\treturn srcRevCommit;\n\t}\n\n\t/**\n\t * @return synchronize destination rev name\n\t */\n\tpublic RevCommit getDstRevCommit() {\n\t\treturn dstRevCommit;\n\t}\n\n\t/**\n\t * @return list of project's that are connected with this repository\n\t */\n\tpublic Set<IProject> getProjects() {\n\t\treturn Collections.unmodifiableSet(projects);\n\t}\n\n\t/**\n\t * @param file\n\t * @return <true> if given {@link File} is contained by this repository\n\t */\n\tpublic boolean contains(File file) {\n\t\treturn file.getAbsoluteFile().toString().startsWith(repoParentPath);\n\t}\n\n\t/**\n\t * @return <code>true</code> if local changes should be included in\n\t * comparison\n\t */\n\tpublic boolean shouldIncludeLocal() {\n\t\treturn includeLocal;\n\t}\n\n\t/**\n\t * @return common ancestor commit\n\t */\n\tpublic RevCommit getCommonAncestorRev() {\n\t\treturn ancestorRevCommit;\n\t}\n\n\t/**\n\t * @param includedResources\n\t * list of resources to be synchronized\n\t */\n\tpublic void setIncludedResources(Set<IResource> includedResources) {\n\t\tthis.includedResources = includedResources;\n\t\tSet<String> paths = new HashSet<>();\n\t\tRepositoryMapping rm = RepositoryMapping.findRepositoryMapping(repo);\n\t\tif (rm != null) {\n\t\t\tfor (IResource resource : includedResources) {\n\t\t\t\tString repoRelativePath = rm.getRepoRelativePath(resource);\n\t\t\t\tif (repoRelativePath != null && repoRelativePath.length() > 0)\n\t\t\t\t\tpaths.add(repoRelativePath);\n\t\t\t}\n\t\t}\n\n\t\tif (!paths.isEmpty())\n\t\t\tpathFilter = PathFilterGroup.createFromStrings(paths);\n\t}\n\n\t/**\n\t * @return set of included resources or {@code null} when all resources\n\t * should be included\n\t */\n\tpublic Set<IResource> getIncludedResources() {\n\t\treturn includedResources;\n\t}\n\n\t/**\n\t * Disposes all nested resources\n\t */\n\tpublic void dispose() {\n\t\tif (projects != null)\n\t\t\tprojects.clear();\n\t\tif (includedResources != null)\n\t\t\tincludedResources.clear();\n\t}\n\n\t/**\n\t * @return instance of {@link TreeFilter} when synchronization was launched\n\t * from nested node (like folder) or {@code null} otherwise\n\t */\n\tpublic TreeFilter getPathFilter() {\n\t\treturn pathFilter;\n\t}\n\n\t/**\n\t * @return synchronization source rev\n\t */\n\tpublic String getSrcRev() {\n\t\treturn srcRev;\n\t}\n\n\t/**\n\t * @return synchronization destination rev\n\t */\n\tpublic String getDstRev() {\n\t\treturn dstRev;\n\t}\n\n\tprivate RemoteAndMerge extractRemoteAndMergeForDst(String rev) {\n\t\t// destination remote name is used for fetch and push, so check if this\n\t\t// is a remote-tracking branch\n\t\ttry {\n\t\t\tList<RemoteConfig> remoteConfigs = RemoteConfig\n\t\t\t\t\t.getAllRemoteConfigs(repo.getConfig());\n\t\t\tfor (RemoteConfig remoteConfig : remoteConfigs) {\n\t\t\t\tList<RefSpec> fetchRefSpecs = remoteConfig.getFetchRefSpecs();\n\t\t\t\tfor (RefSpec fetchRefSpec : fetchRefSpecs) {\n\t\t\t\t\tif (fetchRefSpec.matchDestination(rev)) {\n\t\t\t\t\t\tRefSpec expanded = fetchRefSpec\n\t\t\t\t\t\t\t\t.expandFromDestination(rev);\n\t\t\t\t\t\treturn new RemoteAndMerge(remoteConfig.getName(),\n\t\t\t\t\t\t\t\texpanded.getSource());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (URISyntaxException e) {\n\t\t\t// Fall back to returning empty result below\n\t\t}\n\t\treturn new RemoteAndMerge(null, null);\n\t}\n\n\tprivate RevCommit getCommit(String rev, ObjectWalk ow) throws IOException {\n\t\tif (rev.length() > 0) {\n\t\t\tObjectId id = repo.resolve(rev);\n\t\t\treturn id != null ? ow.parseCommit(id) : null;\n\t\t} else\n\t\t\treturn null;\n\t}\n\n}" }, { "identifier": "GitSynchronizeDataSet", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/dto/GitSynchronizeDataSet.java", "snippet": "public class GitSynchronizeDataSet implements Iterable<GitSynchronizeData> {\n\n\tprivate boolean containsFolderLevelSynchronizationRequest = false;\n\n\tprivate final Set<GitSynchronizeData> gsdSet;\n\n\tprivate final Map<String, GitSynchronizeData> projectMapping;\n\n\tprivate final boolean forceFetch;\n\n\t/**\n\t * Constructs GitSynchronizeDataSet.\n\t */\n\tpublic GitSynchronizeDataSet() {\n\t\tthis(false);\n\t}\n\n\t/**\n\t * Constructs GitSynchronizeDataSet.\n\t *\n\t * @param forceFetch\n\t * {@code true} for forcing fetch action before synchronization\n\t */\n\tpublic GitSynchronizeDataSet(boolean forceFetch) {\n\t\tthis.forceFetch = forceFetch;\n\t\tgsdSet = new HashSet<>();\n\t\tprojectMapping = new HashMap<>();\n\t}\n\n\t/**\n\t * Constructs GitSynchronizeDataSet and adds given element to set.\n\t *\n\t * @param data\n\t */\n\tpublic GitSynchronizeDataSet(GitSynchronizeData data) {\n\t\tthis();\n\t\tadd(data);\n\t}\n\n\t/**\n\t * @param data\n\t */\n\tpublic void add(GitSynchronizeData data) {\n\t\tgsdSet.add(data);\n\t\tif (data.getIncludedResources() != null\n\t\t\t\t&& data.getIncludedResources().size() > 0)\n\t\t\tcontainsFolderLevelSynchronizationRequest = true;\n\n\t\tfor (IProject proj : data.getProjects()) {\n\t\t\tprojectMapping.put(proj.getName(), data);\n\t\t}\n\t}\n\n\t/**\n\t * @param project\n\t * @return <code>true</code> if project has corresponding data\n\t */\n\tpublic boolean contains(IProject project) {\n\t\treturn projectMapping.containsKey(project.getName());\n\t}\n\n\t/**\n\t * @return {@code true} when at least one {@link GitSynchronizeData} is\n\t * configured to include changes only for particular folder,\n\t * {@code false} otherwise\n\t */\n\tpublic boolean containsFolderLevelSynchronizationRequest() {\n\t\treturn containsFolderLevelSynchronizationRequest;\n\t}\n\n\t/**\n\t * @return number of {@link GitSynchronizeData} that are included in this\n\t * set\n\t */\n\tpublic int size() {\n\t\treturn gsdSet.size();\n\t}\n\n\t/**\n\t * @param projectName\n\t * @return <code>null</code> if project does not have corresponding data\n\t */\n\tpublic GitSynchronizeData getData(String projectName) {\n\t\treturn projectMapping.get(projectName);\n\t}\n\n\t/**\n\t * @param project\n\t * @return <code>null</code> if project does not have corresponding data\n\t */\n\tpublic GitSynchronizeData getData(IProject project) {\n\t\treturn projectMapping.get(project.getName());\n\t}\n\n\t@Override\n\tpublic Iterator<GitSynchronizeData> iterator() {\n\t\treturn gsdSet.iterator();\n\t}\n\n\t/**\n\t * @return list of all resources\n\t */\n\tpublic IProject[] getAllProjects() {\n\t\tSet<IProject> resource = new HashSet<>();\n\t\tfor (GitSynchronizeData data : gsdSet) {\n\t\t\tresource.addAll(data.getProjects());\n\t\t}\n\t\treturn resource.toArray(new IProject[0]);\n\t}\n\n\t/**\n\t * @param res\n\t * @return whether the given resource should be included in the\n\t * synchronization.\n\t */\n\tpublic boolean shouldBeIncluded(IResource res) {\n\t\tfinal IProject project = res.getProject();\n\t\tif (project == null)\n\t\t\treturn false;\n\n\t\tfinal GitSynchronizeData syncData = getData(project);\n\t\tif (syncData == null)\n\t\t\treturn false;\n\n\t\tfinal Set<IResource> includedResources = syncData\n\t\t\t\t.getIncludedResources();\n\t\tif (includedResources == null)\n\t\t\treturn true;\n\n\t\tIPath path = res.getLocation();\n\t\tif (path != null) {\n\t\t\tfor (IResource resource : includedResources) {\n\t\t\t\tIPath inclResourceLocation = resource.getLocation();\n\t\t\t\tif (inclResourceLocation != null\n\t\t\t\t\t\t&& inclResourceLocation.isPrefixOf(path))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * @return {@code true} when fetch action should be forced before\n\t * synchronization, {@code false} otherwise.\n\t */\n\tpublic boolean forceFetch() {\n\t\treturn forceFetch;\n\t}\n\n\n\t/**\n\t * Disposes all nested resources\n\t */\n\tpublic void dispose() {\n\t\tif (projectMapping != null)\n\t\t\tprojectMapping.clear();\n\n\t\tif (gsdSet != null)\n\t\t\tfor (GitSynchronizeData gsd : gsdSet)\n\t\t\t\tgsd.dispose();\n\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\n\t\tfor (GitSynchronizeData data : gsdSet) {\n\t\t\tbuilder.append(data.getRepository().getWorkTree());\n\t\t\tbuilder.append(\" \"); //$NON-NLS-1$\n\t\t}\n\n\t\treturn builder.toString();\n\t}\n\n}" } ]
import org.eclipse.egit.core.synchronize.dto.GitSynchronizeData; import org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataSet; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.team.core.variants.SessionResourceVariantByteStore;
3,863
/******************************************************************************* * Copyright (c) 2010, 2013 IBM Corporation 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 * * Contributors: * IBM Corporation - initial API and implementation * Dariusz Luksza <[email protected]> * Laurent Goubet <[email protected]> - 393294 *******************************************************************************/ package org.eclipse.egit.core.synchronize; class GitRemoteResourceVariantTree extends GitResourceVariantTree { GitRemoteResourceVariantTree(GitSyncCache cache, GitSynchronizeDataSet data) { super(new SessionResourceVariantByteStore(), cache, data); } @Override protected ObjectId getObjectId(ThreeWayDiffEntry diffEntry) { return diffEntry.getRemoteId().toObjectId(); } @Override
/******************************************************************************* * Copyright (c) 2010, 2013 IBM Corporation 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 * * Contributors: * IBM Corporation - initial API and implementation * Dariusz Luksza <[email protected]> * Laurent Goubet <[email protected]> - 393294 *******************************************************************************/ package org.eclipse.egit.core.synchronize; class GitRemoteResourceVariantTree extends GitResourceVariantTree { GitRemoteResourceVariantTree(GitSyncCache cache, GitSynchronizeDataSet data) { super(new SessionResourceVariantByteStore(), cache, data); } @Override protected ObjectId getObjectId(ThreeWayDiffEntry diffEntry) { return diffEntry.getRemoteId().toObjectId(); } @Override
protected RevCommit getCommitId(GitSynchronizeData gsd) {
0
2023-10-20 15:17:51+00:00
8k
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;\n private static final int COLUMNS = 8;\n\n public BigBoard(final List<Enemy> enemies) {\n squares = new Enemy[ROWS][COLUMNS];\n int indexEnemy = 0;\n SQUARE_LOOP: for (int row = 0; row < ROWS; row++) {\n for (int column = 0; column < COLUMNS; column++) {\n if (indexEnemy < enemies.size()) {\n \tsquares[row][column] = enemies.get(indexEnemy);\n indexEnemy++;\n } else {\n break SQUARE_LOOP;\n }\n }\n }\n this.iterator = new BoardIterator(this);\n }\n\n\t@Override\n public int getRows() {\n return ROWS;\n }\n\n\t@Override\n public int getColumns() {\n return COLUMNS;\n }\n\n\t@Override\n public Enemy getEnemy(final int row, final int column) {\n return squares[row][column];\n }\n\n\t@Override\n\tpublic void deleteEnemy(final int row, final int column) {\n SQUARE_LOOP: for (int rowCurrent = row; rowCurrent < ROWS; rowCurrent++) {\n for (int columnCurrent = column; columnCurrent < COLUMNS; columnCurrent++) {\n \tif ((rowCurrent != ROWS - 1) || (columnCurrent != COLUMNS - 1)) {\n \t\tfinal int rowNext;\n \t\tfinal int columnNext = columnCurrent < COLUMNS - 1 ? columnCurrent + 1 : 0;\n \t\tif (columnCurrent == COLUMNS - 1) {\n \t\trowNext = rowCurrent < ROWS - 1 ? rowCurrent + 1 : 0;\n \t\t} else {\n \t\t\trowNext = rowCurrent;\n \t\t}\n \tfinal Enemy enemyNext = squares[rowNext][columnNext];\n \tif (enemyNext == null) {\n \tsquares[rowCurrent][columnCurrent] = null;\n \t\tbreak SQUARE_LOOP;\n \t}\n \tsquares[rowCurrent][columnCurrent] = enemyNext;\n \t} else {\n \tsquares[rowCurrent][columnCurrent] = null;\n break SQUARE_LOOP;\n \t}\n }\n }\n }\n\n\t@Override\n\tpublic String getAvatarSquare(final int row, final int column) {\n\t\tfinal Enemy enemy = squares[row][column];\n\t\tfinal StringBuilder avatarSquare = new StringBuilder();\n\t\tif (enemy != null) {\n\t\t\tavatarSquare.append(\"{\");\n\t\t\tavatarSquare.append(row);\n\t\t\tavatarSquare.append(\"-\");\n\t\t\tavatarSquare.append(column);\n\t\t\tavatarSquare.append(\":\");\n\t\t\tfinal String avatar = enemy.getAvatar(\"\");\n\t\t\tavatarSquare.append(!avatar.isEmpty() ? avatar.substring(0, avatar.length() - 1) : \"\");\n\t\t\tavatarSquare.append(\":\");\n\t\t\tavatarSquare.append(enemy.getLife());\n\t\t\tavatarSquare.append(\":\");\n\t\t\tavatarSquare.append(enemy.getAttackLevel(false));\n\t\t\tavatarSquare.append(\"}\");\n\t\t\tif (column == COLUMNS - 1) {\n\t\t\t\tavatarSquare.append(\"\\n\");\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn avatarSquare.toString();\n\t}\n\n\t@Override\n\tpublic PatternsIterator<Enemy> getIterator() {\n\t\treturn this.iterator;\n\t}\n\n}" }, { "identifier": "ConjunctionExpression", "path": "src/main/application/driver/adapter/usecase/expression/ConjunctionExpression.java", "snippet": "public class ConjunctionExpression implements Expression {\n\tprivate final Expression leftExpression;\n\tprivate final Expression rightExpression;\n\t\n\tpublic ConjunctionExpression(final Expression leftExpression, final Expression rightExpression) {\n\t\tthis.leftExpression = leftExpression;\n\t\tthis.rightExpression = rightExpression;\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n\t\tList<String> leftAvatarSquares = leftExpression.interpret(context);\n\t\tList<String> rightAvatarSquares = rightExpression.interpret(context);\n\t\tList<String> avatarSquares = new ArrayList<>(leftAvatarSquares);\n\t\tavatarSquares.retainAll(rightAvatarSquares);\n return avatarSquares;\n\t}\n\n}" }, { "identifier": "Context", "path": "src/main/application/driver/adapter/usecase/expression/Context.java", "snippet": "public class Context {\n\tprivate final List<String> avatarSquares;\n\t\n\tpublic Context(final List<String> avatarSquares) {\n\t\tthis.avatarSquares = avatarSquares;\n\t}\n\t\n\tpublic List<String> getAvatarSquares() {\n\t\treturn this.avatarSquares;\n\t}\n}" }, { "identifier": "AlternativeExpression", "path": "src/main/application/driver/adapter/usecase/expression/AlternativeExpression.java", "snippet": "public class AlternativeExpression implements Expression {\n\tprivate final Expression leftExpression;\n\tprivate final Expression rightExpression;\n\t\n\tpublic AlternativeExpression(final Expression leftExpression, final Expression rightExpression) {\n\t\tthis.leftExpression = leftExpression;\n\t\tthis.rightExpression = rightExpression;\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n\t\tList<String> leftAvatarSquares = leftExpression.interpret(context);\n\t\tList<String> rightAvatarSquares = rightExpression.interpret(context);\n\t\tSet<String> avatarSquares = new LinkedHashSet<>(leftAvatarSquares);\n\t\tavatarSquares.addAll(rightAvatarSquares);\n return new ArrayList<>(avatarSquares);\n\t}\n\n}" }, { "identifier": "EnemyExpression", "path": "src/main/application/driver/adapter/usecase/expression/EnemyExpression.java", "snippet": "public class EnemyExpression implements Expression {\n\tprivate final String word;\n\n\tpublic EnemyExpression(String word) {\n\t\tthis.word = switch(word.toLowerCase()) {\n\t\tcase \"soldado\" -> \"S\";\n\t\tcase \"aire\" -> \"A\";\n\t\tcase \"naval\" -> \"N\";\n\t\tcase \"fortaleza\" -> \"F\";\n\t\tcase \"escuadron\", \"escuadrón\" -> \"E\";\n\t\tcase \"supremo\", \"maestro\", \"jefe\" -> \"J\";\n\t\tdefault -> word.toUpperCase();\n\t\t};\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n return context.getAvatarSquares().stream()\n .filter(avatarSquare -> avatarSquare.contains(this.word))\n .toList();\n\t}\n\n}" }, { "identifier": "EnemyBasicMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyBasicMethod.java", "snippet": "public class EnemyBasicMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyBasicMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<Enemy>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Poison());\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 8;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tif (created <= Math.round(enemies.size() / 3)){\n\t\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Heat();\n\t\t\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "EnemyHighMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyHighMethod.java", "snippet": "public class EnemyHighMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyHighMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 5;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t}\n\n\t\t// soldiers with fort\n final int quantitySoldiersWithFork = 2;\n\t\tfor (int created = 1; created <= quantitySoldiersWithFork; created++) {\n\t\t\tenemies.add(new Fort(soldierEnemyBase.clone()));\n\t\t}\n\t\t\n\t\t// infantry\n final int quantitySquadron = 2;\n final int quantitySoldiersForSquadron = 3;\n\t\tfinal List<Enemy> squadronsAndSoldiers = new ArrayList<>();\n\t\tfor (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {\n\t\t\tfinal List<Enemy> soldiers = new ArrayList<>();\n\t\t\tfor (int created = 1; created <= quantitySoldiersForSquadron; created++) {\n\t\t\t\tsoldiers.add(soldierEnemyBase.clone());\n\t\t\t}\n\t\t\tEnemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));\n\t\t\tif (createdSquadron == 1) {\n\t\t\t\tsquadron = new Fort(squadron);\n\t\t\t}\n\t\t\tsquadronsAndSoldiers.add(squadron);\n\t\t}\n final int quantitySoldiersInSquadron = 4;\n\t\tfor (int created = 1; created <= quantitySoldiersInSquadron; created++) {\n\t\t\tsquadronsAndSoldiers.add(soldierEnemyBase.clone());\n\t\t}\n\t\tfinal Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());\n\t\tenemies.add(infantry);\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Heat();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentThird = new Rainy();\n\t\tfinal FavorableEnvironment favorableEnvironmentFourth = new Jungle(12);\n\t\tfinal FavorableEnvironment favorableEnvironmentFifth = new City(83);\n\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\tfavorableEnvironmentSecond.setNextFavorableEnvironment(favorableEnvironmentThird);\n\t\tfavorableEnvironmentThird.setNextFavorableEnvironment(favorableEnvironmentFourth);\n\t\tfavorableEnvironmentFourth.setNextFavorableEnvironment(favorableEnvironmentFifth);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "EnemyMiddleMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyMiddleMethod.java", "snippet": "public class EnemyMiddleMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyMiddleMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(2));\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 6;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tif (created <= Math.round(enemies.size() / 2)){\n\t\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// infantry\n final int quantitySquadron = 2;\n final int quantitySoldiersForSquadron = 3;\n\t\tfinal List<Enemy> squadronsAndSoldiers = new ArrayList<>();\n\t\tfor (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {\n\t\t\tfinal List<Enemy> soldiers = new ArrayList<>();\n\t\t\tfor (int created = 1; created <= quantitySoldiersForSquadron; created++) {\n\t\t\t\tsoldiers.add(soldierEnemyBase.clone());\n\t\t\t}\n\t\t\tfinal Enemy squadron = armyFactory.createSquadron(soldiers, new Poison());\n\t\t\tsquadronsAndSoldiers.add(squadron);\n\t\t}\n final int quantitySoldiersInSquadron = 3;\n\t\tfor (int created = 1; created <= quantitySoldiersInSquadron; created++) {\n\t\t\tsquadronsAndSoldiers.add(soldierEnemyBase.clone());\n\t\t}\n\t\tfinal Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new MultipleShots(2));\n\t\tenemies.add(infantry);\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Jungle(12);\n\t\tfinal FavorableEnvironment favorableEnvironmentThird = new City(83);\n\t\tfinal FavorableEnvironment favorableEnvironmentFourth = new Heat();\n\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\tfavorableEnvironmentSecond.setNextFavorableEnvironment(favorableEnvironmentThird);\n\t\tfavorableEnvironmentThird.setNextFavorableEnvironment(favorableEnvironmentFourth);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "BasicMission", "path": "src/main/application/driver/adapter/usecase/mission/BasicMission.java", "snippet": "public class BasicMission extends Mission {\n\n\tpublic BasicMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isWeakened = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisWeakened = enemy.getLife() < 150;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isWeakened;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\treturn true;\n\t}\n\n}" }, { "identifier": "HighMission", "path": "src/main/application/driver/adapter/usecase/mission/HighMission.java", "snippet": "public class HighMission extends Mission {\n\n\tpublic HighMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isSupremeDead = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisSupremeDead = enemy.getLife() <= 0;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSupremeDead;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\tboolean isFortAlive = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tif(this.enemyIterator.getNext() instanceof Fort) {\n\t\t\t\tisFortAlive = false;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isFortAlive;\n\t}\n\n}" }, { "identifier": "MiddleMission", "path": "src/main/application/driver/adapter/usecase/mission/MiddleMission.java", "snippet": "public class MiddleMission extends Mission {\n\n\tpublic MiddleMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isWeakened = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisWeakened = enemy.getLife() < 80;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isWeakened;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\tint squadronsAlive = 0;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SquadronAir || enemy instanceof SquadronNaval) {\n\t\t\t\t++squadronsAlive;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn squadronsAlive <= 1;\n\t}\n\n}" }, { "identifier": "EnemyMethod", "path": "src/main/application/driver/port/usecase/EnemyMethod.java", "snippet": "public interface EnemyMethod {\n\tList<Enemy> createEnemies();\n\tFavorableEnvironment createFavorableEnvironments();\n}" }, { "identifier": "Expression", "path": "src/main/application/driver/port/usecase/Expression.java", "snippet": "public interface Expression {\n\tList<String> interpret(Context context);\n}" }, { "identifier": "GameableUseCase", "path": "src/main/application/driver/port/usecase/GameableUseCase.java", "snippet": "public interface GameableUseCase {\n\tvoid startGame();\n\tBoolean[] attackAndCounterAttack(int row, int column);\n\tBoolean[] attackWithComboAndCounterAttack(int row, int column);\n\tvoid calculateFreezing();\n\tboolean isFrozen();\n\tint getTurnsForDefrost();\n\tvoid plusTurnFrozen();\n\tString getStringAvatarSquares();\n\tString getStringAvatarPlayer();\n\tvoid removeDeadEnemies();\n\tString getEnemies(String stringExpression);\n\tvoid healing();\n\tboolean doOrRestoreBackup(String inputString);\n\tboolean isGameCompleted();\n\tboolean verifyAnUpLevel();\n}" }, { "identifier": "BoardCollection", "path": "src/main/application/driver/port/usecase/iterator/BoardCollection.java", "snippet": "public interface BoardCollection<T> {\n int getRows();\n int getColumns();\n Enemy getEnemy(int row, int column);\n\tvoid deleteEnemy(int row, int column);\n\tString getAvatarSquare(int row, int column);\n\tPatternsIterator<T> getIterator();\n}" }, { "identifier": "PatternsIterator", "path": "src/main/application/driver/port/usecase/iterator/PatternsIterator.java", "snippet": "public interface PatternsIterator<T> {\n\tboolean hasNext();\n T getNext();\n\tvoid remove();\n String getAvatarSquareNext();\n void reset();\n}" }, { "identifier": "ArmyFactory", "path": "src/main/domain/model/ArmyFactory.java", "snippet": "public interface ArmyFactory {\n\tPlayer createPlayer(PlayerBuilder playerBuilder);\n\tSoldier createSoldier(int life, int attackLevel, Skillfull skill);\n\tEnemy createSquadron(List<Enemy> squadron, Skillfull skill);\n\tSupreme getSupreme();\n}" }, { "identifier": "CaretakerPlayer", "path": "src/main/domain/model/CaretakerPlayer.java", "snippet": "public class CaretakerPlayer {\n private final Map<String, MementoPlayer> mementosPlayerByKey;\n \n public CaretakerPlayer() {\n \tthis.mementosPlayerByKey = new HashMap<>();\n }\n\n public void addMementoPlayerByKey(final String key, final MementoPlayer mementoPlayer) {\n \tthis.mementosPlayerByKey.put(key, mementoPlayer);\n }\n\n public MementoPlayer getMementoPlayerByKey(final String key) {\n return this.mementosPlayerByKey.get(key);\n }\n}" }, { "identifier": "Command", "path": "src/main/domain/model/Command.java", "snippet": "public interface Command {\n\tvoid execute();\n}" }, { "identifier": "Enemy", "path": "src/main/domain/model/Enemy.java", "snippet": "public abstract class Enemy implements Protective {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final Skillfull skill;\n\tprotected Status status;\n\t\n\tpublic Enemy(int life, int attackLevel, Skillfull skill) {\n\t\tthis.life = life;\n\t\tthis.attackLevel = attackLevel;\n\t\tthis.skill = skill;\n\t\tthis.status = new Asleep();\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel(boolean isAttacking) {\n\t\treturn this.skill.getEnhancedAttackLevel(this.attackLevel, isAttacking);\n\t}\n\t\n\tpublic int getCounterAttackLevel(final int attackLevelReceived) {\n\t\treturn this.status.getAttackLevel(attackLevelReceived, this);\n\t}\n\t\n\tpublic void setStatus(final Status status) {\n\t\tthis.status = status;\n\t}\n\t\n\t@Override\n\tpublic void protect(final Supreme theProtected) {\n\t\tthis.receiveAttack(1);\n\t\tif (this.getLife() <= 0) {\n\t\t\ttheProtected.removeProtector(this);\n\t\t}\n\t}\n\n\tpublic abstract void receiveAttack(final int attack);\n\t\n\tpublic abstract String getAvatar(final String prefix);\n\t\n\tpublic abstract void acceptVisit(Visitor visitor);\n}" }, { "identifier": "FavorableEnvironment", "path": "src/main/domain/model/FavorableEnvironment.java", "snippet": "public interface FavorableEnvironment {\n\tvoid setNextFavorableEnvironment(FavorableEnvironment favorableEnvironment);\n\tboolean canAttack(Enemy enemy);\n\tboolean canHandleAttack(Enemy enemy);\n}" }, { "identifier": "Healable", "path": "src/main/domain/model/Healable.java", "snippet": "public class Healable implements Visitor {\n\n\t@Override\n\tpublic void visitSoldier(Soldier soldier) {\n\t\tif (soldier.getTypeHair().equalsIgnoreCase(\"corto\")) {\n\t\t\tsoldier.life += 1;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void visitSquadron(Squadron squadron) {\n\t\tfor (Enemy enemy : squadron.squadronList) {\n\t\t\tenemy.acceptVisit(this);\n\t\t}\n\t\tsquadron.calculateLife();\n\t}\n\n\t@Override\n\tpublic void visitSupreme(Supreme supreme) {\n\t\tsupreme.life += 1;\n\t}\n\n\t@Override\n\tpublic void visitPlayer(Player player) {\n\t\tplayer.life += 50;\n\t}\n\n}" }, { "identifier": "Mission", "path": "src/main/domain/model/Mission.java", "snippet": "public abstract class Mission {\n\tprotected final BoardCollection<Enemy> board;\n\tprotected final PatternsIterator<Enemy> enemyIterator;\n\t\n\tpublic Mission(BoardCollection<Enemy> board) {\n\t\tthis.board = board;\n\t\tthis.enemyIterator = this.board.getIterator();\n\t}\n\t\n\tpublic boolean isMissionComplete() {\n\t\treturn this.isMainObjectiveComplete()\n\t\t\t\t&& this.isSecondaryObjectiveComplete()\n\t\t\t\t&& this.isTertiaryObjectiveComplete();\n\t}\n\n\tprotected abstract boolean isMainObjectiveComplete();\n\tprotected abstract boolean isSecondaryObjectiveComplete();\n\t\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\tboolean isSoldierAlive = false;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SoldierAir || enemy instanceof SoldierNaval) {\n\t\t\t\tisSoldierAlive = true;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSoldierAlive;\n\t}\n\n}" }, { "identifier": "Player", "path": "src/main/domain/model/Player.java", "snippet": "public abstract class Player {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final String name;\n\tprotected final Type type;\n\tprotected final String typeEye;\n\tprotected final String typeHair;\n\tprotected final String typeShirt;\n\tprotected final String typePant;\n\tprotected final String typeShoes;\n\t\n\tpublic Player(final PlayerBuilder builder) {\n\t\tthis.life = 250;\n\t\tthis.attackLevel = 10;\n\t\tthis.name = builder.name() != null && builder.name() != \"\" ? builder.name() : \"NN\";\n\t\tthis.type = builder.type() != null ? builder.type() : new WarriorType();\n\t\tthis.typeEye = builder.typeEye() != null && builder.typeEye() != \"\" ? builder.typeEye() : \"lentes\";\n\t\tthis.typeHair = builder.typeHair() != null && builder.typeHair() != \"\" ? builder.typeHair() : \"corto\";\n\t\tthis.typeShirt = builder.typeShirt() != null && builder.typeShirt() != \"\" ? builder.typeShirt() : \"franela\";\n\t\tthis.typePant = builder.typePant() != null && builder.typePant() != \"\" ? builder.typePant() : \"largos\";\n\t\tthis.typeShoes = builder.typeShoes() != null && builder.typeShoes() != \"\" ? builder.typeShoes() : \"tennis\";\n\t}\n\t\n\tpublic abstract String getAvatar();\n\t\n\tpublic void acceptVisit(Visitor visitor) {\n\t\tvisitor.visitPlayer(this);\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel() {\n\t\treturn this.attackLevel;\n\t}\n\t\n\tpublic void receiveAttack(final int attack) {\n\t\tthis.life -= attack;\n\t}\n\t\n\tpublic MementoPlayer doBackup() {\n\t\treturn new MementoPlayer(this);\n\t}\n\t\n\tpublic void restoreMemento(final MementoPlayer memento) {\n\t\tthis.life = memento.life;\n\t\tthis.attackLevel = memento.attackLevel;\n\t}\n\t\n\tpublic class MementoPlayer { //anidada para obtener todas las propiedades mutables sin problemas de visibilidad\n\t\tprivate final int life;\n\t\tprivate final int attackLevel;\n\t\t\n\t\t//las propiedades del memento deben ser inmutables y son las propiedades mutables de la clase originadora(en este caso la clase Player)\n\t\tpublic MementoPlayer(Player player) {\n\t\t\tthis.life = player.life;\n\t\t\tthis.attackLevel = player.attackLevel;\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "MementoPlayer", "path": "src/main/domain/model/Player.java", "snippet": "public class MementoPlayer { //anidada para obtener todas las propiedades mutables sin problemas de visibilidad\n\tprivate final int life;\n\tprivate final int attackLevel;\n\t\t\n\t//las propiedades del memento deben ser inmutables y son las propiedades mutables de la clase originadora(en este caso la clase Player)\n\tpublic MementoPlayer(Player player) {\n\t\tthis.life = player.life;\n\t\tthis.attackLevel = player.attackLevel;\n\t}\n\t\t\n}" }, { "identifier": "Attack", "path": "src/main/domain/model/command/Attack.java", "snippet": "public class Attack implements Command {\n\tprivate final FavorableEnvironment favorableEnvironments;\n\tprivate final int playerAttackLevel;\n\tprivate final Enemy enemy;\n\n\t//sus propiedades deben ser inmutables ya que se podría ejecutar en cualquier momento y no deben haber cambiado\n\t//por lo tanto tener cuidado con los objetos pasados por parámetros y sus propiedades que no cambien hasta ser ejecutado el comando\n\tpublic Attack(final FavorableEnvironment favorableEnvironments, final int playerAttackLevel, final Enemy enemy) {\n\t\tthis.favorableEnvironments = favorableEnvironments;\n\t\tthis.playerAttackLevel = playerAttackLevel;\n\t\tthis.enemy = enemy;\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tif (this.enemy.getLife() > 0) { //esta propiedad como excepción a la regla se permite ser mutable ya que cuando se ejecute el comando el enemigo ya podría estar muerto\n\t\t\tfinal boolean isSuccessfulAttack = this.favorableEnvironments.canAttack(this.enemy);\n\t\t\tif (isSuccessfulAttack) {\n\t\t\t\tthis.enemy.receiveAttack(this.playerAttackLevel);\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "HealingPlayer", "path": "src/main/domain/model/command/HealingPlayer.java", "snippet": "public class HealingPlayer implements Command {\n\tprivate final Player player;\n\tprivate final Visitor healable;\n\n\t//sus propiedades deben ser inmutables ya que se podría ejecutar en cualquier momento y no deben haber cambiado\n\t//por lo tanto tener cuidado con los objetos pasados por parámetros y sus propiedades que no cambien hasta ser ejecutado el comando\n\tpublic HealingPlayer(Player player) {\n\t\tthis.player = player;\n\t\tthis.healable = new Healable();\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tthis.player.acceptVisit(this.healable);\n\t}\n\n}" }, { "identifier": "Visitor", "path": "src/main/domain/model/Visitor.java", "snippet": "public interface Visitor {\n\tvoid visitSoldier(Soldier soldier);\n\tvoid visitSquadron(Squadron squadron);\n\tvoid visitSupreme(Supreme supreme);\n\tvoid visitPlayer(Player player);\n}" } ]
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,197
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;
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;
17
2023-10-20 18:36:47+00:00
8k
greatwqs/finance-manager
src/main/java/com/github/greatwqs/app/controller/UserController.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 */\n public static final String ERROR_CODE_PREFIX_KEY = \"error.code.\";\n\n /**\n * request set attribute names\n * RequestContextHolder.currentRequestAttributes().setAttribute(name, value)\n */\n public static final String REQUEST_USER_TOKEN = \"requestUserToken\";\n public static final String REQUEST_USER = \"requestUser\";\n\n /***\n * 用户登录过期时间, 2小时.\n */\n public static final Long USER_LOGIN_SESSION_EXPIRE_TIME = 1000L * 60 * 60 * 2;\n\n /***\n * 分页时, 每页 Item 数量\n */\n public static final Integer DEFAULT_PAGE_SIZE = 50;\n // 订单每页 Item 数量\n public static final Integer ORDER_PAGE_SIZE = DEFAULT_PAGE_SIZE;\n\n /***\n * 用户密码最小/大位数\n */\n public static final Integer PASSWORD_MIN_LENGTH = 8;\n public static final Integer PASSWORD_MAX_LENGTH = 30;\n\n /***\n * 用户登录成功的cookie\n */\n public static final String COOKIE_LOGIN_TOKEN = \"loginToken\";\n public static final String APP_LOGIN_TOKEN = COOKIE_LOGIN_TOKEN;\n\n public static final String PAGE_LOGIN = \"/login.jsp\";\n public static final String PAGE_LOGIN_FAILED = \"/login_failed.jsp\";\n public static final String PAGE_ORDER_QUERY = \"/order_query\";\n public static final String PAGE_USER_ALL_LIST = \"/order_query?isHide=11\";\n public static final String PAGE_USER_UPDATE_PASSWORD = \"/order_query?isHide=1001\";\n}" }, { "identifier": "AppException", "path": "src/main/java/com/github/greatwqs/app/common/exception/AppException.java", "snippet": "public class AppException extends RuntimeException {\n\n private ErrorCode errorCode;\n\n // rewrite default msg in i18n/message.properties\n private String errorMsg;\n\n private List<Object> errorMsgParams;\n\n /***\n * use default msg in i18n/message.properties\n * @param errorCode\n */\n public AppException(ErrorCode errorCode) {\n this.errorCode = errorCode;\n }\n\n /***\n * use default msg with ${errorMsgParams} in i18n/message.properties\n * @param errorCode\n * @param errorMsgParams\n */\n public AppException(ErrorCode errorCode, List<Object> errorMsgParams) {\n this.errorCode = errorCode;\n this.errorMsgParams = errorMsgParams;\n }\n\n /***\n * rewrite default msg\n * @param errorCode\n * @param errorMsg\n */\n public AppException(ErrorCode errorCode, String errorMsg) {\n this.errorCode = errorCode;\n this.errorMsg = errorMsg;\n }\n\n public ErrorCode getErrorCode() {\n return errorCode;\n }\n\n public void setErrorCode(ErrorCode errorCode) {\n this.errorCode = errorCode;\n }\n\n public String getErrorMsg() {\n return errorMsg;\n }\n\n public void setErrorMsg(String errorMsg) {\n this.errorMsg = errorMsg;\n }\n\n public List<Object> getErrorMsgParams() {\n return errorMsgParams;\n }\n\n public void setErrorMsgParams(List<Object> errorMsgParams) {\n this.errorMsgParams = errorMsgParams;\n }\n}" }, { "identifier": "ErrorCode", "path": "src/main/java/com/github/greatwqs/app/common/exception/ErrorCode.java", "snippet": "public enum ErrorCode {\n\n /**\n * HTTP STATUS CODE [0-1000)\n **/\n NORMAL_SUCCESS(200, HttpStatus.OK.value()),\n BAD_REQUEST(400, HttpStatus.BAD_REQUEST.value()),\n UNAUTHORIZED(401, HttpStatus.UNAUTHORIZED.value()),\n FORBIDDEN(403, HttpStatus.FORBIDDEN.value()),\n NOT_FOUND(404, HttpStatus.NOT_FOUND.value()),\n METHOD_NOT_ALLOWED(405, HttpStatus.METHOD_NOT_ALLOWED.value()),\n CONFLICT(409, HttpStatus.CONFLICT.value()),\n UNSUPPORTED_MEDIA_TYPE(415, HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()),\n INTERNAL_SERVER_ERROR(500, HttpStatus.INTERNAL_SERVER_ERROR.value()),\n\n /**\n * Bisiness ERROR [1000-2000)\n **/\n BIZ_UNKNOWN_ERROR(1000, HttpStatus.INTERNAL_SERVER_ERROR.value()),\n USER_LOGIN_ERROR(1001, HttpStatus.FOUND.value()),\n USER_LOGIN_TOKEN_ERROR(1002, HttpStatus.FOUND.value()),\n SUBJECT_NOT_FOUND(1003, HttpStatus.NOT_FOUND.value()),\n TICKET_TYPE_NOT_FOUND(1004, HttpStatus.NOT_FOUND.value()),\n ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE(1005, HttpStatus.BAD_REQUEST.value()),\n ORDER_NOT_FOUND(1006, HttpStatus.NOT_FOUND.value()),\n UPDATE_PASSWORD_CAN_NOT_EMPTY(1007, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_OLD_PASSWORD_NOT_MATCH(1008, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_NEW_PASSWORD_CONFIRM_NOT_MATCH(1009, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_NEW_PASSWORD_LENGTH_NOT_OK(1010, HttpStatus.BAD_REQUEST.value()),\n\n /**\n * Outer Call ERROR [2000+)\n **/\n OUT_UNKNOWN_ERROR(3000, HttpStatus.INTERNAL_SERVER_ERROR.value());\n\n\n private Integer errorCode;\n private Integer httpCode;\n private String errorMsgKey;\n\n ErrorCode(Integer errorCode, Integer httpCode) {\n this.errorCode = errorCode;\n this.httpCode = httpCode;\n }\n\n ErrorCode(Integer errorCode, Integer httpCode, String errorMsgKey) {\n this.errorCode = errorCode;\n this.httpCode = httpCode;\n this.errorMsgKey = errorMsgKey;\n }\n\n /***\n * get error message key.\n * @return example `error.code.2000`\n */\n public String getErrorMsgKey() {\n if (StringUtils.isNotEmpty(errorMsgKey)) {\n return errorMsgKey;\n }\n return AppConstants.ERROR_CODE_PREFIX_KEY + this.errorCode;\n }\n\n public Integer getErrorCode() {\n return errorCode;\n }\n\n public Integer getHttpCode() {\n return httpCode;\n }\n}" }, { "identifier": "RequestComponent", "path": "src/main/java/com/github/greatwqs/app/component/RequestComponent.java", "snippet": "@Slf4j\n@Component\npublic class RequestComponent {\n\n public HttpServletRequest getRequest() {\n if (getRequestAttributes() != null) {\n return getRequestAttributes().getRequest();\n } else {\n return null;\n }\n }\n\n public String getRequestUri() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"unkonw uri\";\n } else {\n return request.getRequestURI();\n }\n }\n\n public String getRequestUrl() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"unkonw url\";\n } else {\n return request.getRequestURL().toString();\n }\n }\n\n public HttpServletResponse getResponse() {\n return getRequestAttributes().getResponse();\n }\n\n public ServletRequestAttributes getRequestAttributes() {\n return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());\n }\n\n /***\n * getExecuteIp\n * @return\n */\n public String getClientIp() {\n HttpServletRequest request = getRequest();\n if (request == null) {\n return \"\";\n }\n String ip = request.getHeader(\"x-forwarded-for\");\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"Proxy-Client-IP\");\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"WL-Proxy-Client-IP\");\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getRemoteAddr();\n }\n if (StringUtils.isBlank(ip) || \"unknown\".equalsIgnoreCase(ip)) {\n ip = request.getHeader(\"X-Real-IP\");\n }\n if (ip != null && ip.trim().length() > 0) {\n int index = ip.indexOf(',');\n return (index != -1) ? ip.substring(0, index) : ip;\n }\n return ip;\n }\n\n /***\n * default zh_CN\n * @return\n */\n public Locale getLocale() {\n return AppConstants.LOCALE;\n }\n\n /***\n * get locale\n * @return\n */\n private Locale getRequestLocale() {\n HttpServletRequest request = getRequest();\n final String APP_LOCALE = \"app_locale\";\n final Cookie cookie = WebUtils.getCookie(request, APP_LOCALE);\n if (cookie != null && StringUtils.isNotEmpty(cookie.getValue())) {\n return org.springframework.util.StringUtils.parseLocaleString(cookie.getValue());\n }\n\n /**\n * based on the Accept-Language header. If the client request\n * doesn't provide an Accept-Language header, this method returns the\n * default locale for the server.\n */\n return request.getLocale();\n }\n\n public void setParam(String key, Object value) {\n RequestContextHolder.currentRequestAttributes()\n .setAttribute(key, value, RequestAttributes.SCOPE_REQUEST);\n }\n\n public Object getParam(String key) {\n return RequestContextHolder.currentRequestAttributes()\n .getAttribute(key, RequestAttributes.SCOPE_REQUEST);\n }\n\n public UserPo getLoginUser() {\n return (UserPo) RequestContextHolder.currentRequestAttributes()\n .getAttribute(AppConstants.REQUEST_USER, RequestAttributes.SCOPE_REQUEST);\n }\n\n public String getLoginToken() {\n return (String) RequestContextHolder.currentRequestAttributes()\n .getAttribute(AppConstants.REQUEST_USER_TOKEN, RequestAttributes.SCOPE_REQUEST);\n }\n}" }, { "identifier": "UserPo", "path": "src/main/java/com/github/greatwqs/app/domain/po/UserPo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class UserPo {\n\n\tprivate Long id;\n\n\tprivate String username;\n\n\tprivate String password;\n\n\tprivate String content;\n\n\tprivate Boolean issuperadmin;\n\n\tprivate Boolean isvalid;\n\n\tprivate Date createtime;\n\n\tprivate Date updatetime;\n}" }, { "identifier": "UserVo", "path": "src/main/java/com/github/greatwqs/app/domain/vo/UserVo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class UserVo {\n\n\tprivate Long id;\n\n\tprivate String username;\n\n\t@JsonIgnore\n\tprivate String password;\n\n\tprivate String address;\n\n\tprivate Boolean issuperadmin;\n\n\tprivate Boolean isvalid;\n\n\tprivate Date createtime;\n\n\tprivate Date updatetime;\n}" }, { "identifier": "UserService", "path": "src/main/java/com/github/greatwqs/app/service/UserService.java", "snippet": "public interface UserService {\n\n\t/***\n\t * 用户登录, 登录成功返回LoginToken, 否则返回null\n\t * @param username\n\t * @param password\n\t * @return\n\t */\n\tString login(String username, String password, String loginIp);\n\n\t/**\n\t * 用户退出登录\n\t * @param userPo\n\t * @return\n\t */\n\tvoid logout(UserPo userPo, String loginToken);\n\n\t/***\n\t * 返回所有用户.\n\t * userPo 如果是超级用户, 返回所有的用户列表.\n\t * 如果是普通用户, 返回为空!\n\t * @param userPo\n\t * @return\n\t */\n\tList<UserVo> allUsers(UserPo userPo);\n\n\t/***\n\t * 用户添加, 返回创建的用户ID\n\t * @param username\n\t * @param content\n\t * @param userPo\n\t * @return\n\t */\n\tLong create(String username, String content, UserPo userPo);\n\n\t/**\n\t * 删除用户\n\t * @param deletedUserId 需要被删除的用户ID\n\t * @param userPo 当前登录管理员\n\t */\n\tvoid delete(Long deletedUserId, UserPo userPo);\n\n\t/***\n\t * 用户自己更新自己密码\n\t * @param userPo\n\t * @param oldPassword\n\t * @param newPassword\n\t * @param newPasswordConfirm\n\t */\n\tvoid updatePassword(UserPo userPo, String oldPassword, String newPassword, String newPasswordConfirm);\n}" }, { "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 */\n public static final String ERROR_CODE_PREFIX_KEY = \"error.code.\";\n\n /**\n * request set attribute names\n * RequestContextHolder.currentRequestAttributes().setAttribute(name, value)\n */\n public static final String REQUEST_USER_TOKEN = \"requestUserToken\";\n public static final String REQUEST_USER = \"requestUser\";\n\n /***\n * 用户登录过期时间, 2小时.\n */\n public static final Long USER_LOGIN_SESSION_EXPIRE_TIME = 1000L * 60 * 60 * 2;\n\n /***\n * 分页时, 每页 Item 数量\n */\n public static final Integer DEFAULT_PAGE_SIZE = 50;\n // 订单每页 Item 数量\n public static final Integer ORDER_PAGE_SIZE = DEFAULT_PAGE_SIZE;\n\n /***\n * 用户密码最小/大位数\n */\n public static final Integer PASSWORD_MIN_LENGTH = 8;\n public static final Integer PASSWORD_MAX_LENGTH = 30;\n\n /***\n * 用户登录成功的cookie\n */\n public static final String COOKIE_LOGIN_TOKEN = \"loginToken\";\n public static final String APP_LOGIN_TOKEN = COOKIE_LOGIN_TOKEN;\n\n public static final String PAGE_LOGIN = \"/login.jsp\";\n public static final String PAGE_LOGIN_FAILED = \"/login_failed.jsp\";\n public static final String PAGE_ORDER_QUERY = \"/order_query\";\n public static final String PAGE_USER_ALL_LIST = \"/order_query?isHide=11\";\n public static final String PAGE_USER_UPDATE_PASSWORD = \"/order_query?isHide=1001\";\n}" } ]
import com.github.greatwqs.app.common.AppConstants; import com.github.greatwqs.app.common.exception.AppException; import com.github.greatwqs.app.common.exception.ErrorCode; import com.github.greatwqs.app.component.RequestComponent; import com.github.greatwqs.app.domain.po.UserPo; import com.github.greatwqs.app.domain.vo.UserVo; import com.github.greatwqs.app.interceptor.annotation.LoginRequired; import com.github.greatwqs.app.service.UserService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static com.github.greatwqs.app.common.AppConstants.*;
3,794
package com.github.greatwqs.app.controller; /** * 用户业务模块 * * @author greatwqs * Create on 2020/6/25 */ @Slf4j @RestController @RequestMapping("user") public class UserController { @Autowired private ModelMapper modelMapper; @Autowired private UserService userService; @Autowired private RequestComponent requestComponent; /** * 用户详情 */ @LoginRequired @RequestMapping(value = "info", method = RequestMethod.GET) public UserVo getUserInfo() { UserPo userPo = requestComponent.getLoginUser(); return modelMapper.map(userPo, UserVo.class); } /** * 用户登录 */ @RequestMapping(value = "login", method = RequestMethod.POST) public void login(Model mode, @RequestParam(value = "username") String username, @RequestParam(value = "password") String password, HttpServletResponse response) throws IOException { final String loginIp = requestComponent.getClientIp(); final String loginToken = userService.login(username, password, loginIp); if (StringUtils.isEmpty(loginToken)) { log.warn("user login failed! username: " + username);
package com.github.greatwqs.app.controller; /** * 用户业务模块 * * @author greatwqs * Create on 2020/6/25 */ @Slf4j @RestController @RequestMapping("user") public class UserController { @Autowired private ModelMapper modelMapper; @Autowired private UserService userService; @Autowired private RequestComponent requestComponent; /** * 用户详情 */ @LoginRequired @RequestMapping(value = "info", method = RequestMethod.GET) public UserVo getUserInfo() { UserPo userPo = requestComponent.getLoginUser(); return modelMapper.map(userPo, UserVo.class); } /** * 用户登录 */ @RequestMapping(value = "login", method = RequestMethod.POST) public void login(Model mode, @RequestParam(value = "username") String username, @RequestParam(value = "password") String password, HttpServletResponse response) throws IOException { final String loginIp = requestComponent.getClientIp(); final String loginToken = userService.login(username, password, loginIp); if (StringUtils.isEmpty(loginToken)) { log.warn("user login failed! username: " + username);
throw new AppException(ErrorCode.USER_LOGIN_ERROR);
1
2023-10-16 12:45:57+00:00
8k
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[] nationName = {\"ALGERIA\", \"ARFENTINA\", \"BRAZIL\", \"CANADA\", \"EGYPT\", \"ETHIOPIA\",\n \"FRANCE\", \"GERMANY\", \"INDIA\", \"INDONESIA\", \"IRAN\", \"IRAQ\", \"JAPAN\", \"JODAN\", \"KENYA\", \"MORACCO\", \"MOZAMBIQUE\", \"PERU\",\n \"CHINA\", \"ROMANIA\", \"SAUDI ARABIA\", \"VIETNAM\", \"RUSSIA\", \"UNITED KINGDOM\", \"UNITED STATES\"};\n public static Integer[] n_regionKey = {0, 1, 1, 1, 4, 0, 3, 3, 2, 2, 4, 4, 2, 4, 0, 0, 0, 1, 2, 3, 4, 2, 3, 3, 1};\n\n public static void main(String[] args) {\n System.out.println(NationData.nationKey.length == NationData.n_regionKey.length && NationData.n_regionKey.length == NationData.nationName.length);\n }\n}" }, { "identifier": "RegionData", "path": "code/src/main/java/benchmark/olap/data/RegionData.java", "snippet": "public class RegionData {\n public static Integer[] regionKey = {0, 1, 2, 3, 4};\n public static String[] regionName = {\"AFRICA\", \"AMERICA\", \"ASIA\", \"EUROPE\", \"MIDDLE EAST\"};\n\n}" }, { "identifier": "BasicRandom", "path": "code/src/main/java/utils/math/random/BasicRandom.java", "snippet": "public class BasicRandom {\n private static final char[] aStringChars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n private static final String[] cLastTokens = {\"BAR\", \"OUGHT\", \"ABLE\", \"PRI\", \"PRES\", \"ESE\", \"ANTI\", \"CALLY\", \"ATION\", \"EING\"};\n private static final String[] pNameColor = {\"almond\", \"antique\", \"aquamarine\", \"azure\", \"beige\", \"bisque\", \"black\", \"blanched\", \"blue\", \"blush\", \"brown\", \"burlywood\", \"burnished\", \"chartreuse\", \"chiffon\", \"chocolate\", \"coral\", \"cornflower\", \"cornsilk\", \"cream\", \"cyan\", \"dark\", \"deep\", \"dim\", \"dodger\", \"drab\", \"firebrick\", \"floral\", \"forest\", \"frosted\", \"gainsboro\", \"ghost\", \"goldenrod\", \"green\", \"grey\", \"honeydew\", \"hot\", \"indian\", \"ivory\", \"khaki\", \"lace\", \"lavender\", \"lawn\", \"lemon\", \"light\", \"lime\", \"linen\", \"magenta\", \"maroon\", \"medium\", \"metallic\", \"midnight\", \"mint\", \"misty\", \"moccasin\", \"navajo\", \"navy\", \"olive\", \"orange\", \"orchid\", \"pale\", \"papaya\", \"peach\", \"peru\", \"pink\", \"plum\", \"powder\", \"puff\", \"purple\", \"red\", \"rose\", \"rosy\", \"royal\", \"saddle\", \"salmon\", \"sandy\", \"seashell\", \"sienna\", \"sky\", \"slate\", \"smoke\", \"snow\", \"spring\", \"steel\", \"tan\", \"thistle\", \"tomato\", \"turquoise\", \"violet\", \"wheat\", \"white\", \"yellow\"};\n private static final String[] containerSyllable1 = {\"SM\", \"LG\", \"MED\", \"JUMBO\", \"WRAP\"};\n private static final String[] containerSyllable2 = {\"CASE\", \"BOX\", \"BAG\", \"JAR\", \"PKG\", \"PACK\", \"CAN\", \"DRUM\"};\n\n private static final String[] typeSyllable1 = {\"STANDARD\", \"SMALL\", \"MEDIUM\", \"LARGE\", \"ECONOMY\", \"PROMO\"};\n private static final String[] typeSyllable2 = {\"ANODIZED\", \"BURNISHED\", \"PLATED\", \"POLISHED\", \"BRUSHED\"};\n private static final String[] typeSyllable3 = {\"TIN\", \"NICKEL\", \"BRASS\", \"STEEL\", \"COPPER\"};\n private static final String[] cktSegment = {\"AUTOMOBILE\", \"BUILDING\", \"FURNITURE\", \"HOUSEHOLD\", \"MACHINERY\"};\n private static final String[] sMode = {\"REG AIR\", \"AIR\", \"RAIL\", \"TRUCK\", \"MAIL\", \"FOB\", \"SHIP\"};\n private static final String[] rFlag = {\"R\", \"A\", \"N\"};\n private static final String[] sInstruct = {\"DELIVER IN PERSON\", \"COLLECT COD\", \"TAKE BACK RETURN\", \"NONE\"};\n\n private static long nURandCLast;\n private static long nURandCC_ID;\n private static long nURandCI_ID;\n private static boolean initialized = false;\n\n private Random random;\n\n private String[] string_A_6;\n private String[] string_A_8;\n private String[] string_A_10;\n private String[] string_A_12;\n private String[] string_A_14;\n private String[] string_A_24;\n private String[] string_A_26;\n private String[] string_A_300;\n\n private String[] string_B_4;\n private String[] string_B_8;\n private String[] string_B_10;\n private String[] string_B_12;\n private String[] string_B_24;\n private String[] string_B_200;\n\n /*\n * jTPCCRandom()\n *\n * Used to create the master jTPCCRandom() instance for loading\n * the database. See below.\n */\n public BasicRandom() {\n if (initialized)\n throw new IllegalStateException(\"Global instance exists\");\n\n this.random = new Random(System.nanoTime());\n BasicRandom.nURandCLast = nextLong(0, 255);\n BasicRandom.nURandCC_ID = nextLong(0, 1023);\n BasicRandom.nURandCI_ID = nextLong(0, 8191);\n\n initialized = true;\n System.out.println(\"utils.math.random initialized\");\n }\n\n /*\n * jTPCCRandom(CLoad)\n *\n * Used to create the master jTPCCRandom instance for running\n * a benchmark utils.load.\n *\n * TPC-C 2.1.6 defines the rules for picking the C values of\n * the non-uniform utils.math.random number generator. In particular\n * 2.1.6.1 defines what numbers for the C value for generating\n * C_LAST must be excluded from the possible range during run\n * time, based on the number used during the utils.load.\n */\n public BasicRandom(long CLoad) {\n long delta;\n\n if (initialized)\n throw new IllegalStateException(\"Global instance exists\");\n\n this.random = new Random(System.nanoTime());\n BasicRandom.nURandCC_ID = nextLong(0, 1023);\n BasicRandom.nURandCI_ID = nextLong(0, 8191);\n\n do {\n BasicRandom.nURandCLast = nextLong(0, 255);\n\n delta = Math.abs(BasicRandom.nURandCLast - CLoad);\n if (delta == 96 || delta == 112)\n continue;\n if (delta < 65 || delta > 119)\n continue;\n break;\n } while (true);\n\n initialized = true;\n }\n\n private BasicRandom(BasicRandom parent) {\n this.random = new Random(System.nanoTime());\n this.generateStrings();\n }\n\n /*\n * newRandom()\n *\n * Creates a derived utils.math.random data generator to be used in another\n * thread of the current benchmark utils.load or run process. As per\n * TPC-C 2.1.6 all terminals during a run must use the same C\n * values per field. The jTPCCRandom Class therefore cannot\n * generate them per instance, but each thread's instance must\n * inherit those numbers from a global instance.\n */\n public BasicRandom newRandom() {\n return new BasicRandom(this);\n }\n\n private void generateStrings() {\n string_A_6 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_6[i] = getAString(6, 6);\n string_A_8 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_8[i] = getAString(8, 8);\n string_A_10 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_10[i] = getAString(10, 10);\n string_A_12 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_12[i] = getAString(12, 12);\n string_A_14 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_14[i] = getAString(14, 14);\n string_A_24 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_24[i] = getAString(24, 24);\n string_A_26 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_26[i] = getAString(26, 26);\n string_A_300 = new String[100];\n for (int i = 0; i < 100; i++)\n string_A_300[i] = getAString(300, 300);\n\n string_B_4 = new String[50];\n for (int i = 0; i < 50; i++)\n string_B_4[i] = getAString(i / 10, i / 10);\n string_B_8 = new String[90];\n for (int i = 0; i < 90; i++)\n string_B_8[i] = getAString(i / 10, i / 10);\n string_B_10 = new String[110];\n for (int i = 0; i < 110; i++)\n string_B_10[i] = getAString(i / 10, i / 10);\n string_B_12 = new String[130];\n for (int i = 0; i < 130; i++)\n string_B_12[i] = getAString(i / 10, i / 10);\n string_B_24 = new String[250];\n for (int i = 0; i < 250; i++)\n string_B_24[i] = getAString(i / 10, i / 10);\n string_B_200 = new String[2010];\n for (int i = 0; i < 2010; i++)\n string_B_200[i] = getAString(i / 10, i / 10);\n }\n\n /*\n * nextDouble(x, y)\n *\n * Produce double utils.math.random number uniformly distributed in [x .. y]\n */\n public double nextDouble(double x, double y) {\n return random.nextDouble() * (y - x) + x;\n }\n\n /*\n * nextLong(x, y)\n *\n * Produce a utils.math.random number uniformly distributed in [x .. y]\n */\n public long nextLong(long x, long y) {\n return (long) (random.nextDouble() * (y - x + 1) + x);\n }\n\n /*\n * nextInt(x, y)\n *\n * Produce a utils.math.random number uniformly distributed in [x .. y]\n */\n public int nextInt(int x, int y) {\n return (int) (random.nextDouble() * (y - x + 1) + x);\n }\n\n /*\n * getAString(x, y)\n *\n * Procude a utils.math.random alphanumeric string of length [x .. y].\n *\n * Note: TPC-C 4.3.2.2 asks for an \"alhpanumeric\" string.\n * Comment 1 about the character set does NOT mean that this\n * function must eventually produce 128 different characters,\n * only that the \"character set\" used to store this data must\n * be able to represent 128 different characters. '#@!%%ÄÖß'\n * is not an alphanumeric string. We can save ourselves a lot\n * of UTF8 related trouble by producing alphanumeric only\n * instead of cartoon style curse-bubbles.\n */\n public String getAString(long x, long y) {\n StringBuilder result = new StringBuilder();\n long len = nextLong(x, y);\n long have = 1;\n\n if (y <= 0)\n return result.toString();\n\n result.append(aStringChars[(int) nextLong(0, 51)]);\n while (have < len) {\n result.append(aStringChars[(int) nextLong(0, 61)]);\n have++;\n }\n\n return result.toString();\n }\n\n public String getAString_6_10() {\n String result = \"\";\n\n result += string_A_6[nextInt(0, 99)];\n result += string_B_4[nextInt(0, 49)];\n\n return result;\n }\n\n public String getAString_8_16() {\n String result = \"\";\n\n result += string_A_8[nextInt(0, 99)];\n result += string_B_8[nextInt(0, 89)];\n\n return result;\n }\n\n public String getAString_10_20() {\n String result = \"\";\n\n result += string_A_10[nextInt(0, 99)];\n result += string_B_10[nextInt(0, 109)];\n\n return result;\n }\n\n public String getAString_12_24() {\n String result = \"\";\n\n result += string_A_12[nextInt(0, 99)];\n result += string_B_12[nextInt(0, 129)];\n\n return result;\n }\n\n public String getAString_14_24() {\n String result = \"\";\n\n result += string_A_14[nextInt(0, 99)];\n result += string_B_10[nextInt(0, 109)];\n\n return result;\n }\n\n public String getAString_24() {\n String result = \"\";\n\n result += string_A_24[nextInt(0, 99)];\n\n return result;\n }\n\n public String getAString_26_50() {\n String result = \"\";\n\n result += string_A_26[nextInt(0, 99)];\n result += string_B_24[nextInt(0, 249)];\n\n return result;\n }\n\n public String getAString_300_500() {\n String result = \"\";\n\n result += string_A_300[nextInt(0, 99)];\n result += string_B_200[nextInt(0, 2009)];\n\n return result;\n }\n\n /*\n * getNString(x, y)\n *\n * Produce a utils.math.random numeric string of length [x .. y].\n */\n public String getNString(long x, long y) {\n StringBuilder result = new StringBuilder();\n long len = nextLong(x, y);\n long have = 0;\n\n while (have < len) {\n result.append((char) (nextLong('0', '9')));\n have++;\n }\n\n return result.toString();\n }\n\n /*\n * getItemID()\n *\n * Produce a non uniform utils.math.random Item ID.\n */\n public int getItemID() {\n return (int) ((((nextLong(0, 8191) | nextLong(1, 100000)) + nURandCI_ID)\n % 100000) + 1);\n }\n\n /*\n * getCustomerID()\n *\n * Produce a non uniform utils.math.random Customer ID.\n */\n public int getCustomerID() {\n return (int) ((((nextLong(0, 1023) | nextLong(1, 3000)) + nURandCC_ID)\n % 3000) + 1);\n }\n\n /*\n * getCLast(num)\n *\n * Produce the syllable representation for C_LAST of [0 .. 999]\n */\n public String getCLast(int num) {\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < 3; i++) {\n result.insert(0, cLastTokens[num % 10]);\n num /= 10;\n }\n return result.toString();\n }\n\n /*\n * getCLast()\n *\n * Procude a non uniform utils.math.random Customer Last Name.\n */\n public String getCLast() {\n long num;\n num = (((nextLong(0, 255) | nextLong(0, 999)) + nURandCLast) % 1000);\n return getCLast((int) num);\n }\n\n public String getState() {\n String result = \"\";\n\n result += (char) nextInt('A', 'Z');\n result += (char) nextInt('A', 'Z');\n\n return result;\n }\n\n\n /*\n * Methods to retrieve the C values used.\n */\n public long getNURandCLast() {\n return nURandCLast;\n }\n\n public long getNURandCC_ID() {\n return nURandCC_ID;\n }\n\n public long getNURandCI_ID() {\n return nURandCI_ID;\n }\n\n public int differentDaysByMillisecond(Date date1, Date date2) {//计算两个日期相差天数\n return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));\n }\n\n public Date getDateAfter(Date d, int day) {\n Calendar now = Calendar.getInstance();\n now.setTime(d);\n now.add(Calendar.DATE, day);\n return now.getTime();\n }\n\n public String getPName(int low, int high) {\n String result;\n int num = nextInt(low, high);\n result = pNameColor[num];\n return result;\n }\n\n public String getContainer() {\n String result = \"\";\n result += containerSyllable1[nextInt(0, 4)];\n result += \" \";\n result += containerSyllable2[nextInt(0, 7)];\n return result;\n }\n\n public String getSmode(int low, int high) {\n return sMode[nextInt(low, high)];\n }\n\n public String getSinstruct(int low, int high) {\n return sInstruct[nextInt(low, high)];\n }\n\n public String getType() {\n String result = \"\";\n result += typeSyllable1[nextInt(0, 5)];\n result += \" \";\n result += typeSyllable2[nextInt(0, 4)];\n result += \" \";\n result += typeSyllable3[nextInt(0, 4)];\n return result;\n }\n\n public String getCktSegement(int low, int high) {\n String result = \"\";\n result += cktSegment[nextInt(low, high)];\n return result;\n }\n} // end jTPCCRandom" } ]
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;
5,209
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;
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;
2
2023-10-22 11:22:32+00:00
8k
Onuraktasj/stock-tracking-system
src/main/java/com/onuraktas/stocktrackingsystem/impl/ProductServiceImpl.java
[ { "identifier": "ProductProducer", "path": "src/main/java/com/onuraktas/stocktrackingsystem/amqp/producer/ProductProducer.java", "snippet": "@Component\npublic class ProductProducer {\n\n private final RabbitTemplate rabbitTemplate;\n\n public ProductProducer(RabbitTemplate rabbitTemplate) {\n this.rabbitTemplate = rabbitTemplate;\n }\n\n public <T> void sendToQueue(String queueName, T message) {\n rabbitTemplate.convertAndSend(queueName, message);\n }\n}" }, { "identifier": "QueueName", "path": "src/main/java/com/onuraktas/stocktrackingsystem/constant/QueueName.java", "snippet": "public class QueueName {\n\n public static final String DELETED_CATEGORY_QUEUE = \"deletedCategoryQueue\";\n public static final String DELETED_PRODUCT_QUEUE = \"deletedProductQueue\";\n}" }, { "identifier": "DeletedProductMessage", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/amqp/DeletedProductMessage.java", "snippet": "@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@Builder\npublic class DeletedProductMessage implements Serializable {\n\n private UUID productId;\n}" }, { "identifier": "ProductDto", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/entity/ProductDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class ProductDto {\n\n private UUID productId;\n private String productName;\n private String description;\n private Integer amount;\n private Boolean isActive;\n}" }, { "identifier": "SimpleCategory", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/general/SimpleCategory.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class SimpleCategory {\n\n private UUID categoryId;\n}" }, { "identifier": "CreateProductRequest", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/CreateProductRequest.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class CreateProductRequest {\n\n private String productName;\n private String description;\n private Integer amount;\n private List<SimpleCategory> categoryList;\n}" }, { "identifier": "UpdateProductAmountRequest", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/request/UpdateProductAmountRequest.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class UpdateProductAmountRequest {\n\n private Integer amount;\n}" }, { "identifier": "CreateProductResponse", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/CreateProductResponse.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@SuperBuilder\npublic class CreateProductResponse {\n\n private UUID productId;\n\n private String productName;\n\n private String status;\n}" }, { "identifier": "DeleteProductByIdResponse", "path": "src/main/java/com/onuraktas/stocktrackingsystem/dto/response/DeleteProductByIdResponse.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@ToString\n@EqualsAndHashCode\n@Builder\npublic class DeleteProductByIdResponse {\n\n private UUID productId;\n private Boolean isActive;\n}" }, { "identifier": "Category", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Category.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@Builder\n@Entity\npublic class Category {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID categoryId;\n private String categoryName;\n @Builder.Default\n private Boolean isActive = true;\n}" }, { "identifier": "CategoryProductRel", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/CategoryProductRel.java", "snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@Setter\n@EqualsAndHashCode\n@ToString\n@Builder\n@Entity\npublic class CategoryProductRel {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID id;\n private UUID categoryId;\n private UUID productId;\n @Builder.Default\n private Boolean isActive = true;\n}" }, { "identifier": "Product", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/Product.java", "snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@EqualsAndHashCode\n@Builder\n@ToString\n@Entity\npublic class Product {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private UUID productId;\n private String productName;\n private String description;\n private Integer amount;\n @Builder.Default\n private Boolean isActive = true;\n}" }, { "identifier": "Status", "path": "src/main/java/com/onuraktas/stocktrackingsystem/entity/enums/Status.java", "snippet": "public enum Status {\n\n OK(\"OK\"),\n NOK(\"NOK\");\n\n private final String status;\n\n Status(String status){\n this.status = status;\n }\n\n public String getStatus(){\n return status;\n }\n}" }, { "identifier": "ProductBadRequestException", "path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/ProductBadRequestException.java", "snippet": "public class ProductBadRequestException extends RuntimeException {\n private String message;\n\n public ProductBadRequestException(String message) {\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}" }, { "identifier": "ProductNotFoundException", "path": "src/main/java/com/onuraktas/stocktrackingsystem/exception/ProductNotFoundException.java", "snippet": "public class ProductNotFoundException extends RuntimeException{\n\n private final String message;\n\n public ProductNotFoundException(String message){\n this.message = message;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n}" }, { "identifier": "GeneralValues", "path": "src/main/java/com/onuraktas/stocktrackingsystem/helper/GeneralValues.java", "snippet": "public class GeneralValues {\n\n public static final Integer CATEGORY_MAX_SIZE = 3;\n}" }, { "identifier": "ProductMapper", "path": "src/main/java/com/onuraktas/stocktrackingsystem/mapper/ProductMapper.java", "snippet": "public class ProductMapper {\n\n public static ProductDto toDto(Product product){\n if (Objects.isNull(product))\n return null;\n return ProductDto.builder()\n .productId(product.getProductId())\n .productName(product.getProductName())\n .description(product.getDescription())\n .amount(product.getAmount())\n .isActive(product.getIsActive())\n .build();\n }\n\n public static Product toEntity(ProductDto productDto){\n if (Objects.isNull(productDto))\n return null;\n return Product.builder()\n .productId(productDto.getProductId())\n .productName(productDto.getProductName())\n .description(productDto.getDescription())\n .amount(productDto.getAmount())\n .build();\n }\n\n public static Product toEntity(CreateProductRequest createProductRequest){\n if (Objects.isNull(createProductRequest))\n return null;\n return Product.builder()\n .productName(createProductRequest.getProductName())\n .description(createProductRequest.getDescription())\n .amount(createProductRequest.getAmount())\n .build();\n }\n\n public static CreateProductResponse toCreateProductResponse(Product product){\n if (Objects.isNull(product))\n return null;\n\n return CreateProductResponse.builder()\n .productId(product.getProductId())\n .productName(product.getProductName())\n .build();\n }\n\n public static List<ProductDto> toDtoList(List<Product> products){\n return products.stream().parallel()\n .map(ProductMapper::toDto)\n .toList();\n }\n}" }, { "identifier": "ExceptionMessages", "path": "src/main/java/com/onuraktas/stocktrackingsystem/message/ExceptionMessages.java", "snippet": "public class ExceptionMessages {\n\n public static final String BAD_REQUEST = \"Bad request\";\n}" }, { "identifier": "ProductMessages", "path": "src/main/java/com/onuraktas/stocktrackingsystem/message/ProductMessages.java", "snippet": "public class ProductMessages {\n\n public static final String PRODUCT_NOT_FOUND = \"Product not found\";\n public static final String CATEGORY_LIST_EMPTY = \"Category list is empty\";\n public static final String CATEGORY_LIST_SIZE_EXCEEDED = \"Category list size exceeded\";\n public static final String CATEGORY_NOT_FOUND = \"Category not found\";\n}" }, { "identifier": "CategoryProductRelRepository", "path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/CategoryProductRelRepository.java", "snippet": "@Repository\npublic interface CategoryProductRelRepository extends JpaRepository<CategoryProductRel, UUID> {\n\n List<CategoryProductRel> findAllByCategoryIdAndIsActive(UUID categoryId, Boolean isActive);\n List<CategoryProductRel> findAllByProductIdAndIsActive(UUID productId, Boolean isActive);\n List<CategoryProductRel> findAllByProductIdInAndIsActive(List<UUID> productIdList, Boolean isActive);\n}" }, { "identifier": "CategoryRepository", "path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/CategoryRepository.java", "snippet": "public interface CategoryRepository extends JpaRepository<Category, UUID> {\n\n Optional<Category> findByCategoryIdAndIsActive(UUID categoryId, Boolean isActive);\n\n Category findByCategoryName(String categoryName);\n\n List<Category> findAllByCategoryIdInAndIsActive(List<UUID> categoryIds, Boolean isActive);\n}" }, { "identifier": "ProductRepository", "path": "src/main/java/com/onuraktas/stocktrackingsystem/repository/ProductRepository.java", "snippet": "public interface ProductRepository extends JpaRepository<Product, UUID> {\n\n List<Product> findAllByProductIdIn(List<UUID> productIdList);\n List<Product> findAllByProductIdInAndIsActive(List<UUID> productId, Boolean isActive);\n Optional<Product> findByProductIdAndIsActive(UUID productId, Boolean isActive);\n}" }, { "identifier": "ProductService", "path": "src/main/java/com/onuraktas/stocktrackingsystem/service/ProductService.java", "snippet": "public interface ProductService {\n\n CreateProductResponse createProduct(CreateProductRequest createProductRequest);\n List<ProductDto> getAllProduct();\n ProductDto getProduct(UUID productId);\n\n ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto);\n\n ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request);\n\n DeleteProductByIdResponse deleteProductById(UUID productId);\n\n List<ProductDto> getProductListByCategory(UUID categoryId);\n\n void deleteProductListByProductListIdList(List<UUID> productIdList);\n}" } ]
import com.onuraktas.stocktrackingsystem.amqp.producer.ProductProducer; import com.onuraktas.stocktrackingsystem.constant.QueueName; import com.onuraktas.stocktrackingsystem.dto.amqp.DeletedProductMessage; import com.onuraktas.stocktrackingsystem.dto.entity.ProductDto; import com.onuraktas.stocktrackingsystem.dto.general.SimpleCategory; import com.onuraktas.stocktrackingsystem.dto.request.CreateProductRequest; import com.onuraktas.stocktrackingsystem.dto.request.UpdateProductAmountRequest; import com.onuraktas.stocktrackingsystem.dto.response.CreateProductResponse; import com.onuraktas.stocktrackingsystem.dto.response.DeleteProductByIdResponse; import com.onuraktas.stocktrackingsystem.entity.Category; import com.onuraktas.stocktrackingsystem.entity.CategoryProductRel; import com.onuraktas.stocktrackingsystem.entity.Product; import com.onuraktas.stocktrackingsystem.entity.enums.Status; import com.onuraktas.stocktrackingsystem.exception.ProductBadRequestException; import com.onuraktas.stocktrackingsystem.exception.ProductNotFoundException; import com.onuraktas.stocktrackingsystem.helper.GeneralValues; import com.onuraktas.stocktrackingsystem.mapper.ProductMapper; import com.onuraktas.stocktrackingsystem.message.ExceptionMessages; import com.onuraktas.stocktrackingsystem.message.ProductMessages; import com.onuraktas.stocktrackingsystem.repository.CategoryProductRelRepository; import com.onuraktas.stocktrackingsystem.repository.CategoryRepository; import com.onuraktas.stocktrackingsystem.repository.ProductRepository; import com.onuraktas.stocktrackingsystem.service.ProductService; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.*;
3,824
package com.onuraktas.stocktrackingsystem.impl; @Service public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final CategoryProductRelRepository categoryProductRelRepository; private final CategoryRepository categoryRepository; private final ProductProducer productProducer; public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){ this.productRepository = productRepository; this.categoryProductRelRepository = categoryProductRelRepository; this.categoryRepository = categoryRepository; this.productProducer = productProducer; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public CreateProductResponse createProduct(CreateProductRequest createProductRequest) { this.validateCreateProductRequest(createProductRequest); List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE); if (categoryList.isEmpty()) throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND); List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList(); Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest)); CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product); createProductResponse.setStatus(Status.OK.getStatus()); List<CategoryProductRel> categoryProductRelList = new ArrayList<>(); for (UUID categoryId : categoryIdList) { categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build()); } this.categoryProductRelRepository.saveAll(categoryProductRelList); return createProductResponse; } @Override public List<ProductDto> getAllProduct() { return ProductMapper.toDtoList(productRepository.findAll()); } @Override public ProductDto getProduct(UUID productId) { return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND))); } @Override public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) { if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId())) return ResponseEntity.badRequest().build(); Optional<Product> existProduct = productRepository.findById(productId); if (existProduct.isEmpty()) return ResponseEntity.notFound().build(); final ProductDto updateProduct = this.save(productDto); if (Objects.nonNull(updateProduct)) return ResponseEntity.ok(updateProduct); return ResponseEntity.internalServerError().build(); } @Override public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) { Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)); product.setAmount(request.getAmount()); productRepository.save(product); return ProductMapper.toDto(productRepository.save(product)); } @Override public DeleteProductByIdResponse deleteProductById(UUID productId) { Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND)); deletedProduct.setIsActive(Boolean.FALSE); this.productRepository.save(deletedProduct); List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE); categoryProductRelList.forEach(categoryProductRel -> { categoryProductRel.setIsActive(Boolean.FALSE); }); this.categoryProductRelRepository.saveAll(categoryProductRelList); return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build(); } @Override public List<ProductDto> getProductListByCategory(UUID categoryId) { List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList(); if (productIdList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE)); if (productDtoList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); return productDtoList; } @Override public void deleteProductListByProductListIdList(List<UUID> productIdList) { List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE); productList.forEach(product -> product.setIsActive(Boolean.FALSE)); this.productRepository.saveAll(productList); List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>(); productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build())); this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList); } private ProductDto save (ProductDto productDto){ Product product = ProductMapper.toEntity(productDto); product = productRepository.save(product); return ProductMapper.toDto(product); } private void validateCreateProductRequest(CreateProductRequest createProductRequest) { if (Objects.isNull(createProductRequest))
package com.onuraktas.stocktrackingsystem.impl; @Service public class ProductServiceImpl implements ProductService { private final ProductRepository productRepository; private final CategoryProductRelRepository categoryProductRelRepository; private final CategoryRepository categoryRepository; private final ProductProducer productProducer; public ProductServiceImpl (ProductRepository productRepository, CategoryProductRelRepository categoryProductRelRepository, CategoryRepository categoryRepository, ProductProducer productProducer){ this.productRepository = productRepository; this.categoryProductRelRepository = categoryProductRelRepository; this.categoryRepository = categoryRepository; this.productProducer = productProducer; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public CreateProductResponse createProduct(CreateProductRequest createProductRequest) { this.validateCreateProductRequest(createProductRequest); List<Category> categoryList = this.categoryRepository.findAllByCategoryIdInAndIsActive(createProductRequest.getCategoryList().stream().map(SimpleCategory::getCategoryId).toList(), Boolean.TRUE); if (categoryList.isEmpty()) throw new ProductBadRequestException(ProductMessages.CATEGORY_NOT_FOUND); List<UUID> categoryIdList = categoryList.stream().map(Category::getCategoryId).toList(); Product product = this.productRepository.save(ProductMapper.toEntity(createProductRequest)); CreateProductResponse createProductResponse = ProductMapper.toCreateProductResponse(product); createProductResponse.setStatus(Status.OK.getStatus()); List<CategoryProductRel> categoryProductRelList = new ArrayList<>(); for (UUID categoryId : categoryIdList) { categoryProductRelList.add(CategoryProductRel.builder().categoryId(categoryId).productId(product.getProductId()).build()); } this.categoryProductRelRepository.saveAll(categoryProductRelList); return createProductResponse; } @Override public List<ProductDto> getAllProduct() { return ProductMapper.toDtoList(productRepository.findAll()); } @Override public ProductDto getProduct(UUID productId) { return ProductMapper.toDto(productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND))); } @Override public ResponseEntity<ProductDto> updateProduct(UUID productId, ProductDto productDto) { if (Objects.isNull(productId) || Objects.isNull(productDto.getProductId()) || !Objects.equals(productId,productDto.getProductId())) return ResponseEntity.badRequest().build(); Optional<Product> existProduct = productRepository.findById(productId); if (existProduct.isEmpty()) return ResponseEntity.notFound().build(); final ProductDto updateProduct = this.save(productDto); if (Objects.nonNull(updateProduct)) return ResponseEntity.ok(updateProduct); return ResponseEntity.internalServerError().build(); } @Override public ProductDto updateProductAmount(UUID productId, UpdateProductAmountRequest request) { Product product = productRepository.findById(productId).orElseThrow(()-> new NoSuchElementException(ProductMessages.PRODUCT_NOT_FOUND)); product.setAmount(request.getAmount()); productRepository.save(product); return ProductMapper.toDto(productRepository.save(product)); } @Override public DeleteProductByIdResponse deleteProductById(UUID productId) { Product deletedProduct = this.productRepository.findByProductIdAndIsActive(productId, Boolean.TRUE).orElseThrow(()-> new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND)); deletedProduct.setIsActive(Boolean.FALSE); this.productRepository.save(deletedProduct); List<CategoryProductRel> categoryProductRelList = this.categoryProductRelRepository.findAllByProductIdAndIsActive(productId, Boolean.TRUE); categoryProductRelList.forEach(categoryProductRel -> { categoryProductRel.setIsActive(Boolean.FALSE); }); this.categoryProductRelRepository.saveAll(categoryProductRelList); return DeleteProductByIdResponse.builder().productId(productId).isActive(Boolean.FALSE).build(); } @Override public List<ProductDto> getProductListByCategory(UUID categoryId) { List<UUID> productIdList = this.categoryProductRelRepository.findAllByCategoryIdAndIsActive(categoryId, Boolean.TRUE).stream().map(CategoryProductRel::getProductId).toList(); if (productIdList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); List<ProductDto> productDtoList = ProductMapper.toDtoList(this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE)); if (productDtoList.isEmpty()) throw new ProductNotFoundException(ProductMessages.PRODUCT_NOT_FOUND); return productDtoList; } @Override public void deleteProductListByProductListIdList(List<UUID> productIdList) { List<Product> productList = this.productRepository.findAllByProductIdInAndIsActive(productIdList, Boolean.TRUE); productList.forEach(product -> product.setIsActive(Boolean.FALSE)); this.productRepository.saveAll(productList); List<DeletedProductMessage> deletedProductMessageList = new ArrayList<>(); productList.stream().map(Product::getProductId).forEach(productId -> deletedProductMessageList.add(DeletedProductMessage.builder().productId(productId).build())); this.productProducer.sendToQueue(QueueName.DELETED_PRODUCT_QUEUE, deletedProductMessageList); } private ProductDto save (ProductDto productDto){ Product product = ProductMapper.toEntity(productDto); product = productRepository.save(product); return ProductMapper.toDto(product); } private void validateCreateProductRequest(CreateProductRequest createProductRequest) { if (Objects.isNull(createProductRequest))
throw new ProductBadRequestException(ExceptionMessages.BAD_REQUEST);
17
2023-10-23 19:00:09+00:00
8k
ushh789/FinancialCalculator
src/main/java/com/netrunners/financialcalculator/MenuControllers/ResultTableController.java
[ { "identifier": "Converter", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/CurrencyConverter/Converter.java", "snippet": "public class Converter {\n public static JsonArray getRates() throws IOException {\n URL url = new URL(\"https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json\");\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n\n connection.setRequestMethod(\"GET\");\n\n int responseCode = connection.getResponseCode();\n if (responseCode != 200) {\n LogHelper.log(Level.WARNING, \"Failed to get json from National Bank of Ukraine, response code: \" + responseCode, null);\n return null;\n }\n\n InputStream inputStream = connection.getInputStream();\n BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));\n StringBuilder json = new StringBuilder();\n String line;\n\n while ((line = reader.readLine()) != null) {\n json.append(line);\n }\n reader.close();\n inputStream.close();\n Gson gson = new Gson();\n\n return gson.fromJson(json.toString(), JsonArray.class).getAsJsonArray();\n }\n\n public static float getRateByCC(String cc) {\n try {\n JsonArray rates = getRates();\n if (rates == null) {\n LogHelper.log(Level.WARNING, \"Failed to retrieve exchange rates\", null);\n throw new RuntimeException(\"Failed to retrieve exchange rates\");\n }\n if (cc.equals(\"UAH\")){\n return 1;\n }\n for (JsonElement element : rates) {\n JsonObject obj = element.getAsJsonObject();\n if (obj.get(\"cc\").getAsString().equals(cc)) {\n return obj.get(\"rate\").getAsFloat();\n }\n }\n LogHelper.log(Level.WARNING, \"Currency code \" + cc + \" not found\", null);\n throw new IllegalArgumentException(\"Currency code \" + cc + \" not found\");\n } catch (IOException e) {\n LogHelper.log(Level.WARNING, \"IOException in Converter.getRateByCC, caused by input: \" + cc, null);\n throw new RuntimeException(e);\n }\n }\n\n public static String getCC(String userSelectedCurrency) {\n switch (userSelectedCurrency) {\n case \"$\" -> {\n return \"USD\";\n }\n case \"£\" -> {\n return \"GBP\";\n }\n case \"€\" -> {\n return \"EUR\";\n }\n case \"zł\" ->{\n return \"PLN\";\n }\n case \"₴\" ->{\n return \"UAH\";\n }\n default -> {\n return \"ERROR\";\n }\n }\n }\n}" }, { "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 static {\n try {\n // Налаштовуємо об'єкт логування для запису в файл \"log.txt\"\n FileHandler fileHandler = new FileHandler(\"logs/log\"+ LocalDateTime.now().format(DateTimeFormatter.ofPattern(\"dd-MM-yyyy_HH-mm-ss\"))+\".log\");\n SimpleFormatter formatter = new SimpleFormatter();\n fileHandler.setFormatter(formatter);\n logger.addHandler(fileHandler);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // Метод для логування повідомлень\n public static void log(Level level, String message, Throwable throwable) {\n logger.log(level, message, throwable);\n }\n}" }, { "identifier": "DateTimeFunctions", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TimeFunctions/DateTimeFunctions.java", "snippet": "public class DateTimeFunctions {\n\n public static int countDaysBetweenDates(LocalDate startDate, LocalDate endDate) {\n return (int) ChronoUnit.DAYS.between(startDate, endDate);\n }\n\n public static int countDaysToNextPeriod(Credit credit, LocalDate date) {\n switch (credit.getPaymentType()) {\n case 1 -> {\n if (date.plusMonths(1).withDayOfMonth(1).isAfter(credit.getEndDate())) {\n return countDaysBetweenDates(date, credit.getEndDate());\n } else {\n return countDaysBetweenDates(date, date.plusMonths(1).withDayOfMonth(1));\n }\n }\n case 2 -> {\n if (date.plusMonths(3).withDayOfMonth(1).isAfter(credit.getEndDate())) {\n return countDaysBetweenDates(date, credit.getEndDate());\n } else {\n return countDaysBetweenDates(date, date.plusMonths(3).withDayOfMonth(1));\n }\n }\n case 3 -> {\n if (date.plusYears(1).withMonth(1).withDayOfMonth(1).isAfter(credit.getEndDate())) {\n return countDaysBetweenDates(date, credit.getEndDate());\n } else {\n return countDaysBetweenDates(date, date.plusYears(1).withMonth(1).withDayOfMonth(1));\n }\n }\n case 4 -> {\n return countDaysBetweenDates(date, credit.getEndDate());\n }\n }\n return 0;\n }\n\n public static int countDaysToNextPeriod(Deposit deposit, LocalDate tempDate, LocalDate endDate) {\n switch (deposit.getWithdrawalOption()) {\n case 1 -> {\n if (tempDate.plusMonths(1).withDayOfMonth(1).isAfter(endDate)) {\n return countDaysBetweenDates(tempDate, endDate);\n } else {\n return countDaysBetweenDates(tempDate, tempDate.plusMonths(1).withDayOfMonth(1));\n }\n }\n case 2 -> {\n if (tempDate.plusMonths(3).withDayOfMonth(1).isAfter(endDate)) {\n return countDaysBetweenDates(tempDate, endDate);\n } else {\n return countDaysBetweenDates(tempDate, tempDate.plusMonths(3).withDayOfMonth(1));\n }\n }\n case 3 -> {\n if (tempDate.plusYears(1).withMonth(1).withDayOfMonth(1).isAfter(endDate)) {\n return countDaysBetweenDates(tempDate, endDate);\n } else {\n return countDaysBetweenDates(tempDate, tempDate.plusYears(1).withMonth(1).withDayOfMonth(1));\n }\n }\n case 4 -> {\n return countDaysBetweenDates(tempDate, endDate);\n }\n }\n return 0;\n }\n\n public static boolean isDateBetweenDates(LocalDate dateToCheck, LocalDate start, LocalDate end) {\n return !dateToCheck.isBefore(start) && !dateToCheck.isAfter(end);\n }\n\n}" }, { "identifier": "WindowsOpener", "path": "src/main/java/com/netrunners/financialcalculator/VisualInstruments/WindowsOpener.java", "snippet": "public class WindowsOpener{\n public static void depositOpener(){\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource(\"DepositMenu.fxml\"));\n Stage stage = new Stage();\n stage.titleProperty().bind(LanguageManager.getInstance().getStringBinding(\"DepositButton\"));\n Scene scene = new Scene(fxmlLoader.load());\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(820);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n\n } catch (IOException e) {\n LogHelper.log(Level.SEVERE, \"Error opening DepositMenu.fxml: \", e);\n }\n }\n public static void creditOpener(){\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource(\"CreditMenu.fxml\"));\n Stage stage = new Stage();\n stage.titleProperty().bind(LanguageManager.getInstance().getStringBinding(\"CreditButton\"));\n Scene scene = new Scene(fxmlLoader.load());\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(820);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error opening CreditMenu.fxml: \", e);\n }\n }\n}" } ]
import com.netrunners.financialcalculator.LogicalInstrumnts.CurrencyConverter.Converter; import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.LogHelper; import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DateTimeFunctions; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Deposit.*; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.*; import com.netrunners.financialcalculator.VisualInstruments.MenuActions.*; import com.netrunners.financialcalculator.VisualInstruments.WindowsOpener; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.stage.FileChooser; import javafx.stage.Stage; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.logging.Level;
5,450
} tempDate = tempDate.plusDays(daysToNextPeriod); numbersColumnFlag++; } return data; } private List<Object[]> countCreditWithHolidaysData(CreditWithHolidays credit) { DaystoNextPeriod.add(0); DaystoNextPeriodWithHolidays.add(0); LocalDate tempDate = credit.getStartDate(); List<Object[]> data = new ArrayList<>(); int numbersColumnFlag = 0; float dailyBodyPart = credit.countCreditBodyPerDay(); dailyPart = credit.countCreditBodyPerDay(); float tempLoan; loan = credit.getLoan(); while (!tempDate.equals(credit.getEndDate())) { tempLoan = credit.getLoan(); float totalLoan = tempLoan; float creditBody = 0; float periodPercents = 0; int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate); if (numbersColumnFlag == 0) { periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType())); investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput")); periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan")); } else { DaystoNextPeriod.add(daysToNextPeriod); DaystoNextPeriodWithHolidays.add(daysToNextPeriod); for (int i = 0; i < daysToNextPeriod; i++) { if (!DateTimeFunctions.isDateBetweenDates(tempDate, credit.getHolidaysStart(), credit.getHolidaysEnd())) { creditBody += dailyBodyPart; } else { DaystoNextPeriod.set(numbersColumnFlag, DaystoNextPeriod.get(numbersColumnFlag) - 1); } periodPercents += credit.countLoan(); tempDate = tempDate.plusDays(1); } if (tempDate.equals(credit.getEndDate())) { creditBody = tempLoan; } totalLoan -= creditBody; credit.setLoan(totalLoan); } data.add(new Object[]{numbersColumnFlag, String.format("%.2f", tempLoan) + credit.getCurrency(), String.format("%.2f", creditBody) + credit.getCurrency(), String.format("%.2f", totalLoan) + credit.getCurrency(), String.format("%.2f", periodPercents) + credit.getCurrency() }); numbersColumnFlag++; } return data; } private List<Object[]> countCreditWithoutHolidaysData(Credit credit) { DaystoNextPeriod.add(0); DaystoNextPeriodWithHolidays.add(0); LocalDate tempDate = credit.getStartDate(); List<Object[]> data = new ArrayList<>(); int numbersColumnFlag = 0; float dailyBodyPart = credit.countCreditBodyPerDay(); dailyPart = credit.countCreditBodyPerDay(); loan = credit.getLoan(); float tempLoan; while (tempDate.isBefore(credit.getEndDate())) { tempLoan = credit.getLoan(); float totalLoan = tempLoan; float creditBody = 0; float periodPercents = 0; int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate); if (numbersColumnFlag == 0) { periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType())); investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput")); periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan")); } else { DaystoNextPeriod.add(daysToNextPeriod); DaystoNextPeriodWithHolidays.add(daysToNextPeriod); for (int i = 0; i < daysToNextPeriod; i++) { periodPercents += credit.countLoan(); creditBody += dailyBodyPart; tempDate = tempDate.plusDays(1); } if (tempDate.equals(credit.getEndDate())) { creditBody = tempLoan; } totalLoan -= creditBody; credit.setLoan(totalLoan); } data.add(new Object[]{numbersColumnFlag, String.format("%.2f", tempLoan) + credit.getCurrency(), String.format("%.2f", creditBody) + credit.getCurrency(), String.format("%.2f", totalLoan) + credit.getCurrency(), String.format("%.2f", periodPercents) + credit.getCurrency() }); numbersColumnFlag++; } return data; } private void writeDataToCSV(List<Object[]> data, Deposit deposit, File file) { if(file!=null){ try (PrintWriter writer = new PrintWriter(new FileWriter(file))) { writer.println(deposit.getNameOfWithdrawalType() + ";" + investmentloanColumn.getText() + ";" + periodProfitLoanColumn.getText() + ";" + totalColumn.getText()); for (Object[] row : data) { writer.println(row[0] + ";" + row[1] + ";" + row[2] + ";" + row[3]); writer.flush(); } writer.println("Annual percent of deposit: " + deposit.getAnnualPercent()); writer.println("Currency: " + deposit.getCurrency()); writer.println("Start date: " + deposit.getStartDate()); writer.println("End date: " + deposit.getEndDate()); if (deposit.isEarlyWithdrawal()) { writer.println("Early withdrawal date: " + deposit.getEarlyWithdrawalDate()); } } catch (IOException e) {
package com.netrunners.financialcalculator.MenuControllers; public class ResultTableController { @FXML private MenuItem aboutUs; @FXML private MenuItem creditButtonMenu; @FXML private MenuItem currency; @FXML private MenuItem darkTheme; @FXML private Menu fileButton; @FXML private Menu aboutButton; @FXML private MenuItem depositButtonMenu; @FXML private MenuItem exitApp; @FXML private TableColumn<Object[], Integer> periodColumn; @FXML private MenuItem languageButton; @FXML private MenuItem lightTheme; @FXML private TableColumn<Object[], String> investmentloanColumn; @FXML private MenuItem openFileButton; @FXML private TableColumn<Object[], String> periodProfitLoanColumn; @FXML private TableView<Object[]> resultTable; @FXML private MenuItem saveAsButton; @FXML private MenuItem saveButton; @FXML private Menu viewButton; @FXML private Menu settingsButton; @FXML private Menu themeButton; @FXML private TableColumn<Object[], String> totalColumn; @FXML private TableColumn<Object[], String> periodPercentsColumn; @FXML private Button exportButton; @FXML private Menu newButton; @FXML private Label financialCalculatorLabel; @FXML private Button convertButton; float loan; float dailyPart; private LanguageManager languageManager = LanguageManager.getInstance(); List<Integer> DaystoNextPeriodWithHolidays = new ArrayList<>(); List<Integer> DaystoNextPeriod = new ArrayList<>(); private String userSelectedCurrency; float tempinvest; @FXML void initialize() { openFileButton.setDisable(true); currency.setDisable(true); darkTheme.setOnAction(event -> ThemeSelector.setDarkTheme()); lightTheme.setOnAction(event -> ThemeSelector.setLightTheme()); aboutUs.setOnAction(event -> AboutUsAlert.showAboutUs()); exitApp.setOnAction(event -> ExitApp.exitApp()); depositButtonMenu.setOnAction(event -> WindowsOpener.depositOpener()); creditButtonMenu.setOnAction(event -> WindowsOpener.creditOpener()); exportButton.setOnAction(event -> { }); convertButton.setOnAction(event -> { List<String> choices = new ArrayList<>(); choices.add("₴"); choices.add("$"); choices.add("£"); choices.add("€"); ChoiceDialog<String> dialog = new ChoiceDialog<>("-", choices); dialog.setTitle(LanguageManager.getInstance().getStringBinding("ConvertTitle").get()); Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png")); dialog.setHeaderText(null); dialog.setContentText(LanguageManager.getInstance().getStringBinding("ConvertTo").get()); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { String selectedConvertCurrency = result.get(); float rate = Converter.getRateByCC(Converter.getCC(userSelectedCurrency)) / Converter.getRateByCC(Converter.getCC(selectedConvertCurrency)); ObservableList<Object[]> investmentLoanColumnItems = investmentloanColumn.getTableView().getItems(); ObservableList<Object[]> periodProfitLoanColumnItems = periodProfitLoanColumn.getTableView().getItems(); ObservableList<Object[]> totalColumnItems = totalColumn.getTableView().getItems(); for (Object[] item : investmentLoanColumnItems) { item[1] = extractFloatValue((String) item[1]) * rate; String newValue = String.format("%.2f", item[1]) + selectedConvertCurrency; item[1] = newValue; if(!investmentLoanColumnItems.isEmpty()) { if(loan==0){tempinvest = extractFloatValue((String) investmentLoanColumnItems.get(0)[1]);} else{ loan = extractFloatValue((String) investmentLoanColumnItems.get(0)[1]);} } } for (Object[] item : periodProfitLoanColumnItems) { item[2] = extractFloatValue((String) item[2]) * rate; String newValue = String.format("%.2f", item[2]) + selectedConvertCurrency; item[2] = newValue; } for (Object[] item : totalColumnItems) { item[3] = extractFloatValue((String) item[3]) * rate; String newValue = String.format("%.2f", item[3]) + selectedConvertCurrency; item[3] = newValue; } if (periodPercentsColumn.isVisible()) { ObservableList<Object[]> periodPercentsColumnItems = periodPercentsColumn.getTableView().getItems(); for (Object[] item : periodPercentsColumnItems) { item[4] = extractFloatValue((String) item[4]) * rate; String newValue = String.format("%.2f", item[4]) + selectedConvertCurrency; item[4] = newValue; } } userSelectedCurrency = selectedConvertCurrency; resultTable.refresh(); } }); languageButton.setOnAction(event -> { List<String> choices = new ArrayList<>(); choices.add("English"); choices.add("Українська"); choices.add("Español"); choices.add("Français"); choices.add("Deutsch"); choices.add("Czech"); choices.add("Polski"); choices.add("Nederlands"); choices.add("日本語"); choices.add("中国人"); ChoiceDialog<String> dialog = new ChoiceDialog<>("English", choices); dialog.setTitle(LanguageManager.getInstance().getStringBinding("LanguageTitle").get()); Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow(); stage.getIcons().add(new Image("file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png")); dialog.setHeaderText(null); dialog.setContentText(LanguageManager.getInstance().getStringBinding("ChooseLanguage").get()); Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { String chosenLanguage = result.get(); Locale locale = switch (chosenLanguage) { case "Українська" -> new Locale("uk"); case "Español" -> new Locale("es"); case "Français" -> new Locale("fr"); case "Deutsch" -> new Locale("de"); case "Czech" -> new Locale("cs"); case "Polski" -> new Locale("pl"); case "Nederlands" -> new Locale("nl"); case "日本語" -> new Locale("ja"); case "中国人" -> new Locale("zh"); default -> new Locale("en"); }; languageManager.changeLanguage(locale); } }); financialCalculatorLabel.textProperty().bind(languageManager.getStringBinding("ResultTableLabel")); depositButtonMenu.textProperty().bind(languageManager.getStringBinding("DepositButton")); creditButtonMenu.textProperty().bind(languageManager.getStringBinding("CreditButton")); languageButton.textProperty().bind(languageManager.getStringBinding("languageButton")); darkTheme.textProperty().bind(languageManager.getStringBinding("darkTheme")); lightTheme.textProperty().bind(languageManager.getStringBinding("lightTheme")); aboutUs.textProperty().bind(languageManager.getStringBinding("aboutUs")); exitApp.textProperty().bind(languageManager.getStringBinding("exitApp")); currency.textProperty().bind(languageManager.getStringBinding("currency")); openFileButton.textProperty().bind(languageManager.getStringBinding("openFileButton")); saveAsButton.textProperty().bind(languageManager.getStringBinding("saveAsButton")); saveButton.textProperty().bind(languageManager.getStringBinding("saveButton")); totalColumn.textProperty().bind(languageManager.getStringBinding("totalColumn")); periodPercentsColumn.textProperty().bind(languageManager.getStringBinding("PeriodPercents")); exportButton.textProperty().bind(languageManager.getStringBinding("Export")); viewButton.textProperty().bind(languageManager.getStringBinding("viewButton")); settingsButton.textProperty().bind(languageManager.getStringBinding("settingsButton")); themeButton.textProperty().bind(languageManager.getStringBinding("themeButton")); fileButton.textProperty().bind(languageManager.getStringBinding("fileButton")); aboutButton.textProperty().bind(languageManager.getStringBinding("aboutButton")); newButton.textProperty().bind(languageManager.getStringBinding("newButton")); convertButton.textProperty().bind(languageManager.getStringBinding("ConvertTitle")); } public void updateTable(Deposit deposit) { fillColumns(deposit); } public void updateTable(Credit credit) { fillColumns(credit); } private void fillColumns(Credit credit) { userSelectedCurrency = credit.getCurrency(); resultTable.getColumns().clear(); periodPercentsColumn.setVisible(true); periodColumn.setCellValueFactory(cellData -> cellData.getValue()[0] == null ? null : new SimpleObjectProperty<>((Integer) cellData.getValue()[0])); investmentloanColumn.setCellValueFactory(cellData -> cellData.getValue()[1] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[1])); periodProfitLoanColumn.setCellValueFactory(cellData -> cellData.getValue()[2] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[2])); totalColumn.setCellValueFactory(cellData -> cellData.getValue()[3] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[3])); periodPercentsColumn.setCellValueFactory(cellData -> cellData.getValue()[4] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[4])); List<Object[]> data = new ArrayList<>(); resultTable.getColumns().addAll(periodColumn, investmentloanColumn, periodProfitLoanColumn, totalColumn, periodPercentsColumn); if (credit instanceof CreditWithoutHolidays) { data = countCreditWithoutHolidaysData(credit); } else if (credit instanceof CreditWithHolidays) { data = countCreditWithHolidaysData((CreditWithHolidays) credit); } ObservableList<Object[]> observableData = FXCollections.observableArrayList(data); resultTable.setItems(observableData); List<Object[]> finalData = data; exportButton.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("Export").get()); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv")); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx")); File file = fileChooser.showSaveDialog(null); if (file != null && file.getName().endsWith(".xlsx")) { writeDataToExcel(finalData, credit, file); } else { writeDataToCSV(finalData, credit, file); } }); saveButton.setOnAction(event -> { System.out.println(loan); System.out.println(tempinvest); LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"); String formattedNow = now.format(formatter); File file = new File("saves/Credit_result_" + formattedNow + ".csv"); writeDataToCSV(finalData, credit, file); SavingAlert.showSavingAlert(); }); saveAsButton.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveAsButton").get()); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv")); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx")); File file = fileChooser.showSaveDialog(null); if (file != null && file.getName().endsWith(".xlsx")) { writeDataToExcel(finalData, credit, file); } else { writeDataToCSV(finalData, credit, file); } }); } private void fillColumns(Deposit deposit) { userSelectedCurrency = deposit.getCurrency(); resultTable.getColumns().clear(); periodPercentsColumn.setVisible(false); periodColumn.setCellValueFactory(cellData -> cellData.getValue()[0] == null ? null : new SimpleObjectProperty<>((Integer) cellData.getValue()[0])); investmentloanColumn.setCellValueFactory(cellData -> cellData.getValue()[1] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[1])); periodProfitLoanColumn.setCellValueFactory(cellData -> cellData.getValue()[2] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[2])); totalColumn.setCellValueFactory(cellData -> cellData.getValue()[3] == null ? null : new SimpleObjectProperty<>((String) cellData.getValue()[3])); List<Object[]> data = countDepositData(deposit); resultTable.getColumns().addAll(periodColumn, investmentloanColumn, periodProfitLoanColumn, totalColumn); ObservableList<Object[]> observableData = FXCollections.observableArrayList(data); resultTable.setItems(observableData); exportButton.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("Export").get()); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv")); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx")); File file = fileChooser.showSaveDialog(null); if (file != null && file.getName().endsWith(".xlsx")) { writeDataToExcel(data, deposit, file); } else { writeDataToCSV(data, deposit, file); } }); saveButton.setOnAction(event -> { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss"); String formattedNow = now.format(formatter); File file = new File("saves/Deposit_result_" + formattedNow + ".csv"); writeDataToCSV(data, deposit, file); SavingAlert.showSavingAlert(); }); saveAsButton.setOnAction(event -> { FileChooser fileChooser = new FileChooser(); File initialDirectory = new File("saves/"); fileChooser.setInitialDirectory(initialDirectory); fileChooser.setTitle(LanguageManager.getInstance().getStringBinding("saveAsButton").get()); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("CSV Files", "*.csv")); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Excel Files", "*.xlsx")); File file = fileChooser.showSaveDialog(null); if (file != null && file.getName().endsWith(".xlsx")) { writeDataToExcel(data, deposit, file); } else { writeDataToCSV(data, deposit, file); } }); } private List<Object[]> countDepositData(Deposit deposit) { DaystoNextPeriod.add(0); List<Object[]> data = new ArrayList<>(); LocalDate tempDate = deposit.getStartDate(); float tempInvestment = deposit.getInvestment(); tempinvest = tempInvestment; float totalInvestment = tempInvestment; int numbersColumnFlag = 0; LocalDate endOfContract; if (deposit.isEarlyWithdrawal()) { endOfContract = deposit.getEarlyWithdrawalDate(); } else { endOfContract = deposit.getEndDate(); } boolean capitalize = deposit instanceof CapitalisedDeposit; while (!tempDate.equals(endOfContract)) { float periodProfit = 0; int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(deposit, tempDate, endOfContract); if (numbersColumnFlag == 0) { periodColumn.textProperty().bind(languageManager.getStringBinding(deposit.getNameOfWithdrawalType())); investmentloanColumn.textProperty().bind(languageManager.getStringBinding("InvestInput")); periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("ProfitColumn")); daysToNextPeriod = 0; } else { DaystoNextPeriod.add(daysToNextPeriod); if (capitalize) { for (int i = 0; i < daysToNextPeriod; i++) { periodProfit += deposit.countProfit(); } } else { for (int i = 0; i < daysToNextPeriod; i++) { periodProfit += deposit.countProfit(); } } } totalInvestment += periodProfit; data.add(new Object[]{numbersColumnFlag, String.format("%.2f", tempInvestment) + deposit.getCurrency(), String.format("%.2f", periodProfit) + deposit.getCurrency(), String.format("%.2f", totalInvestment) + deposit.getCurrency() }); if (capitalize) { tempInvestment = totalInvestment; deposit.setInvestment(tempInvestment); } tempDate = tempDate.plusDays(daysToNextPeriod); numbersColumnFlag++; } return data; } private List<Object[]> countCreditWithHolidaysData(CreditWithHolidays credit) { DaystoNextPeriod.add(0); DaystoNextPeriodWithHolidays.add(0); LocalDate tempDate = credit.getStartDate(); List<Object[]> data = new ArrayList<>(); int numbersColumnFlag = 0; float dailyBodyPart = credit.countCreditBodyPerDay(); dailyPart = credit.countCreditBodyPerDay(); float tempLoan; loan = credit.getLoan(); while (!tempDate.equals(credit.getEndDate())) { tempLoan = credit.getLoan(); float totalLoan = tempLoan; float creditBody = 0; float periodPercents = 0; int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate); if (numbersColumnFlag == 0) { periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType())); investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput")); periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan")); } else { DaystoNextPeriod.add(daysToNextPeriod); DaystoNextPeriodWithHolidays.add(daysToNextPeriod); for (int i = 0; i < daysToNextPeriod; i++) { if (!DateTimeFunctions.isDateBetweenDates(tempDate, credit.getHolidaysStart(), credit.getHolidaysEnd())) { creditBody += dailyBodyPart; } else { DaystoNextPeriod.set(numbersColumnFlag, DaystoNextPeriod.get(numbersColumnFlag) - 1); } periodPercents += credit.countLoan(); tempDate = tempDate.plusDays(1); } if (tempDate.equals(credit.getEndDate())) { creditBody = tempLoan; } totalLoan -= creditBody; credit.setLoan(totalLoan); } data.add(new Object[]{numbersColumnFlag, String.format("%.2f", tempLoan) + credit.getCurrency(), String.format("%.2f", creditBody) + credit.getCurrency(), String.format("%.2f", totalLoan) + credit.getCurrency(), String.format("%.2f", periodPercents) + credit.getCurrency() }); numbersColumnFlag++; } return data; } private List<Object[]> countCreditWithoutHolidaysData(Credit credit) { DaystoNextPeriod.add(0); DaystoNextPeriodWithHolidays.add(0); LocalDate tempDate = credit.getStartDate(); List<Object[]> data = new ArrayList<>(); int numbersColumnFlag = 0; float dailyBodyPart = credit.countCreditBodyPerDay(); dailyPart = credit.countCreditBodyPerDay(); loan = credit.getLoan(); float tempLoan; while (tempDate.isBefore(credit.getEndDate())) { tempLoan = credit.getLoan(); float totalLoan = tempLoan; float creditBody = 0; float periodPercents = 0; int daysToNextPeriod = DateTimeFunctions.countDaysToNextPeriod(credit, tempDate); if (numbersColumnFlag == 0) { periodColumn.textProperty().bind(languageManager.getStringBinding(credit.getNameOfPaymentType())); investmentloanColumn.textProperty().bind(languageManager.getStringBinding("LoanInput")); periodProfitLoanColumn.textProperty().bind(languageManager.getStringBinding("PaymentLoan")); } else { DaystoNextPeriod.add(daysToNextPeriod); DaystoNextPeriodWithHolidays.add(daysToNextPeriod); for (int i = 0; i < daysToNextPeriod; i++) { periodPercents += credit.countLoan(); creditBody += dailyBodyPart; tempDate = tempDate.plusDays(1); } if (tempDate.equals(credit.getEndDate())) { creditBody = tempLoan; } totalLoan -= creditBody; credit.setLoan(totalLoan); } data.add(new Object[]{numbersColumnFlag, String.format("%.2f", tempLoan) + credit.getCurrency(), String.format("%.2f", creditBody) + credit.getCurrency(), String.format("%.2f", totalLoan) + credit.getCurrency(), String.format("%.2f", periodPercents) + credit.getCurrency() }); numbersColumnFlag++; } return data; } private void writeDataToCSV(List<Object[]> data, Deposit deposit, File file) { if(file!=null){ try (PrintWriter writer = new PrintWriter(new FileWriter(file))) { writer.println(deposit.getNameOfWithdrawalType() + ";" + investmentloanColumn.getText() + ";" + periodProfitLoanColumn.getText() + ";" + totalColumn.getText()); for (Object[] row : data) { writer.println(row[0] + ";" + row[1] + ";" + row[2] + ";" + row[3]); writer.flush(); } writer.println("Annual percent of deposit: " + deposit.getAnnualPercent()); writer.println("Currency: " + deposit.getCurrency()); writer.println("Start date: " + deposit.getStartDate()); writer.println("End date: " + deposit.getEndDate()); if (deposit.isEarlyWithdrawal()) { writer.println("Early withdrawal date: " + deposit.getEarlyWithdrawalDate()); } } catch (IOException e) {
LogHelper.log(Level.SEVERE, "Error while writing Deposit to CSV", e);
1
2023-10-18 16:03:09+00:00
8k
bowbahdoe/java-audio-stack
tritonus-share/src/main/java/dev/mccue/tritonus/share/sampled/convert/TAsynchronousFilteredAudioInputStream.java
[ { "identifier": "TCircularBuffer", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/TCircularBuffer.java", "snippet": "public class TCircularBuffer\r\n{\r\n\tprivate boolean\t\tm_bBlockingRead;\r\n\tprivate boolean\t\tm_bBlockingWrite;\r\n\tprivate byte[]\t\tm_abData;\r\n\tprivate int\t\t\tm_nSize;\r\n\tprivate long\t\tm_lReadPos;\r\n\tprivate long\t\tm_lWritePos;\r\n\tprivate Trigger\t\tm_trigger;\r\n\tprivate boolean\t\tm_bOpen;\r\n\r\n\r\n\r\n\tpublic TCircularBuffer(int nSize, boolean bBlockingRead, boolean bBlockingWrite, Trigger trigger)\r\n\t{\r\n\t\tm_bBlockingRead = bBlockingRead;\r\n\t\tm_bBlockingWrite = bBlockingWrite;\r\n\t\tm_nSize = nSize;\r\n\t\tm_abData = new byte[m_nSize];\r\n\t\tm_lReadPos = 0;\r\n\t\tm_lWritePos = 0;\r\n\t\tm_trigger = trigger;\r\n\t\tm_bOpen = true;\r\n\t}\r\n\r\n\r\n\r\n\tpublic void close()\r\n\t{\r\n\t\tm_bOpen = false;\r\n\t\t// TODO: call notify() ?\r\n\t}\r\n\r\n\r\n\r\n\tprivate boolean isOpen()\r\n\t{\r\n\t\treturn m_bOpen;\r\n\t}\r\n\r\n\r\n\tpublic int availableRead()\r\n\t{\r\n\t\treturn (int) (m_lWritePos - m_lReadPos);\r\n\t}\r\n\r\n\r\n\r\n\tpublic int availableWrite()\r\n\t{\r\n\t\treturn m_nSize - availableRead();\r\n\t}\r\n\r\n\r\n\r\n\tprivate int getReadPos()\r\n\t{\r\n\t\treturn (int) (m_lReadPos % m_nSize);\r\n\t}\r\n\r\n\r\n\r\n\tprivate int getWritePos()\r\n\t{\r\n\t\treturn (int) (m_lWritePos % m_nSize);\r\n\t}\r\n\r\n\r\n\r\n\tpublic int read(byte[] abData)\r\n\t{\r\n\t\treturn read(abData, 0, abData.length);\r\n\t}\r\n\r\n\r\n\r\n\tpublic int read(byte[] abData, int nOffset, int nLength)\r\n\t{\r\n\t\tif (TDebug.TraceCircularBuffer)\r\n\t\t{\r\n\t\t\tTDebug.out(\">TCircularBuffer.read(): called.\");\r\n\t\t\tdumpInternalState();\r\n\t\t}\r\n\t\tif (! isOpen())\r\n\t\t{\r\n\t\t\tif (availableRead() > 0)\r\n\t\t\t{\r\n\t\t\t\tnLength = Math.min(nLength, availableRead());\r\n\t\t\t\tif (TDebug.TraceCircularBuffer) { TDebug.out(\"reading rest in closed buffer, length: \" + nLength); }\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (TDebug.TraceCircularBuffer) { TDebug.out(\"< not open. returning -1.\"); }\r\n\t\t\t\treturn -1;\r\n\t\t\t}\r\n\t\t}\r\n\t\tsynchronized (this)\r\n\t\t{\r\n\t\t\tif (m_trigger != null && availableRead() < nLength)\r\n\t\t\t{\r\n\t\t\t\tif (TDebug.TraceCircularBuffer) { TDebug.out(\"executing trigger.\"); }\r\n\t\t\t\tm_trigger.execute();\r\n\t\t\t}\r\n\t\t\tif (!m_bBlockingRead)\r\n\t\t\t{\r\n\t\t\t\tnLength = Math.min(availableRead(), nLength);\r\n\t\t\t}\r\n\t\t\tint nRemainingBytes = nLength;\r\n\t\t\twhile (nRemainingBytes > 0)\r\n\t\t\t{\r\n\t\t\t\twhile (availableRead() == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twait();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (InterruptedException e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (TDebug.TraceAllExceptions)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tTDebug.out(e);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tint\tnAvailable = Math.min(availableRead(), nRemainingBytes);\r\n\t\t\t\twhile (nAvailable > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tint\tnToRead = Math.min(nAvailable, m_nSize - getReadPos());\r\n\t\t\t\t\tSystem.arraycopy(m_abData, getReadPos(), abData, nOffset, nToRead);\r\n\t\t\t\t\tm_lReadPos += nToRead;\r\n\t\t\t\t\tnOffset += nToRead;\r\n\t\t\t\t\tnAvailable -= nToRead;\r\n\t\t\t\t\tnRemainingBytes -= nToRead;\r\n\t\t\t\t}\r\n\t\t\t\tnotifyAll();\r\n\t\t\t}\r\n\t\t\tif (TDebug.TraceCircularBuffer)\r\n\t\t\t{\r\n\t\t\t\tTDebug.out(\"After read:\");\r\n\t\t\t\tdumpInternalState();\r\n\t\t\t\tTDebug.out(\"< completed. Read \" + nLength + \" bytes\");\r\n\t\t\t}\r\n\t\t\treturn nLength;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tpublic int write(byte[] abData)\r\n\t{\r\n\t\treturn write(abData, 0, abData.length);\r\n\t}\r\n\r\n\r\n\r\n\tpublic int write(byte[] abData, int nOffset, int nLength)\r\n\t{\r\n\t\tif (TDebug.TraceCircularBuffer)\r\n\t\t{\r\n\t\t\tTDebug.out(\">TCircularBuffer.write(): called; nLength: \" + nLength);\r\n\t\t\tdumpInternalState();\r\n\t\t}\r\n\t\tsynchronized (this)\r\n\t\t{\r\n\t\t\tif (TDebug.TraceCircularBuffer) { TDebug.out(\"entered synchronized block.\"); }\r\n\t\t\tif (!m_bBlockingWrite)\r\n\t\t\t{\r\n\t\t\t\tnLength = Math.min(availableWrite(), nLength);\r\n\t\t\t}\r\n\t\t\tint nRemainingBytes = nLength;\r\n\t\t\twhile (nRemainingBytes > 0)\r\n\t\t\t{\r\n\t\t\t\twhile (availableWrite() == 0)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twait();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcatch (InterruptedException e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (TDebug.TraceAllExceptions)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tTDebug.out(e);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tint\tnAvailable = Math.min(availableWrite(), nRemainingBytes);\r\n\t\t\t\twhile (nAvailable > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tint\tnToWrite = Math.min(nAvailable, m_nSize - getWritePos());\r\n\t\t\t\t\t//TDebug.out(\"src buf size= \" + abData.length + \", offset = \" + nOffset + \", dst buf size=\" + m_abData.length + \" write pos=\" + getWritePos() + \" len=\" + nToWrite);\r\n\t\t\t\t\tSystem.arraycopy(abData, nOffset, m_abData, getWritePos(), nToWrite);\r\n\t\t\t\t\tm_lWritePos += nToWrite;\r\n\t\t\t\t\tnOffset += nToWrite;\r\n\t\t\t\t\tnAvailable -= nToWrite;\r\n\t\t\t\t\tnRemainingBytes -= nToWrite;\r\n\t\t\t\t}\r\n\t\t\t\tnotifyAll();\r\n\t\t\t}\r\n\t\t\tif (TDebug.TraceCircularBuffer)\r\n\t\t\t{\r\n\t\t\t\tTDebug.out(\"After write:\");\r\n\t\t\t\tdumpInternalState();\r\n\t\t\t\tTDebug.out(\"< completed. Wrote \"+nLength+\" bytes\");\r\n\t\t\t}\r\n\t\t\treturn nLength;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate void dumpInternalState()\r\n\t{\r\n\t\tTDebug.out(\"m_lReadPos = \" + m_lReadPos + \" ^= \"+getReadPos());\r\n\t\tTDebug.out(\"m_lWritePos = \" + m_lWritePos + \" ^= \"+getWritePos());\r\n\t\tTDebug.out(\"availableRead() = \" + availableRead());\r\n\t\tTDebug.out(\"availableWrite() = \" + availableWrite());\r\n\t}\r\n\r\n\r\n\r\n\tpublic static interface Trigger\r\n\t{\r\n\t\tpublic void execute();\r\n\t}\r\n\r\n\r\n}\r" }, { "identifier": "TDebug", "path": "tritonus-share/src/main/java/dev/mccue/tritonus/share/TDebug.java", "snippet": "public class TDebug\r\n{\r\n\tpublic static boolean\t\tSHOW_ACCESS_CONTROL_EXCEPTIONS = false;\r\n\tprivate static final String\tPROPERTY_PREFIX = \"tritonus.\";\r\n\t// The stream we output to\r\n\tpublic static PrintStream\tm_printStream = System.out;\r\n\r\n\tprivate static String indent=\"\";\r\n\r\n\t// meta-general\r\n\tpublic static boolean\tTraceAllExceptions = getBooleanProperty(\"TraceAllExceptions\");\r\n\tpublic static boolean\tTraceAllWarnings = getBooleanProperty(\"TraceAllWarnings\");\r\n\r\n\t// general\r\n\tpublic static boolean\tTraceInit = getBooleanProperty(\"TraceInit\");\r\n\tpublic static boolean\tTraceCircularBuffer = getBooleanProperty(\"TraceCircularBuffer\");\r\n\tpublic static boolean\tTraceService = getBooleanProperty(\"TraceService\");\r\n\r\n\t// sampled common implementation\r\n\tpublic static boolean\tTraceAudioSystem = getBooleanProperty(\"TraceAudioSystem\");\r\n\tpublic static boolean\tTraceAudioConfig = getBooleanProperty(\"TraceAudioConfig\");\r\n\tpublic static boolean\tTraceAudioInputStream = getBooleanProperty(\"TraceAudioInputStream\");\r\n\tpublic static boolean\tTraceMixerProvider = getBooleanProperty(\"TraceMixerProvider\");\r\n\tpublic static boolean\tTraceControl = getBooleanProperty(\"TraceControl\");\r\n\tpublic static boolean\tTraceLine = getBooleanProperty(\"TraceLine\");\r\n\tpublic static boolean\tTraceDataLine = getBooleanProperty(\"TraceDataLine\");\r\n\tpublic static boolean\tTraceMixer = getBooleanProperty(\"TraceMixer\");\r\n\tpublic static boolean\tTraceSourceDataLine = getBooleanProperty(\"TraceSourceDataLine\");\r\n\tpublic static boolean\tTraceTargetDataLine = getBooleanProperty(\"TraceTargetDataLine\");\r\n\tpublic static boolean\tTraceClip = getBooleanProperty(\"TraceClip\");\r\n\tpublic static boolean\tTraceAudioFileReader = getBooleanProperty(\"TraceAudioFileReader\");\r\n\tpublic static boolean\tTraceAudioFileWriter = getBooleanProperty(\"TraceAudioFileWriter\");\r\n\tpublic static boolean\tTraceAudioConverter = getBooleanProperty(\"TraceAudioConverter\");\r\n\tpublic static boolean\tTraceAudioOutputStream = getBooleanProperty(\"TraceAudioOutputStream\");\r\n\r\n\t// sampled specific implementation\r\n\tpublic static boolean\tTraceEsdNative = getBooleanProperty(\"TraceEsdNative\");\r\n\tpublic static boolean\tTraceEsdStreamNative = getBooleanProperty(\"TraceEsdStreamNative\");\r\n\tpublic static boolean\tTraceEsdRecordingStreamNative = getBooleanProperty(\"TraceEsdRecordingStreamNative\");\r\n\tpublic static boolean\tTraceAlsaNative = getBooleanProperty(\"TraceAlsaNative\");\r\n\tpublic static boolean\tTraceAlsaMixerNative = getBooleanProperty(\"TraceAlsaMixerNative\");\r\n\tpublic static boolean\tTraceAlsaPcmNative = getBooleanProperty(\"TraceAlsaPcmNative\");\r\n\tpublic static boolean\tTraceMixingAudioInputStream = getBooleanProperty(\"TraceMixingAudioInputStream\");\r\n\tpublic static boolean\tTraceOggNative = getBooleanProperty(\"TraceOggNative\");\r\n\tpublic static boolean\tTraceVorbisNative = getBooleanProperty(\"TraceVorbisNative\");\r\n\r\n\t// midi common implementation\r\n\tpublic static boolean\tTraceMidiSystem = getBooleanProperty(\"TraceMidiSystem\");\r\n\tpublic static boolean\tTraceMidiConfig = getBooleanProperty(\"TraceMidiConfig\");\r\n\tpublic static boolean\tTraceMidiDeviceProvider = getBooleanProperty(\"TraceMidiDeviceProvider\");\r\n\tpublic static boolean\tTraceSequencer = getBooleanProperty(\"TraceSequencer\");\r\n\tpublic static boolean\tTraceSynthesizer = getBooleanProperty(\"TraceSynthesizer\");\r\n\tpublic static boolean\tTraceMidiDevice = getBooleanProperty(\"TraceMidiDevice\");\r\n\r\n\t// midi specific implementation\r\n\tpublic static boolean\tTraceAlsaSeq = getBooleanProperty(\"TraceAlsaSeq\");\r\n\tpublic static boolean\tTraceAlsaSeqDetails = getBooleanProperty(\"TraceAlsaSeqDetails\");\r\n\tpublic static boolean\tTraceAlsaSeqNative = getBooleanProperty(\"TraceAlsaSeqNative\");\r\n\tpublic static boolean\tTracePortScan = getBooleanProperty(\"TracePortScan\");\r\n\tpublic static boolean\tTraceAlsaMidiIn = getBooleanProperty(\"TraceAlsaMidiIn\");\r\n\tpublic static boolean\tTraceAlsaMidiOut = getBooleanProperty(\"TraceAlsaMidiOut\");\r\n\tpublic static boolean\tTraceAlsaMidiChannel = getBooleanProperty(\"TraceAlsaMidiChannel\");\r\n\r\n\tpublic static boolean\tTraceFluidNative = getBooleanProperty(\"TraceFluidNative\");\r\n\r\n\t// misc\r\n\tpublic static boolean\tTraceAlsaCtlNative = getBooleanProperty(\"TraceAlsaCtlNative\");\r\n\tpublic static boolean\tTraceCdda = getBooleanProperty(\"TraceCdda\");\r\n\tpublic static boolean\tTraceCddaNative = getBooleanProperty(\"TraceCddaNative\");\r\n\r\n\r\n\r\n\t// make this method configurable to write to file, write to stderr,...\r\n\tpublic static void out(String strMessage)\r\n\t{\r\n\t\tif (strMessage.length()>0 && strMessage.charAt(0)=='<') {\r\n\t\t\tif (indent.length()>2) {\t\r\n\t\t\t\tindent=indent.substring(2);\r\n\t\t\t} else {\r\n\t\t\t\tindent=\"\";\r\n\t\t\t}\r\n\t\t}\r\n\t\tString newMsg=null;\r\n\t\tif (indent!=\"\" && strMessage.indexOf(\"\\n\")>=0) {\r\n\t\t\tnewMsg=\"\";\r\n\t\t\tStringTokenizer tokenizer=new StringTokenizer(strMessage, \"\\n\");\r\n\t\t\twhile (tokenizer.hasMoreTokens()) {\r\n\t\t\t\tnewMsg+=indent+tokenizer.nextToken()+\"\\n\";\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tnewMsg=indent+strMessage;\r\n\t\t}\r\n\t\tm_printStream.println(newMsg);\r\n\t\tif (strMessage.length()>0 && strMessage.charAt(0)=='>') {\r\n\t\t\t\tindent+=\" \";\r\n\t\t} \r\n\t}\r\n\r\n\r\n\r\n\tpublic static void out(Throwable throwable)\r\n\t{\r\n\t\tthrowable.printStackTrace(m_printStream);\r\n\t}\r\n\r\n\r\n\r\n\tpublic static void assertion(boolean bAssertion)\r\n\t{\r\n\t\tif (!bAssertion)\r\n\t\t{\r\n\t\t\tthrow new AssertException();\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tpublic static class AssertException\r\n\textends RuntimeException\r\n\t{\r\n\t\tprivate static final long serialVersionUID = 1;\r\n\r\n\t\tpublic AssertException()\r\n\t\t{\r\n\t\t}\r\n\r\n\r\n\r\n\t\tpublic AssertException(String sMessage)\r\n\t\t{\r\n\t\t\tsuper(sMessage);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate static boolean getBooleanProperty(String strName)\r\n\t{\r\n\t\tString\tstrPropertyName = PROPERTY_PREFIX + strName;\r\n\t\tString\tstrValue = \"false\";\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstrValue = System.getProperty(strPropertyName, \"false\");\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tif (SHOW_ACCESS_CONTROL_EXCEPTIONS)\r\n\t\t\t{\r\n\t\t\t\tout(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\t// TDebug.out(\"property: \" + strPropertyName + \"=\" + strValue);\r\n\t\tboolean\tbValue = strValue.toLowerCase().equals(\"true\");\r\n\t\t// TDebug.out(\"bValue: \" + bValue);\r\n\t\treturn bValue;\r\n\t}\r\n}\r" } ]
import java.io.ByteArrayInputStream; import java.io.IOException; import javax.sound.sampled.AudioFormat; import dev.mccue.tritonus.share.TCircularBuffer; import dev.mccue.tritonus.share.TDebug;
4,158
/* * TAsynchronousFilteredAudioInputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 1999, 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.convert; /** Base class for asynchronus converters. This class serves as base class for converters that do not have a fixed ratio between the size of a block of input data and the size of a block of output data. These types of converters therefore need an internal buffer, which is realized in this class. @author Matthias Pfisterer */ public abstract class TAsynchronousFilteredAudioInputStream extends TAudioInputStream implements TCircularBuffer.Trigger { private static final int DEFAULT_BUFFER_SIZE = 327670; private static final int DEFAULT_MIN_AVAILABLE = 4096; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // must be protected because it's accessed by the native CDDA lib protected TCircularBuffer m_circularBuffer; private int m_nMinAvailable; private byte[] m_abSingleByte; /** Constructor. This constructor uses the default buffer size and the default min available amount. @param lLength length of this stream in frames. May be AudioSystem.NOT_SPECIFIED. */ public TAsynchronousFilteredAudioInputStream(AudioFormat outputFormat, long lLength) { this(outputFormat, lLength, DEFAULT_BUFFER_SIZE, DEFAULT_MIN_AVAILABLE); } /** Constructor. With this constructor, the buffer size and the minimum available amount can be specified as parameters. @param lLength length of this stream in frames. May be AudioSystem.NOT_SPECIFIED. @param nBufferSize size of the circular buffer in bytes. */ public TAsynchronousFilteredAudioInputStream( AudioFormat outputFormat, long lLength, int nBufferSize, int nMinAvailable) { /* The usage of a ByteArrayInputStream is a hack. * (the infamous "JavaOne hack", because I did it on June * 6th 2000 in San Francisco, only hours before a * JavaOne session where I wanted to show mp3 playback * with Java Sound.) It is necessary because in the FCS * version of the Sun jdk1.3, the constructor of * AudioInputStream throws an exception if its first * argument is null. So we have to pass a dummy non-null * value. */ super(new ByteArrayInputStream(EMPTY_BYTE_ARRAY), outputFormat, lLength);
/* * TAsynchronousFilteredAudioInputStream.java * * This file is part of Tritonus: http://www.tritonus.org/ */ /* * Copyright (c) 1999, 2000 by Matthias Pfisterer * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library General Public License as published * by the Free Software Foundation; either version 2 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ /* |<--- this code is formatted to fit into 80 columns --->| */ package dev.mccue.tritonus.share.sampled.convert; /** Base class for asynchronus converters. This class serves as base class for converters that do not have a fixed ratio between the size of a block of input data and the size of a block of output data. These types of converters therefore need an internal buffer, which is realized in this class. @author Matthias Pfisterer */ public abstract class TAsynchronousFilteredAudioInputStream extends TAudioInputStream implements TCircularBuffer.Trigger { private static final int DEFAULT_BUFFER_SIZE = 327670; private static final int DEFAULT_MIN_AVAILABLE = 4096; private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // must be protected because it's accessed by the native CDDA lib protected TCircularBuffer m_circularBuffer; private int m_nMinAvailable; private byte[] m_abSingleByte; /** Constructor. This constructor uses the default buffer size and the default min available amount. @param lLength length of this stream in frames. May be AudioSystem.NOT_SPECIFIED. */ public TAsynchronousFilteredAudioInputStream(AudioFormat outputFormat, long lLength) { this(outputFormat, lLength, DEFAULT_BUFFER_SIZE, DEFAULT_MIN_AVAILABLE); } /** Constructor. With this constructor, the buffer size and the minimum available amount can be specified as parameters. @param lLength length of this stream in frames. May be AudioSystem.NOT_SPECIFIED. @param nBufferSize size of the circular buffer in bytes. */ public TAsynchronousFilteredAudioInputStream( AudioFormat outputFormat, long lLength, int nBufferSize, int nMinAvailable) { /* The usage of a ByteArrayInputStream is a hack. * (the infamous "JavaOne hack", because I did it on June * 6th 2000 in San Francisco, only hours before a * JavaOne session where I wanted to show mp3 playback * with Java Sound.) It is necessary because in the FCS * version of the Sun jdk1.3, the constructor of * AudioInputStream throws an exception if its first * argument is null. So we have to pass a dummy non-null * value. */ super(new ByteArrayInputStream(EMPTY_BYTE_ARRAY), outputFormat, lLength);
if (TDebug.TraceAudioConverter) { TDebug.out("TAsynchronousFilteredAudioInputStream.<init>(): begin"); }
1
2023-10-19 14:09:37+00:00
8k
dvillavicencio/Riven-of-a-Thousand-Servers
src/test/java/com/danielvm/destiny2bot/integration/InteractionControllerTest.java
[ { "identifier": "BungieConfiguration", "path": "src/main/java/com/danielvm/destiny2bot/config/BungieConfiguration.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"bungie.api\")\npublic class BungieConfiguration implements OAuth2Configuration {\n\n /**\n * The name of the Bungie API key header\n */\n private static final String API_KEY_HEADER_NAME = \"x-api-key\";\n\n /**\n * API key provided by Bungie when registering an application in their portal\n */\n private String key;\n\n /**\n * Bungie clientId\n */\n private String clientId;\n\n /**\n * Bungie client secret\n */\n private String clientSecret;\n\n /**\n * Base url for Bungie Requests\n */\n private String baseUrl;\n\n /**\n * Url for Bungie Token endpoint\n */\n private String tokenUrl;\n\n /**\n * Url for OAuth2 authorization flow\n */\n private String authorizationUrl;\n\n /**\n * Url for callback during OAuth2 authorization\n */\n private String callbackUrl;\n\n @Bean\n public BungieClient bungieCharacterClient(WebClient.Builder builder) {\n var webClient = builder\n .baseUrl(this.baseUrl)\n .defaultHeader(API_KEY_HEADER_NAME, this.key)\n .build();\n return HttpServiceProxyFactory.builder()\n .exchangeAdapter(WebClientAdapter.create(webClient))\n .build()\n .createClient(BungieClient.class);\n }\n}" }, { "identifier": "DiscordConfiguration", "path": "src/main/java/com/danielvm/destiny2bot/config/DiscordConfiguration.java", "snippet": "@Data\n@Configuration\n@ConfigurationProperties(prefix = \"discord.api\")\npublic class DiscordConfiguration implements OAuth2Configuration {\n\n /**\n * Base Url for Discord API calls\n */\n private String baseUrl;\n\n /**\n * The token for the Discord Bot\n */\n private String botToken;\n\n /**\n * The Bot's public key for verifying request signatures\n */\n private String botPublicKey;\n\n /**\n * The clientId for OAuth2 authentication\n */\n private String clientId;\n\n /**\n * The clientSecret for OAuth2 authentication\n */\n private String clientSecret;\n\n /**\n * The callback URL for OAuth2 authentication\n */\n private String callbackUrl;\n\n /**\n * The authorization url for OAuth2 authentication\n */\n private String authorizationUrl;\n\n /**\n * Token URL to retrieve access token for OAuth2\n */\n private String tokenUrl;\n\n /**\n * List of scopes for Discord OAuth2\n */\n private List<String> scopes;\n\n @Bean\n public DiscordClient discordClient(WebClient.Builder defaultBuilder) {\n var webClient = defaultBuilder\n .baseUrl(this.baseUrl)\n .build();\n return HttpServiceProxyFactory.builder()\n .exchangeAdapter(WebClientAdapter.create(webClient))\n .build()\n .createClient(DiscordClient.class);\n }\n}" }, { "identifier": "UserDetailsReactiveDao", "path": "src/main/java/com/danielvm/destiny2bot/dao/UserDetailsReactiveDao.java", "snippet": "@Repository\npublic class UserDetailsReactiveDao {\n\n private final ReactiveRedisTemplate<String, UserDetails> reactiveRedisTemplate;\n\n public UserDetailsReactiveDao(\n ReactiveRedisTemplate<String, UserDetails> reactiveRedisTemplate) {\n this.reactiveRedisTemplate = reactiveRedisTemplate;\n }\n\n /**\n * Save an entity to Redis if it was not previously present\n *\n * @param userDetails The entity to persist\n * @return True if it was successful, else returns False\n */\n public Mono<Boolean> save(UserDetails userDetails) {\n return reactiveRedisTemplate.opsForValue()\n .set(userDetails.getDiscordId(), userDetails);\n }\n\n /**\n * Return user details by their discordId\n *\n * @param discordId The discordId to find by\n * @return {@link UserDetails}\n */\n public Mono<UserDetails> getByDiscordId(String discordId) {\n return reactiveRedisTemplate.opsForValue().get(discordId);\n }\n\n /**\n * Returns if an entity with the given discordId exists\n *\n * @param discordId The discordId to check for\n * @return True if it exists, else False\n */\n public Mono<Boolean> existsByDiscordId(String discordId) {\n return reactiveRedisTemplate.opsForValue().get(discordId).hasElement();\n }\n}" }, { "identifier": "GenericResponse", "path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/GenericResponse.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GenericResponse<T> {\n\n /**\n * Most of the responses from Bungie.net have a Json element named 'Response' with arbitrary info\n * depending on the endpoint. This field is just a generic-wrapper for it.\n */\n @JsonAlias(\"Response\")\n @Nullable\n private T response;\n}" }, { "identifier": "MilestoneEntry", "path": "src/main/java/com/danielvm/destiny2bot/dto/destiny/milestone/MilestoneEntry.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class MilestoneEntry {\n\n private String milestoneHash;\n private ZonedDateTime startDate;\n private ZonedDateTime endDate;\n private List<ActivitiesDto> activities;\n}" }, { "identifier": "DiscordUser", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/DiscordUser.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class DiscordUser {\n\n /**\n * The user's Identification\n */\n private String id;\n\n /**\n * The user's username\n */\n private String username;\n}" }, { "identifier": "Interaction", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/Interaction.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Interaction implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 315485352844067387L;\n\n /**\n * The Id of the interaction\n */\n private Object id;\n\n /**\n * The Id of the application\n */\n @JsonAlias(\"application_id\")\n private Object applicationId;\n\n /**\n * The type of the interaction (see {@link com.danielvm.destiny2bot.enums.InteractionType})\n */\n private Integer type;\n\n /**\n * Additional data of the interaction, will be attached to all interactions besides PING\n */\n private InteractionData data;\n\n /**\n * Member Data of the user that invoked the command\n */\n private Member member;\n\n}" }, { "identifier": "InteractionData", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/InteractionData.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class InteractionData {\n\n /**\n * The Id of the invoked command\n */\n private Object id;\n\n /**\n * The name of the invoked command\n */\n private String name;\n\n /**\n * The type of the invoked command\n */\n private Integer type;\n\n}" }, { "identifier": "Member", "path": "src/main/java/com/danielvm/destiny2bot/dto/discord/Member.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Member {\n\n /**\n * Information about the user that sent the interaction\n */\n private DiscordUser user;\n}" }, { "identifier": "UserDetails", "path": "src/main/java/com/danielvm/destiny2bot/entity/UserDetails.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UserDetails implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 6161559188488304844L;\n\n private String discordId;\n\n private String discordUsername;\n\n private String accessToken;\n\n private String refreshToken;\n\n private Instant expiration;\n}" }, { "identifier": "InteractionType", "path": "src/main/java/com/danielvm/destiny2bot/enums/InteractionType.java", "snippet": "public enum InteractionType {\n PING(1),\n APPLICATION_COMMAND(2),\n MESSAGE_COMPONENT(3),\n APPLICATION_COMMAND_AUTOCOMPLETE(4),\n MODAL_SUBMIT(5);\n\n @Getter\n private final Integer type;\n\n InteractionType(Integer type) {\n this.type = type;\n }\n\n /**\n * Find an InteractionType type by their integer code\n *\n * @param type The integer code of the interaction\n * @return {@link InteractionType}\n */\n public static InteractionType findByValue(Integer type) {\n return Arrays.stream(InteractionType.values())\n .filter(it -> Objects.equals(it.type, type))\n .findFirst().orElse(null);\n }\n}" }, { "identifier": "ManifestEntity", "path": "src/main/java/com/danielvm/destiny2bot/enums/ManifestEntity.java", "snippet": "public enum ManifestEntity {\n\n BUCKET_DEFINITION(\"DestinyInventoryItemDefinition\"),\n STAT_DEFINITION(\"DestinyStatDefinition\"),\n CLASS_DEFINITION(\"DestinyClassDefinition\"),\n ITEM_INVENTORY_DEFINITION(\"DestinyInventoryItemDefinition\"),\n MILESTONE_DEFINITION(\"DestinyMilestoneDefinition\"),\n ACTIVITY_TYPE_DEFINITION(\"DestinyActivityTypeDefinition\"),\n ACTIVITY_DEFINITION(\"DestinyActivityDefinition\");\n\n @Getter\n private final String id;\n\n ManifestEntity(String id) {\n this.id = id;\n }\n}" }, { "identifier": "MessageUtil", "path": "src/main/java/com/danielvm/destiny2bot/util/MessageUtil.java", "snippet": "public class MessageUtil {\n\n private static final LocalTime DESTINY_2_STANDARD_RESET_TIME = LocalTime.of(9, 0);\n private static final ZoneId STANDARD_TIMEZONE = ZoneId.of(\"America/Los_Angeles\");\n public static final ZonedDateTime NEXT_TUESDAY = ZonedDateTime.of(\n LocalDate.now(STANDARD_TIMEZONE), DESTINY_2_STANDARD_RESET_TIME, STANDARD_TIMEZONE)\n .with(TemporalAdjusters.next(DayOfWeek.TUESDAY));\n public static final ZonedDateTime PREVIOUS_TUESDAY = ZonedDateTime.of(\n LocalDate.now(STANDARD_TIMEZONE), DESTINY_2_STANDARD_RESET_TIME, STANDARD_TIMEZONE)\n .with(TemporalAdjusters.previous(DayOfWeek.TUESDAY));\n\n /**\n * Formatter used to format the date for a message Example: the LocalDate object with date\n * 2023-01-01 would be formatted to \"Sunday 1st, January 2023\"\n */\n private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern(\n \"EEEE d'%s', MMMM yyyy\");\n\n private MessageUtil() {\n }\n\n /**\n * Format the given local date using the class formatter, it also includes the correct suffix for\n * a date\n *\n * @param localDate the date to be formatted\n * @return String of the formatted local date\n */\n public static String formatDate(LocalDate localDate) {\n Integer dayOfMonth = localDate.getDayOfMonth();\n return FORMATTER.format(localDate)\n .formatted(suffix(dayOfMonth));\n }\n\n private static String suffix(Integer dayOfMonth) {\n if (dayOfMonth >= 11 && dayOfMonth <= 13) {\n return \"th\";\n }\n return switch (dayOfMonth % 10) {\n case 1 -> \"st\";\n case 2 -> \"nd\";\n case 3 -> \"rd\";\n default -> \"th\";\n };\n }\n\n}" }, { "identifier": "OAuth2Util", "path": "src/main/java/com/danielvm/destiny2bot/util/OAuth2Util.java", "snippet": "@Validated\npublic class OAuth2Util {\n\n private static final String BEARER_TOKEN_FORMAT = \"Bearer %s\";\n\n private OAuth2Util() {\n }\n\n /**\n * Format the given token to bearer token format\n *\n * @param token The token to format\n * @return The formatted String\n */\n public static String formatBearerToken(String token) {\n return BEARER_TOKEN_FORMAT.formatted(token);\n }\n\n /**\n * Build body parameters for a token request to an OAuth2 resource provider\n *\n * @param authorizationCode The authorization code\n * @param redirectUri The redirect type\n * @param clientSecret The client secret\n * @param clientId The clientId\n * @return {@link MultiValueMap} of OAuth2 attributes for Token exchange\n */\n public static MultiValueMap<String, String> buildTokenExchangeParameters(\n String authorizationCode,\n String redirectUri,\n String clientSecret,\n String clientId) {\n MultiValueMap<String, String> map = new LinkedMultiValueMap<>();\n map.add(OAuth2Params.CODE, authorizationCode);\n map.add(OAuth2Params.GRANT_TYPE, OAuth2Params.AUTHORIZATION_CODE);\n map.add(OAuth2Params.REDIRECT_URI, redirectUri);\n map.add(OAuth2Params.CLIENT_SECRET, clientSecret);\n map.add(OAuth2Params.CLIENT_ID, clientId);\n return map;\n }\n\n /**\n * Build body parameters for a token request to an OAuth2 resource provider\n *\n * @param refreshToken The refresh token to send\n * @return {@link MultiValueMap} of OAuth2 attributes for refresh token exchange\n */\n public static MultiValueMap<String, String> buildRefreshTokenExchangeParameters(\n String refreshToken, String clientId, String clientSecret) {\n MultiValueMap<String, String> map = new LinkedMultiValueMap<>();\n map.add(OAuth2Params.GRANT_TYPE, OAuth2Params.REFRESH_TOKEN);\n map.add(OAuth2Params.REFRESH_TOKEN, refreshToken);\n map.add(OAuth2Params.CLIENT_ID, clientId);\n map.add(OAuth2Params.CLIENT_SECRET, clientSecret);\n return map;\n }\n\n /**\n * Return the qualified url with all parameters\n *\n * @param bungieConfiguration The config class containing all necessary information to build the\n * authorization URI\n * @return The authorization url with all required parameters\n */\n public static String bungieAuthorizationUrl(String authUrl, String clientId) {\n return UriComponentsBuilder\n .fromHttpUrl(authUrl)\n .queryParam(OAuth2Params.RESPONSE_TYPE, OAuth2Params.CODE)\n .queryParam(OAuth2Params.CLIENT_ID, clientId)\n .build().toString();\n }\n\n /**\n * Returns a registration link based on some OAuth2 parameters. This URL can be used to register\n * the bot to an end-user's Discord server\n *\n * @param authUrl The authorization URL parameter\n * @param clientId The clientId parameter\n * @param callbackUrl The callback URL parameter\n * @param scopes The scopes parameter\n * @return a String with the above parameters\n */\n public static String discordAuthorizationUrl(\n String authUrl, String clientId, String callbackUrl, String scopes) {\n return UriComponentsBuilder.fromHttpUrl(authUrl)\n .queryParam(OAuth2Params.CLIENT_ID, clientId)\n .queryParam(OAuth2Params.REDIRECT_URI,\n URLEncoder.encode(callbackUrl, StandardCharsets.UTF_8))\n .queryParam(OAuth2Params.RESPONSE_TYPE, OAuth2Params.CODE)\n .queryParam(OAuth2Params.SCOPE, scopes).build().toString();\n }\n\n}" } ]
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.assertj.core.api.Assertions.assertThat; import com.danielvm.destiny2bot.config.BungieConfiguration; import com.danielvm.destiny2bot.config.DiscordConfiguration; import com.danielvm.destiny2bot.dao.UserDetailsReactiveDao; import com.danielvm.destiny2bot.dto.destiny.GenericResponse; import com.danielvm.destiny2bot.dto.destiny.milestone.MilestoneEntry; import com.danielvm.destiny2bot.dto.discord.DiscordUser; import com.danielvm.destiny2bot.dto.discord.Interaction; import com.danielvm.destiny2bot.dto.discord.InteractionData; import com.danielvm.destiny2bot.dto.discord.Member; import com.danielvm.destiny2bot.entity.UserDetails; import com.danielvm.destiny2bot.enums.InteractionType; import com.danielvm.destiny2bot.enums.ManifestEntity; import com.danielvm.destiny2bot.util.MessageUtil; import com.danielvm.destiny2bot.util.OAuth2Util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.KeyPair; import java.security.PublicKey; import java.time.Instant; import java.util.Map; import java.util.Objects; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; import org.springframework.web.reactive.function.BodyInserters; import software.pando.crypto.nacl.Crypto;
7,052
stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/")) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(400) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/missing-api-key.json"))); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON is correct String errorJson; try { errorJson = objectMapper.writeValueAsString( objectMapper.readValue( new ClassPathResource("__files/bungie/missing-api-key.json").getInputStream(), Object.class)); } catch (IOException e) { throw new RuntimeException(e); } response.expectStatus() .isBadRequest() .expectBody() .jsonPath("$.detail").value(json -> assertJsonLenient(errorJson, json)) .jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value()); } @Test @DisplayName("Interactions fail if the signature is invalid") public void getWeeklyRaidInvalidSignature() throws JsonProcessingException, DecoderException { // given: an interaction with an invalid signature InteractionData data = new InteractionData(2, "weekly_raid", 1); Interaction body = new Interaction(1, "theApplicationId", 2, data, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createInvalidSignature(body, timestamp); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON has the correct error message response.expectStatus() .isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value()) .jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid"); } @Test @DisplayName("PING interactions with valid signatures are ack'd correctly") public void pingRequestsAreAckdCorrectly() throws JsonProcessingException, DecoderException { // given: an interaction with an invalid signature Interaction body = new Interaction(1, "theApplicationId", 1, null, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createValidSignature(body, timestamp); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON has the correct error message response.expectStatus() .isOk() .expectBody() .jsonPath("$.type").isEqualTo(InteractionType.PING.getType()); } @Test @DisplayName("PING interactions with invalid signatures are not ack'd") public void invalidPingRequestsAreNotAckd() throws JsonProcessingException, DecoderException { // given: an interaction with an invalid signature Interaction body = new Interaction(1, "theApplicationId", 1, null, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createInvalidSignature(body, timestamp); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON has the correct error message response.expectStatus() .isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value()) .jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid"); } @Test @DisplayName("Autocomplete requests for raid stats returns the user's characters successfully") public void autocompleteRequestsForRaidStats() throws DecoderException, JsonProcessingException { // given: a valid autocomplete request String username = "deahtstroke"; String discordId = "123456";
package com.danielvm.destiny2bot.integration; public class InteractionControllerTest extends BaseIntegrationTest { private static final String VALID_PRIVATE_KEY = "F0EA3A0516695324C03ED552CD5A08A58CA1248172E8816C3BF235E52E75A7BF"; private static final String MALICIOUS_PRIVATE_KEY = "CE4517095255B0C92D586AF9EEC27B998D68775363F9FE74341483FB3A657CEC"; // Static mapper to be used on the @BeforeAll static method private static final ObjectMapper OBJECT_MAPPER = new JsonMapper.Builder(new JsonMapper()) .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .build() .registerModule(new JavaTimeModule()); @Autowired BungieConfiguration bungieConfiguration; @Autowired DiscordConfiguration discordConfiguration; @Autowired UserDetailsReactiveDao userDetailsReactiveDao; /** * This method replaces all the placeholder values in the milestones-response.json file The reason * for this is that the /weekly_raid and /weekly_dungeon responses will be weird if the dates are * not dynamic, therefore this method * * @throws IOException in case we are not able to write back to the file (in-place) */ @BeforeAll public static void before() throws IOException { File milestoneFile = new File("src/test/resources/__files/bungie/milestone-response.json"); TypeReference<GenericResponse<Map<String, MilestoneEntry>>> typeReference = new TypeReference<>() { }; var milestoneResponse = OBJECT_MAPPER.readValue(milestoneFile, typeReference); replaceDates(milestoneResponse, "526718853"); replaceDates(milestoneResponse, "2712317338"); OBJECT_MAPPER.writeValue(milestoneFile, milestoneResponse); } private static void replaceDates(GenericResponse<Map<String, MilestoneEntry>> response, String hash) { response.getResponse().entrySet().stream() .filter(entry -> Objects.equals(entry.getKey(), hash)) .forEach(entry -> { var startDate = entry.getValue().getStartDate(); var endDate = entry.getValue().getEndDate(); if (Objects.nonNull(startDate)) { entry.getValue().setStartDate(MessageUtil.PREVIOUS_TUESDAY); } if (Objects.nonNull(endDate)) { entry.getValue().setEndDate(MessageUtil.NEXT_TUESDAY); } }); } private String createValidSignature(Interaction body, String timestamp) throws JsonProcessingException, DecoderException { KeyPair signingKeys = Crypto.seedSigningKeyPair(Hex.decodeHex(VALID_PRIVATE_KEY.toCharArray())); discordConfiguration.setBotPublicKey( Hex.encodeHexString( signingKeys.getPublic().getEncoded())); // change the public key in the config class var signatureBytes = Crypto.sign(signingKeys.getPrivate(), (timestamp + objectMapper.writeValueAsString(body)).getBytes(StandardCharsets.UTF_8)); return Hex.encodeHexString(signatureBytes); } private String createInvalidSignature(Interaction body, String timestamp) throws JsonProcessingException, DecoderException { KeyPair invalidSigningKeyPair = Crypto.seedSigningKeyPair( Hex.decodeHex(MALICIOUS_PRIVATE_KEY.toCharArray())); PublicKey validPublicKey = Crypto.seedSigningKeyPair( Hex.decodeHex(VALID_PRIVATE_KEY.toCharArray())).getPublic(); discordConfiguration.setBotPublicKey( Hex.encodeHexString(validPublicKey.getEncoded())); var signatureBytes = Crypto.sign(invalidSigningKeyPair.getPrivate(), (timestamp + objectMapper.writeValueAsString(body)).getBytes(StandardCharsets.UTF_8)); return Hex.encodeHexString(signatureBytes); } @Test @DisplayName("get weekly dungeon works successfully") public void getWeeklyDungeonWorksSuccessfully() throws JsonProcessingException, DecoderException { // given: a weekly_dungeon interaction with a valid signature InteractionData weeklyDungeonData = new InteractionData(2, "weekly_dungeon", 1); Interaction body = new Interaction(1, "theApplicationId", 2, weeklyDungeonData, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createValidSignature(body, timestamp); stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/")) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/milestone-response.json"))); var activityDefinition = ManifestEntity.ACTIVITY_DEFINITION.getId(); var activityHash = "1262462921"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(activityDefinition, activityHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/dungeon-activity-response.json"))); var masterDungeonHash = "2296818662"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(activityDefinition, masterDungeonHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/master-dungeon-activity-response.json"))); var activityTypeDefinition = ManifestEntity.ACTIVITY_TYPE_DEFINITION.getId(); var activityTypeHash = "608898761"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(activityTypeDefinition, activityTypeHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/dungeon-activity-type-response.json"))); var milestoneDefinition = ManifestEntity.MILESTONE_DEFINITION.getId(); var milestoneHash = "526718853"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(milestoneDefinition, milestoneHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/dungeon-milestone-response.json"))); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON is correct response.expectStatus() .isOk() .expectBody() .jsonPath("$.type").isEqualTo(4) .jsonPath("$.data.content").isEqualTo( """ This week's dungeon is: Spire of the Watcher. You have until %s to complete it before the next dungeon in the rotation. """.formatted(MessageUtil.formatDate(MessageUtil.NEXT_TUESDAY.toLocalDate()))); } @Test @DisplayName("get weekly raid works successfully") public void getWeeklyRaidWorksSuccessfully() throws JsonProcessingException, DecoderException { // given: a weekly_raid interaction with a valid signature InteractionData weeklyRaidData = new InteractionData(2, "weekly_raid", 1); Interaction body = new Interaction(1, "theApplicationId", 2, weeklyRaidData, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createValidSignature(body, timestamp); stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/")) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/milestone-response.json"))); var activityDefinition = ManifestEntity.ACTIVITY_DEFINITION.getId(); var activityHash = "1042180643"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(activityDefinition, activityHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/raid-activity-response.json"))); var activityTypeDefinition = ManifestEntity.ACTIVITY_TYPE_DEFINITION.getId(); var activityTypeHash = "2043403989"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(activityTypeDefinition, activityTypeHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/raid-activity-type-response.json"))); var milestoneDefinition = ManifestEntity.MILESTONE_DEFINITION.getId(); var milestoneHash = "2712317338"; stubFor(get(urlPathEqualTo( "/bungie/Destiny2/Manifest/%s/%s/".formatted(milestoneDefinition, milestoneHash))) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(200) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/raid-milestone-response.json"))); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON is correct response.expectStatus() .isOk() .expectBody() .jsonPath("$.type").isEqualTo(4) .jsonPath("$.data.content").isEqualTo( """ This week's raid is: Garden of Salvation. You have until %s to complete it before the next raid comes along. """.formatted(MessageUtil.formatDate(MessageUtil.NEXT_TUESDAY.toLocalDate()))); } @Test @DisplayName("get weekly raid fails if no milestones are found") public void getWeeklyRaidsShouldThrowErrors() throws JsonProcessingException, DecoderException { // given: a weekly_raid interaction with a valid signature InteractionData weeklyRaidData = new InteractionData(2, "weekly_raid", 1); Interaction body = new Interaction(1, "theApplicationId", 2, weeklyRaidData, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createValidSignature(body, timestamp); stubFor(get(urlPathEqualTo("/bungie/Destiny2/Milestones/")) .withHeader("x-api-key", equalTo(bungieConfiguration.getKey())) .willReturn(aResponse() .withStatus(400) .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .withBodyFile("bungie/missing-api-key.json"))); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON is correct String errorJson; try { errorJson = objectMapper.writeValueAsString( objectMapper.readValue( new ClassPathResource("__files/bungie/missing-api-key.json").getInputStream(), Object.class)); } catch (IOException e) { throw new RuntimeException(e); } response.expectStatus() .isBadRequest() .expectBody() .jsonPath("$.detail").value(json -> assertJsonLenient(errorJson, json)) .jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value()); } @Test @DisplayName("Interactions fail if the signature is invalid") public void getWeeklyRaidInvalidSignature() throws JsonProcessingException, DecoderException { // given: an interaction with an invalid signature InteractionData data = new InteractionData(2, "weekly_raid", 1); Interaction body = new Interaction(1, "theApplicationId", 2, data, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createInvalidSignature(body, timestamp); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON has the correct error message response.expectStatus() .isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value()) .jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid"); } @Test @DisplayName("PING interactions with valid signatures are ack'd correctly") public void pingRequestsAreAckdCorrectly() throws JsonProcessingException, DecoderException { // given: an interaction with an invalid signature Interaction body = new Interaction(1, "theApplicationId", 1, null, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createValidSignature(body, timestamp); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON has the correct error message response.expectStatus() .isOk() .expectBody() .jsonPath("$.type").isEqualTo(InteractionType.PING.getType()); } @Test @DisplayName("PING interactions with invalid signatures are not ack'd") public void invalidPingRequestsAreNotAckd() throws JsonProcessingException, DecoderException { // given: an interaction with an invalid signature Interaction body = new Interaction(1, "theApplicationId", 1, null, null); String timestamp = String.valueOf(Instant.now().getEpochSecond()); String signature = createInvalidSignature(body, timestamp); // when: the request is sent var response = webTestClient.post() .uri("/interactions") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .header("X-Signature-Ed25519", signature) .header("X-Signature-Timestamp", timestamp) .body(BodyInserters.fromValue(body)) .exchange(); // then: the response JSON has the correct error message response.expectStatus() .isBadRequest() .expectBody() .jsonPath("$.status").isEqualTo(HttpStatus.BAD_REQUEST.value()) .jsonPath("$.detail").isEqualTo("interactions.request: Signature is invalid"); } @Test @DisplayName("Autocomplete requests for raid stats returns the user's characters successfully") public void autocompleteRequestsForRaidStats() throws DecoderException, JsonProcessingException { // given: a valid autocomplete request String username = "deahtstroke"; String discordId = "123456";
DiscordUser user = new DiscordUser(discordId, username);
5
2023-10-20 05:53:03+00:00
8k
MinecraftForge/ModLauncher
ml-test/src/test/java/net/minecraftforge/modlauncher/test/ClassTransformerTests.java
[ { "identifier": "ITransformationService", "path": "src/main/java/cpw/mods/modlauncher/api/ITransformationService.java", "snippet": "public interface ITransformationService {\n /**\n * The name of this mod service. It will be used throughout the system. It should be lower case,\n * the first character should be alphanumeric and it should only consist of standard alphanumeric\n * characters\n *\n * @return the name of the mod service\n */\n @NotNull\n String name();\n\n /**\n * Define command line arguments for your mod service. These will be prefixed by your {@link #name()}\n * to prevent collisions.\n *\n * @param argumentBuilder a function mapping name, description to a set of JOptSimple properties for that argument\n */\n default void arguments(BiFunction<String, String, OptionSpecBuilder> argumentBuilder) {\n }\n\n default void argumentValues(OptionResult option) {\n }\n\n /**\n * Initialize your service.\n *\n * @param environment environment - query state from here to determine viability\n */\n void initialize(IEnvironment environment);\n\n record Resource(IModuleLayerManager.Layer target, List<SecureJar> resources) {}\n /**\n * Scan for mods (but don't classload them), identify metadata that might drive\n * game functionality, return list of elements and target module layer (One of PLUGIN or GAME)\n *\n * @param environment environment\n */\n default List<Resource> beginScanning(IEnvironment environment) {\n return List.of();\n }\n\n default List<Resource> completeScan(IModuleLayerManager layerManager) {\n return List.of();\n }\n\n /**\n * Load your service. Called immediately on loading with a list of other services found.\n * Use to identify and immediately indicate incompatibilities with other services, and environment\n * configuration. This is to try and immediately abort a guaranteed bad environment.\n *\n * @param env environment - query state from here\n * @param otherServices other services loaded with the system\n * @throws IncompatibleEnvironmentException if there is an incompatibility detected. Identify specifics in\n * the exception message\n */\n void onLoad(IEnvironment env, Set<String> otherServices) throws IncompatibleEnvironmentException;\n\n /**\n * The {@link ITransformer} is the fundamental operator of the system.\n *\n * @return A list of transformers for your ITransformationService. This is called after {@link #onLoad(IEnvironment, Set)}\n * and {@link #initialize(IEnvironment)}, so you can return an appropriate Transformer set for the environment\n * you find yourself in.\n */\n @NotNull\n List<ITransformer> transformers();\n\n /** Hasn't been called in ages, will be removed in next breaking bump */\n @Deprecated(forRemoval = true, since = \"10.1\")\n default Map.Entry<Set<String>,Supplier<Function<String, Optional<URL>>>> additionalClassesLocator() {\n return null;\n }\n\n /** Hasn't been called in ages, will be removed in next breaking bump */\n @Deprecated(forRemoval = true, since = \"10.1\")\n default Map.Entry<Set<String>,Supplier<Function<String, Optional<URL>>>> additionalResourcesLocator() {\n return null;\n }\n\n interface OptionResult {\n <V> V value(OptionSpec<V> options);\n\n @NotNull\n <V> List<V> values(OptionSpec<V> options);\n }\n}" }, { "identifier": "ITransformer", "path": "src/main/java/cpw/mods/modlauncher/api/ITransformer.java", "snippet": "public interface ITransformer<T> {\n\n String[] DEFAULT_LABEL = {\"default\"};\n\n /**\n * Transform the input to the ITransformer's desire. The context from the last vote is\n * provided as well.\n *\n * @param input The ASM input node, which can be mutated directly\n * @param context The voting context\n * @return An ASM node of the same type as that supplied. It will be used for subsequent\n * rounds of voting.\n */\n @NotNull\n T transform(T input, ITransformerVotingContext context);\n\n /**\n * Return the {@link TransformerVoteResult} for this transformer.\n * The transformer should evaluate whether or not is is a candidate to apply during\n * the round of voting in progress, represented by the context parameter.\n * How the vote works:\n * <ul>\n * <li>If the transformer wishes to be a candidate, it should return {@link TransformerVoteResult#YES}.</li>\n * <li>If the transformer wishes to exit the voting (the transformer has already\n * has its intended change applied, for example), it should return {@link TransformerVoteResult#NO}</li>\n * <li>If the transformer wishes to wait for future rounds of voting it should return\n * {@link TransformerVoteResult#DEFER}. Note that if there is <em>no</em> YES candidate, but DEFER\n * candidates remain, this is a DEFERRAL stalemate and the game will crash.</li>\n * <li>If the transformer wishes to crash the game, it should return {@link TransformerVoteResult#REJECT}.\n * This is extremely frowned upon, and should not be used except in extreme circumstances. If an\n * incompatibility is present, it should detect and handle it in the {@link ITransformationService#onLoad}\n * </li>\n * </ul>\n * After all votes from candidate transformers are collected, the NOs are removed from the\n * current set of voters, one from the set of YES voters is selected and it's {@link ITransformer#transform(Object, ITransformerVotingContext)}\n * method called. It is then removed from the set of transformers and another round is performed.\n *\n * @param context The context of the vote\n * @return A TransformerVoteResult indicating the desire of this transformer\n */\n @NotNull\n TransformerVoteResult castVote(ITransformerVotingContext context);\n\n /**\n * Return a set of {@link Target} identifying which elements this transformer wishes to try\n * and apply to. The {@link Target#getTargetType()} must match the T variable for the transformer\n * as documented in {@link TargetType}, other combinations will be rejected.\n *\n * @return The set of targets this transformer wishes to apply to\n */\n @NotNull\n Set<Target> targets();\n\n /**\n * @return A string array for uniquely identifying this transformer instance within the service.\n */\n default String[] labels() {\n return DEFAULT_LABEL;\n }\n /**\n * Specifies the target type for the {@link Target}. Note that the type of the transformer T\n * dictates what are acceptable targets for this transformer.\n */\n enum TargetType {\n /**\n * Target a class. The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.ClassNode}\n */\n CLASS,\n /**\n * Target a method. The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.MethodNode}\n */\n METHOD,\n /**\n * Target a field. The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.FieldNode}\n */\n FIELD,\n /**\n * Target a class, before field and method transforms operate. SHOULD ONLY BE USED to \"replace\" a complete class\n * The {@link ITransformer} T variable must refer to {@link org.objectweb.asm.tree.ClassNode}\n */\n PRE_CLASS;\n }\n\n /**\n * Simple data holder indicating where the {@link ITransformer} can target.\n */\n @SuppressWarnings(\"SameParameterValue\")\n final class Target {\n private final String className;\n private final String elementName;\n private final String elementDescriptor;\n private final TargetType targetType;\n\n /**\n * Build a new target. Ensure that the targetType matches the T type for the ITransformer\n * supplying the target.\n * <p>\n * In an obfuscated environment, this will be the obfuscated \"notch\" naming, in a\n * deobfuscated environment this will be the searge naming.\n *\n * @param className The name of the class being targetted\n * @param elementName The name of the element being targetted. This is the field name for a field,\n * the method name for a method. Empty string for other types\n * @param elementDescriptor The method's descriptor. Empty string for other types\n * @param targetType The {@link TargetType} for this target - it should match the ITransformer\n * type variable T\n */\n Target(String className, String elementName, String elementDescriptor, TargetType targetType) {\n Objects.requireNonNull(className, \"Class Name cannot be null\");\n Objects.requireNonNull(elementName, \"Element Name cannot be null\");\n Objects.requireNonNull(elementDescriptor, \"Element Descriptor cannot be null\");\n Objects.requireNonNull(targetType, \"Target Type cannot be null\");\n this.className = className;\n this.elementName = elementName;\n this.elementDescriptor = elementDescriptor;\n this.targetType = targetType;\n }\n\n /**\n * Convenience method returning a {@link Target} for a class\n *\n * @param className The name of the class\n * @return A target for the named class\n */\n @NotNull\n public static Target targetClass(String className) {\n return new Target(className, \"\", \"\", TargetType.CLASS);\n }\n\n /**\n * Convenience method returning a {@link Target} for a class (prior to other loading operations)\n *\n * @param className The name of the class\n * @return A target for the named class\n */\n @NotNull\n public static Target targetPreClass(String className) {\n return new Target(className, \"\", \"\", TargetType.PRE_CLASS);\n }\n /**\n * Convenience method return a {@link Target} for a method\n *\n * @param className The name of the class containing the method\n * @param methodName The name of the method\n * @param methodDescriptor The method's descriptor string\n * @return A target for the named method\n */\n @NotNull\n public static Target targetMethod(String className, String methodName, String methodDescriptor) {\n return new Target(className, methodName, methodDescriptor, TargetType.METHOD);\n }\n\n /**\n * Convenience method returning a {@link Target} for a field\n *\n * @param className The name of the class containing the field\n * @param fieldName The name of the field\n * @return A target for the named field\n */\n @NotNull\n public static Target targetField(String className, String fieldName) {\n return new Target(className, fieldName, \"\", TargetType.FIELD);\n }\n\n /**\n * @return The class name for this target\n */\n public String getClassName() {\n return className;\n }\n\n /**\n * @return The element name for this target, either the field name or the method name\n */\n public String getElementName() {\n return elementName;\n }\n\n /**\n * @return The element's descriptor. Usually the method descriptor\n */\n public String getElementDescriptor() {\n return elementDescriptor;\n }\n\n /**\n * @return The target type of this target\n */\n public TargetType getTargetType() {\n return targetType;\n }\n }\n}" }, { "identifier": "ITransformerVotingContext", "path": "src/main/java/cpw/mods/modlauncher/api/ITransformerVotingContext.java", "snippet": "public interface ITransformerVotingContext {\n /**\n * @return The class name being transformed\n */\n String getClassName();\n\n /**\n * @return If the class already existed\n */\n boolean doesClassExist();\n\n /**\n * @return The initial sha256 checksum of the class bytes.\n */\n byte[] getInitialClassSha256();\n\n /**\n * @return The activities already performed on this class. This list is read only, but will change as activities happen.\n */\n List<ITransformerActivity> getAuditActivities();\n\n String getReason();\n\n /**\n * Return the result of applying the supplied field predicate to the current field node.\n * Can only be used on a Field target.\n *\n * @param fieldPredicate The field predicate\n * @return true if the predicate passed\n */\n boolean applyFieldPredicate(FieldPredicate fieldPredicate);\n\n /**\n * Return the result of applying the supplied method predicate to the current method node.\n * Can only be used on a Method target.\n *\n * @param methodPredicate The method predicate\n * @return true if the predicate passed\n */\n boolean applyMethodPredicate(MethodPredicate methodPredicate);\n\n /**\n * Return the result of applying the supplied class predicate to the current class node.\n * Can only be used on a Class target.\n *\n * @param classPredicate The class predicate\n * @return true if the predicate passed\n */\n boolean applyClassPredicate(ClassPredicate classPredicate);\n\n /**\n * Return the result of applying the supplied instruction predicate to the current method node.\n * Can only be used on a Method target.\n *\n * @param insnPredicate The insn predicate\n * @return true if the predicate passed\n */\n boolean applyInstructionPredicate(InsnPredicate insnPredicate);\n\n interface FieldPredicate {\n boolean test(final int access, final String name, final String descriptor, final String signature, final Object value);\n }\n\n interface MethodPredicate {\n boolean test(final int access, final String name, final String descriptor, final String signature, final String[] exceptions);\n }\n\n interface ClassPredicate {\n boolean test(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces);\n }\n\n interface InsnPredicate {\n boolean test(final int insnCount, final int opcode, Object... args);\n }\n}" }, { "identifier": "TransformerVoteResult", "path": "src/main/java/cpw/mods/modlauncher/api/TransformerVoteResult.java", "snippet": "public enum TransformerVoteResult {\n YES, DEFER, NO, REJECT\n}" } ]
import cpw.mods.modlauncher.*; import cpw.mods.modlauncher.api.ITransformationService; import cpw.mods.modlauncher.api.ITransformer; import cpw.mods.modlauncher.api.ITransformerVotingContext; import cpw.mods.modlauncher.api.TransformerVoteResult; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.MarkerManager; import org.apache.logging.log4j.core.config.Configurator; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldNode; import org.powermock.reflect.Whitebox; import java.util.Collections; import java.util.Set; import static org.junit.jupiter.api.Assertions.*;
4,234
/* * Copyright (c) Forge Development LLC * SPDX-License-Identifier: LGPL-3.0-only */ package net.minecraftforge.modlauncher.test; /** * Test core transformer functionality */ class ClassTransformerTests { @Test void testClassTransformer() throws Exception { MarkerManager.getMarker("CLASSDUMP"); Configurator.setLevel(ClassTransformer.class.getName(), Level.TRACE); UnsafeHacksUtil.hackPowermock(); final TransformStore transformStore = new TransformStore(); final ModuleLayerHandler layerHandler = Whitebox.invokeConstructor(ModuleLayerHandler.class); final LaunchPluginHandler lph = new LaunchPluginHandler(layerHandler); final ClassTransformer classTransformer = Whitebox.invokeConstructor(ClassTransformer.class, new Class[] { transformStore.getClass(), lph.getClass(), TransformingClassLoader.class }, new Object[] { transformStore, lph, null}); final ITransformationService dummyService = new MockTransformerService(); Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.MyClass", TransformTargetLabel.LabelType.CLASS), classTransformer(), dummyService); byte[] result = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class,String.class}, new byte[0], "test.MyClass","testing"); assertAll("Class loads and is valid", () -> assertNotNull(result), // () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.MyClass", result)), () -> { ClassReader cr = new ClassReader(result); ClassNode cn = new ClassNode(); cr.accept(cn, 0); assertTrue(cn.fields.stream().anyMatch(f -> f.name.equals("testfield"))); } ); ClassNode dummyClass = new ClassNode(); dummyClass.superName = "java/lang/Object"; dummyClass.version = 52; dummyClass.name = "test/DummyClass"; dummyClass.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "dummyfield", "Ljava/lang/String;", null, null)); ClassWriter cw = new ClassWriter(Opcodes.ASM5); dummyClass.accept(cw); Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.DummyClass", "dummyfield"), fieldNodeTransformer1(), dummyService); byte[] result1 = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class, String.class}, cw.toByteArray(), "test.DummyClass", "testing"); assertAll("Class loads and is valid", () -> assertNotNull(result1), // () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.DummyClass", result1)), () -> { ClassReader cr = new ClassReader(result1); ClassNode cn = new ClassNode(); cr.accept(cn, 0); assertEquals("CHEESE", cn.fields.get(0).value); } ); } private ITransformer<FieldNode> fieldNodeTransformer1() { return new ITransformer<>() { @NotNull @Override public FieldNode transform(FieldNode input, ITransformerVotingContext context) { input.value = "CHEESE"; return input; } @NotNull @Override
/* * Copyright (c) Forge Development LLC * SPDX-License-Identifier: LGPL-3.0-only */ package net.minecraftforge.modlauncher.test; /** * Test core transformer functionality */ class ClassTransformerTests { @Test void testClassTransformer() throws Exception { MarkerManager.getMarker("CLASSDUMP"); Configurator.setLevel(ClassTransformer.class.getName(), Level.TRACE); UnsafeHacksUtil.hackPowermock(); final TransformStore transformStore = new TransformStore(); final ModuleLayerHandler layerHandler = Whitebox.invokeConstructor(ModuleLayerHandler.class); final LaunchPluginHandler lph = new LaunchPluginHandler(layerHandler); final ClassTransformer classTransformer = Whitebox.invokeConstructor(ClassTransformer.class, new Class[] { transformStore.getClass(), lph.getClass(), TransformingClassLoader.class }, new Object[] { transformStore, lph, null}); final ITransformationService dummyService = new MockTransformerService(); Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.MyClass", TransformTargetLabel.LabelType.CLASS), classTransformer(), dummyService); byte[] result = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class,String.class}, new byte[0], "test.MyClass","testing"); assertAll("Class loads and is valid", () -> assertNotNull(result), // () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.MyClass", result)), () -> { ClassReader cr = new ClassReader(result); ClassNode cn = new ClassNode(); cr.accept(cn, 0); assertTrue(cn.fields.stream().anyMatch(f -> f.name.equals("testfield"))); } ); ClassNode dummyClass = new ClassNode(); dummyClass.superName = "java/lang/Object"; dummyClass.version = 52; dummyClass.name = "test/DummyClass"; dummyClass.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "dummyfield", "Ljava/lang/String;", null, null)); ClassWriter cw = new ClassWriter(Opcodes.ASM5); dummyClass.accept(cw); Whitebox.invokeMethod(transformStore, "addTransformer", new TransformTargetLabel("test.DummyClass", "dummyfield"), fieldNodeTransformer1(), dummyService); byte[] result1 = Whitebox.invokeMethod(classTransformer, "transform", new Class[]{byte[].class, String.class, String.class}, cw.toByteArray(), "test.DummyClass", "testing"); assertAll("Class loads and is valid", () -> assertNotNull(result1), // () -> assertNotNull(new TransformingClassLoader(transformStore, lph, FileSystems.getDefault().getPath(".")).getClass("test.DummyClass", result1)), () -> { ClassReader cr = new ClassReader(result1); ClassNode cn = new ClassNode(); cr.accept(cn, 0); assertEquals("CHEESE", cn.fields.get(0).value); } ); } private ITransformer<FieldNode> fieldNodeTransformer1() { return new ITransformer<>() { @NotNull @Override public FieldNode transform(FieldNode input, ITransformerVotingContext context) { input.value = "CHEESE"; return input; } @NotNull @Override
public TransformerVoteResult castVote(ITransformerVotingContext context) {
3
2023-10-18 17:56:01+00:00
8k
Kyrotechnic/KyroClient
Client/src/main/java/me/kyroclient/managers/WindowManager.java
[ { "identifier": "Module", "path": "Client/src/main/java/me/kyroclient/modules/Module.java", "snippet": "public class Module {\n @Expose\n @SerializedName(\"name\")\n public String name;\n @Expose\n @SerializedName(\"toggled\")\n private boolean toggled;\n @Expose\n @SerializedName(\"keyCode\")\n private int keycode;\n private final Category category;\n public boolean extended;\n @Expose\n @SerializedName(\"settings\")\n public ConfigManager.ConfigSetting[] cfgSettings;\n private boolean devOnly;\n public final MilliTimer toggledTime;\n public final List<Setting> settings;\n\n public Module(final String name, final int keycode, final Category category) {\n this.toggledTime = new MilliTimer();\n this.settings = new ArrayList<Setting>();\n this.name = name;\n this.keycode = keycode;\n this.category = category;\n }\n\n public Module(final String name, final Category category) {\n this(name, 0, category);\n }\n\n public boolean isToggled() {\n return this.toggled;\n }\n\n public void toggle() {\n this.setToggled(!this.toggled);\n }\n\n public void onEnable() {\n }\n public void assign()\n {\n\n }\n\n public void onSave() {\n }\n\n public String getSuffix()\n {\n return null;\n }\n\n public void addSetting(final Setting setting) {\n this.getSettings().add(setting);\n }\n\n public void addSettings(final Setting... settings) {\n for (final Setting setting : settings) {\n this.addSetting(setting);\n }\n }\n\n public Category getCategory() {\n return this.category;\n }\n\n public String getName() {\n return this.name;\n }\n\n public boolean isPressed() {\n return this.keycode != 0 && Keyboard.isKeyDown(this.keycode);\n }\n\n public int getKeycode() {\n return this.keycode;\n }\n\n public void setKeycode(final int keycode) {\n this.keycode = keycode;\n }\n\n public List<Setting> getSettings() {\n return this.settings;\n }\n\n public static List<Module> getModulesByCategory(final Category c) {\n return (List<Module>) KyroClient.moduleManager.getModules().stream().filter(module -> module.category == c).collect(Collectors.toList());\n }\n\n /*public static <T> T getModule(final Class<T> module) {\n for (final Module m : KyroClient.modules) {\n if (m.getClass().equals(module)) {\n return (T)m;\n }\n }\n return null;\n }\n\n public static Module getModule(final Predicate<Module> predicate) {\n for (final Module m : KyroClient.modules) {\n if (predicate.test(m)) {\n return m;\n }\n }\n return null;\n }\n\n public static Module getModule(final String string) {\n for (final Module m : KyroClient.modules) {\n if (m.getName().equalsIgnoreCase(string)) {\n return m;\n }\n }\n return null;\n }*/\n\n public void setToggled(final boolean toggled) {\n if (this.toggled != toggled) {\n this.toggled = toggled;\n this.toggledTime.reset();\n if (toggled) {\n this.onEnable();\n }\n else {\n this.onDisable();\n }\n }\n }\n\n public String suffix()\n {\n return \"\";\n }\n\n public void onDisable() {\n }\n\n public void setDevOnly(final boolean devOnly) {\n this.devOnly = devOnly;\n }\n\n public boolean isDevOnly() {\n return this.devOnly;\n }\n\n protected static void sendMessage(final String message) {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n\n public enum Category\n {\n CRIMSONISLE(\"Crimson Isle\"),\n GARDEN(\"Garden\"),\n RIFT(\"Rift\"),\n DUNGEONS(\"Dungeons\"),\n PLAYER(\"Player\"),\n RENDER(\"Render\"),\n COMBAT(\"Combat\"),\n MISC(\"Misc\"),\n DIANA(\"Diana\"),\n MINING(\"Mining\"),\n CLIENT(\"Client\");\n\n public String name;\n\n private Category(final String name) {\n this.name = name;\n }\n }\n}" }, { "identifier": "Window", "path": "Client/src/main/java/me/kyroclient/ui/modern/windows/Window.java", "snippet": "public abstract class Window {\n private final String name;\n public static final int LEFT_CLICK = 0;\n public static final int RIGHT_CLICK = 1;\n public static final int MIDDLE_CLICK = 2;\n\n public Window(String name) {\n this.name = name;\n }\n\n public abstract void initGui();\n\n public abstract void drawScreen(int var1, int var2, float var3);\n\n public abstract void mouseClicked(int var1, int var2, int var3);\n\n public abstract void mouseReleased(int var1, int var2, int var3);\n\n public abstract void keyTyped(char var1, int var2);\n\n public String getName() {\n return this.name;\n }\n\n public boolean isHovered(int mouseX, int mouseY, double x, double y, double width, double height) {\n return (double)mouseX > x && (double)mouseX < x + width && (double)mouseY > y && (double)mouseY < y + height;\n }\n}" }, { "identifier": "HomeWindow", "path": "Client/src/main/java/me/kyroclient/ui/modern/windows/impl/HomeWindow.java", "snippet": "public class HomeWindow extends Window {\n public static AnimationUtils scroll = new AnimationUtils(0.0);\n public int scrollY;\n public HomeWindow() {\n super(\"Home\");\n }\n\n @Override\n public void initGui() {\n }\n\n @Override\n public void drawScreen(int mouseX, int mouseY, float partialTicks) {\n int yOffset = (int) (50 + scroll.getValue());\n for (String str : KyroClient.changelog) {\n Fonts.getPrimary().drawString(str, ModernClickGui.getX() + 100.0, ModernClickGui.getY() + (double)yOffset, Color.WHITE.getRGB());\n yOffset += 12;\n }\n\n MouseUtils.Scroll scrol = MouseUtils.scroll();\n\n if (scrol != null)\n {\n switch (scrol)\n {\n case DOWN:\n if ((scrollY > (ModernClickGui.getHeight() - 25) - getHeight()))\n {\n scrollY -= 10;\n }\n break;\n case UP:\n scrollY += 10;\n if (scrollY >= 0)\n {\n scrollY = 0;\n }\n\n if (getHeight() < (ModernClickGui.getHeight() - 25))\n scrollY = 0;\n }\n }\n\n scroll.setAnimation(scrollY, 12);\n }\n\n public int getHeight()\n {\n return 12 * KyroClient.changelog.size();\n }\n\n @Override\n public void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n }\n\n @Override\n public void mouseReleased(int mouseX, int mouseY, int mouseButton) {\n }\n\n @Override\n public void keyTyped(char typedChar, int keyCode) {\n }\n}" }, { "identifier": "ModuleWindow", "path": "Client/src/main/java/me/kyroclient/ui/modern/windows/impl/ModuleWindow.java", "snippet": "public class ModuleWindow extends Window {\n public AnimationUtils scrollAnimation = new AnimationUtils(0.0);\n public static double scrollY;\n public static double scrollYsettings;\n public List<Module> modulesInCategory;\n public static Module selectedModule;\n public static StringSetting selectedString = null;\n public static NumberSetting selectedNumber = null;\n public static Module changeBind = null;\n public static AnimationUtils settingsAnimation = new AnimationUtils(0.0);\n\n public ModuleWindow(Module.Category moduleCategory) {\n super(moduleCategory.name);\n this.modulesInCategory = Module.getModulesByCategory(moduleCategory).stream().sorted(Comparator.comparingDouble(c -> Fonts.getPrimary().getStringWidth(c.getName()))).collect(Collectors.toList());\n Collections.reverse(this.modulesInCategory);\n }\n\n @Override\n public void initGui() {\n }\n\n @Override\n public void drawScreen(int mouseX, int mouseY, float partialTicks) {\n MouseUtils.Scroll scroll;\n int offset = 30;\n if (!ModernClickGui.settingsOpened) {\n for (Module module : this.modulesInCategory) {\n RenderUtils.drawBorderedRoundedRect((float)(ModernClickGui.getX() + 95.0), (float)(ModernClickGui.getY() + (double)offset + this.scrollAnimation.getValue()), ModernClickGui.getWidth() - 100.0f, 20.0f, 3.0f, 1.0f, module.isToggled() ? KyroClient.themeManager.getSecondaryColor().getRGB() : KyroClient.themeManager.getPrimaryColor().getRGB(), KyroClient.themeManager.getSecondaryColor().getRGB());\n Fonts.getPrimary().drawString(module.getName(), ModernClickGui.getX() + 105.0, ModernClickGui.getY() + (double)offset + this.scrollAnimation.getValue() + 6.0, Color.WHITE.getRGB());\n if (!module.getSettings().isEmpty()) {\n Fonts.icon.drawString(\"C\", ModernClickGui.getX() + (double)ModernClickGui.getWidth() - 21.0, ModernClickGui.getY() + (double)offset + this.scrollAnimation.getValue() + 8.0, Color.WHITE.getRGB());\n }\n if (changeBind == module)\n {\n Fonts.getPrimary().drawString(\"[...]\", ModernClickGui.getX() + (double)ModernClickGui.getWidth() - 35, ModernClickGui.getY() + (double)offset + this.scrollAnimation.getValue() + 7.0, Color.WHITE.getRGB());\n }\n else if (module.getKeycode() != 0)\n {\n String keyname = \"[\" + ((module.getKeycode() >= 256) ? \" \" : Keyboard.getKeyName(module.getKeycode()).replaceAll(\"NONE\", \" \")) + \"]\";\n int length = (int) Fonts.getPrimary().getStringWidth(keyname) - 5;\n Fonts.getPrimary().drawString(keyname, ModernClickGui.getX() + (double)ModernClickGui.getWidth() - 25 - length, ModernClickGui.getY() + (double)offset + this.scrollAnimation.getValue() + 7.0, Color.WHITE.getRGB());\n }\n offset += 25;\n }\n } else if (selectedModule != null) {\n Fonts.getPrimary().drawString(selectedModule.getName(), ModernClickGui.getX() + 95.0, 30.0, Color.WHITE.getRGB());\n\n for (Comp comp : updateComps(selectedModule.getSettings())) {\n comp.drawScreen(mouseX, mouseY, partialTicks);\n }\n }\n scroll = MouseUtils.scroll();\n if (scroll != null && !ModernClickGui.settingsOpened) {\n switch (scroll) {\n case DOWN: {\n if (!(scrollY > (double)(-(this.modulesInCategory.size() - 8) * 25))) break;\n scrollY -= 25.0;\n break;\n }\n case UP: {\n if (scrollY < -10.0) {\n scrollY += 25.0;\n break;\n }\n if (this.modulesInCategory.size() <= 8) break;\n scrollY = 0.0;\n }\n }\n }\n else if (scroll != null && ModernClickGui.settingsOpened)\n {\n switch (scroll)\n {\n case DOWN: {\n if ((scrollYsettings > (ModernClickGui.getHeight() - 25.0f) - settingsHeight))\n scrollYsettings -= 10;\n break;\n }\n case UP: {\n scrollYsettings += 10;\n if (scrollYsettings >= 0)\n {\n scrollYsettings = 0;\n }\n if (settingsHeight < (ModernClickGui.getHeight() - 25))\n scrollYsettings = 0.0;\n }\n }\n }\n this.scrollAnimation.setAnimation(scrollY, 16.0);\n settingsAnimation.setAnimation(scrollYsettings, 16);\n StencilUtils.disableStencilBuffer();\n }\n\n public static List<Comp> updateComps(List<Setting> settings) {\n List<Comp> comps = new ArrayList<>();\n int settingOffset = 30 + (int) settingsAnimation.getValue();\n boolean lastBool = false;\n for (Setting s : settings) {\n if (s.isHidden()) continue;\n if (!(s instanceof BooleanSetting) && lastBool) {\n lastBool = false;\n settingOffset += 15;\n }\n if (s instanceof BooleanSetting && !lastBool) {\n comps.add(new CompBoolSetting(95.0, settingOffset, (BooleanSetting)s));\n lastBool = true;\n continue;\n }\n else if (s instanceof BooleanSetting && lastBool)\n {\n comps.add(new CompBoolSetting(95.0f + (ModernClickGui.getWidth() - 95.0f) / 2.0f, settingOffset, (BooleanSetting)s));\n settingOffset += 15;\n lastBool = false;\n }\n else if (s instanceof ModeSetting)\n {\n comps.add(new CompModeSetting(95, settingOffset, (ModeSetting) s));\n settingOffset += 20;\n }\n else if (s instanceof StringSetting)\n {\n comps.add(new CompStringSetting(95, settingOffset, (StringSetting) s));\n settingOffset += 20;\n }\n else if (s instanceof RunnableSetting)\n {\n comps.add(new CompRunnableSetting(95, settingOffset, (RunnableSetting) s));\n settingOffset += 20;\n }\n else if (s instanceof NumberSetting)\n {\n comps.add(new CompSliderSetting(95, settingOffset, (NumberSetting) s));\n settingOffset += 25;\n }\n\n }\n settingsHeight = settingOffset - (int) (settingsAnimation.getValue());\n return comps;\n }\n\n public static int settingsHeight;\n public void close()\n {\n selectedModule = null;\n settingsHeight = 0;\n scrollYsettings = 0;\n settingsAnimation.setAnimation(0, 0);\n ModernClickGui.settingsOpened = false;\n selectedString = null;\n selectedNumber = null;\n changeBind = null;\n KyroClient.configManager.saveConfig();\n }\n\n @Override\n public void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n int offset = 30;\n if (selectedModule == null) {\n for (Module module : this.modulesInCategory) {\n if (this.isHovered(mouseX, mouseY, ModernClickGui.getX() + 95.0, ModernClickGui.getY() + (double) offset + this.scrollAnimation.getValue(), ModernClickGui.getWidth() - 100.0f, 20.0)) {\n switch (mouseButton) {\n case 0: {\n if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT))\n {\n changeBind = module;\n return;\n }\n module.toggle();\n break;\n }\n case 1: {\n if (module.getSettings().isEmpty()) {\n return;\n }\n close();\n selectedModule = module;\n ModernClickGui.settingsOpened = true;\n break;\n }\n case 2: {\n changeBind = module;\n break;\n }\n }\n }\n offset += 25;\n }\n }\n else\n {\n for (Comp comp : updateComps(selectedModule.getSettings()))\n {\n if (CompStringSetting.in)\n {\n CompStringSetting.in = false;\n break;\n }\n comp.mouseClicked(mouseX, mouseY, mouseButton);\n }\n }\n\n changeBind = null;\n }\n\n @Override\n public void mouseReleased(int mouseX, int mouseY, int mouseButton) {\n KyroClient.configManager.saveConfig();\n if (selectedModule == null) return;\n\n for (Comp comp : updateComps(selectedModule.getSettings()))\n {\n comp.mouseReleased(mouseX, mouseY, mouseButton);\n }\n\n if (selectedNumber != null)\n {\n selectedNumber = null;\n }\n }\n\n @Override\n public void keyTyped(char typedChar, int keyCode) {\n if (keyCode == KyroClient.clickGui.getKeycode())\n {\n if (changeBind != null)\n {\n changeBind.setKeycode(0);\n changeBind = null;\n }\n }\n else if (keyCode == Keyboard.KEY_LSHIFT)\n {\n if (changeBind != null) return;\n }\n\n if (changeBind != null && keyCode != 1)\n {\n changeBind.setKeycode(keyCode);\n changeBind = null;\n }\n if (selectedModule == null) return;\n if (selectedString == null) return;\n\n else if (selectedString != null) {\n if (keyCode == 28) {\n selectedString = null;\n }\n else if (keyCode == 47 && (Keyboard.isKeyDown(157) || Keyboard.isKeyDown(29))) {\n selectedString.setValue(this.selectedString.getValue() + getClipboardString());\n }\n else if (keyCode != 14) {\n selectedString.setValue(ChatAllowedCharacters.filterAllowedCharacters(this.selectedString.getValue() + typedChar));\n }\n else {\n selectedString.setValue(this.selectedString.getValue().substring(0, Math.max(0, this.selectedString.getValue().length() - 1)));\n }\n }\n\n KyroClient.configManager.saveConfig();\n }\n\n static {\n selectedModule = null;\n }\n}" }, { "identifier": "ThemeWindow", "path": "Client/src/main/java/me/kyroclient/ui/modern/windows/impl/ThemeWindow.java", "snippet": "public class ThemeWindow\n extends Window {\n public ThemeWindow() {\n super(\"Themes\");\n }\n\n @Override\n public void initGui() {\n }\n\n @Override\n public void drawScreen(int mouseX, int mouseY, float partialTicks) {\n CompModeSetting modeSetting = new CompModeSetting(95, 30, KyroClient.clickGui.colorMode);\n modeSetting.drawScreen(mouseX, mouseY, partialTicks);\n }\n\n @Override\n public void mouseClicked(int mouseX, int mouseY, int mouseButton) {\n CompModeSetting modeSetting = new CompModeSetting(95, 30, KyroClient.clickGui.colorMode);\n modeSetting.mouseClicked(mouseX, mouseY, mouseButton);\n\n KyroClient.themeManager.setTheme(KyroClient.clickGui.colorMode.getSelected());\n KyroClient.configManager.saveConfig();\n }\n\n @Override\n public void mouseReleased(int mouseX, int mouseY, int mouseButton) {\n }\n\n @Override\n public void keyTyped(char typedChar, int keyCode) {\n }\n}" } ]
import java.util.ArrayList; import java.util.List; import me.kyroclient.modules.Module; import me.kyroclient.ui.modern.windows.Window; import me.kyroclient.ui.modern.windows.impl.HomeWindow; import me.kyroclient.ui.modern.windows.impl.ModuleWindow; import me.kyroclient.ui.modern.windows.impl.ThemeWindow;
4,719
package me.kyroclient.managers; public class WindowManager { public List<Window> windows = new ArrayList<Window>(); public WindowManager() {
package me.kyroclient.managers; public class WindowManager { public List<Window> windows = new ArrayList<Window>(); public WindowManager() {
this.windows.add(new HomeWindow());
2
2023-10-15 16:24:51+00:00
8k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/missions/quests/AutoQuestTest.java
[ { "identifier": "MissionManager", "path": "source/core/src/main/com/csse3200/game/missions/MissionManager.java", "snippet": "public class MissionManager implements Json.Serializable {\n\n\t/**\n\t * An enum storing all possible events that the {@link MissionManager}'s {@link EventHandler} should listen to and\n\t * trigger. To add a listener to the {@link MissionManager}, create a new {@link MissionEvent} enum value, and add\n\t * a listener for the {@link #name()} of the enum value.\n\t */\n\tpublic enum MissionEvent {\n\t\t// Triggers when a mission is completed, a single String representing name of completed mission is provided as\n\t\t// an argument\n\t\tMISSION_COMPLETE,\n\t\t// Triggers when a new quest has been added to the mission manager\n\t\tNEW_QUEST,\n\t\t// Triggers when a quest expires\n\t\tQUEST_EXPIRED,\n\t\t// Triggers when a story quest's reward is collected (to ensure that the player has read the required dialogue),\n\t\t// a single String representing the name of the quest whose reward has been collected is provided as an argument\n\t\tQUEST_REWARD_COLLECTED,\n\t\t// Triggers when a crop is planted, a single String representing plant name is provided as an argument\n\t\tPLANT_CROP,\n\t\t// Triggers when a crop is fertilised\n\t\tFERTILISE_CROP,\n\t\t// Triggers when ship debris is cleared\n\t\tDEBRIS_CLEARED,\n\t\t// Triggers when a crop is harvested, a single String representing the plant name is provided as an argument\n\t\tHARVEST_CROP,\n\t\t// Triggers on successful water use\n\t\tWATER_CROP,\n\t\t// Triggers when an animal is tamed\n\t\tANIMAL_TAMED,\n\t\t// Triggers when a reward is collected used for MissionCompleteQuests\n\t\tREWARD_COMPLETE,\n\t\t// Triggers when a CombatStatsController is defeated by having it's health reduced to 0, a EntityType enum value\n\t\t// is provided representing the type of entity defeated is provided as an argument\n\t\tCOMBAT_ACTOR_DEFEATED,\n\t\t// Triggers when an animal is eaten by a Space Snapper, a EntityType enum value is provided representing the\n\t\t// type of entity eaten is provided as an argument\n\t\tANIMAL_EATEN,\n\t\t// Triggers when a ship part is added to the Ship\n\t\tSHIP_PART_ADDED,\n\t\t//Triggers when an item is collected\n\t\tITEMS_COLLECTED,\n\t\t// Triggers when a fish is caught (includes any item from fishing)\n\t\tFISH,\n\t}\n\n\t/**\n\t * The {@link MissionManager}'s {@link EventHandler}. {@link Mission}s should add listeners to\n\t * this {@link EventHandler} to update their state, when said events are triggered by in-game\n\t * interactions\n\t */\n\tprivate final EventHandler events = new EventHandler();\n\n\t/**\n\t * A {@link List} of {@link Quest}s which are currently active\n\t */\n\tprivate final List<Quest> activeQuests = new ArrayList<>();\n\n\t/**\n\t * A {@link List} of {@link Quest}s which the player may choose to accept by interacting with\n\t * the missions NPC in-game\n\t */\n\tprivate final List<Quest> selectableQuests = new ArrayList<>();\n\n\t/**\n\t * An array of all in-game {@link Achievement}s\n\t */\n\tprivate static final Achievement[] achievements = new Achievement[]{\n\t\t\tnew PlantCropsAchievement(\"Plant President\", 50),\n\t\t\tnew PlantCropsAchievement(\"Crop Enjoyer\", 200),\n\t\t\tnew PlantCropsAchievement(\"Gardener of the Galaxy\", 800),\n\t\t\tnew CollectItemsAchievement(\"Collector\", 10),\n\t\t\tnew CollectItemsAchievement(\"Item Hoarder\", 20),\n\t\t\tnew CollectItemsAchievement(\"Average Tristan\", 50)\n\t};\n\n\t/**\n\t * Creates the mission manager, registered all game achievements and adds a listener for hourly updates\n\t */\n\tpublic MissionManager() {\n\t\tServiceLocator.getTimeService().getEvents().addListener(\"hourUpdate\", this::updateActiveQuestTimes);\n\t\tfor (Achievement mission : achievements) {\n\t\t\tmission.registerMission(events);\n\t\t}\n\t}\n\n\t/**\n\t * Accepts a quest by adding it to the list of active quests in the game. Also registers this quest in the game.\n\t * If this {@link Quest} is in the {@link List} of selectable {@link Quest}s, then this method will also remove the\n\t * {@link Quest} from the {@link List} of selectable {@link Quest}s.\n\t *\n\t * @param quest The {@link Quest} to be added and registered\n\t */\n\tpublic void acceptQuest(Quest quest) {\n\t\t// Remove the quest from selectable quests if present\n\t\tselectableQuests.remove(quest);\n\t\tactiveQuests.add(quest);\n\t\tquest.registerMission(events);\n\t}\n\n\t/**\n\t * Returns a {@link List} of currently active (tracked) {@link Quest}s. This includes all {@link Quest}s which have not\n\t * expired (that is, they have been accepted, and they have been completed or not yet expired).\n\t *\n\t * @return The {@link List} of active {@link Quest}s.\n\t */\n\tpublic List<Quest> getActiveQuests() {\n\t\treturn activeQuests;\n\t}\n\n\t/**\n\t * Adds a {@link Quest} to the {@link List} of selectable {@link Quest}s. Selectable {@link Quest}s can be accepted\n\t * by the player through the in-game quest NPC.\n\t *\n\t * @param quest The {@link Quest} to add (this {@link Quest} should not have already been registered).\n\t */\n\tpublic void addQuest(Quest quest) {\n\t\tselectableQuests.add(quest);\n\t\tevents.trigger(MissionEvent.NEW_QUEST.name());\n\t}\n\n\t/**\n\t * Returns a {@link List} of selectable {@link Quest}s. These {@link Quest}s can be accepted in-game through\n\t * interaction with the quest NPC.\n\t *\n\t * @return The list of selectable {@link Quest}s.\n\t */\n\tpublic List<Quest> getSelectableQuests() {\n\t\treturn selectableQuests;\n\t}\n\n\t/**\n\t * Returns all in-game {@link Achievement}s.\n\t *\n\t * @return All in-game {@link Achievement}s.\n\t */\n\tpublic Achievement[] getAchievements() {\n\t\treturn achievements;\n\t}\n\n\t/**\n\t * Returns the {@link MissionManager}'s {@link EventHandler}, which is responsible for triggering events which\n\t * update the state of {@link Mission}s\n\t *\n\t * @return The {@link EventHandler} of the {@link MissionManager}, from which events can be triggered to update the\n\t * state of relevant {@link Mission}s.\n\t */\n\tpublic EventHandler getEvents() {\n\t\treturn events;\n\t}\n\n\t/**\n\t * Updates all active {@link Quest}s' durations through their {@link Quest#updateExpiry()} method.\n\t */\n\tprivate void updateActiveQuestTimes() {\n\t\tfor (Quest quest : activeQuests) {\n\t\t\tquest.updateExpiry();\n\t\t\tif (quest.isExpired()) {\n\t\t\t\tevents.trigger(MissionEvent.QUEST_EXPIRED.name());\n\t\t\t\tif (quest.isMandatory()) {\n\t\t\t\t\tevents.trigger(\"loseScreen\", quest.getName());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Writes the {@link MissionManager} to a Json object for saving\n\t *\n\t * @param json Json object written to\n\t */\n\t@Override\n\tpublic void write(Json json) {\n\t\tjson.writeObjectStart(\"ActiveQuests\");\n\t\tfor (Quest q : activeQuests) {\n\t\t\tq.write(json);\n\t\t}\n\t\tjson.writeObjectEnd();\n\t\tjson.writeObjectStart(\"SelectableQuests\");\n\t\tfor (Quest q : selectableQuests) {\n\t\t\tq.write(json);\n\t\t}\n\t\tjson.writeObjectEnd();\n\t\tjson.writeObjectStart(\"Achievements\");\n\t\tint i = 0;\n\t\tfor (Achievement achievement : achievements) {\n\t\t\tachievement.write(json, i);\n\t\t\ti++;\n\t\t}\n\t\tjson.writeObjectEnd();\n\t}\n\n\tpublic void readReal(Json json, JsonValue jsonMap) {\n\t\tJsonValue active = jsonMap.get(\"ActiveQuests\");\n\t\tactiveQuests.clear();\n\t\tif (active.has(\"Quest\")) {\n\t\t\tactive.forEach(jsonValue -> {\n\t\t\t\tQuest q = FactoryService.getQuests().get(jsonValue.getString(\"name\")).get();\n\t\t\t\tq.read(jsonValue);\n\t\t\t\tacceptQuest(q);\n\t\t\t});\n\t\t}\n\t\tJsonValue selectable = jsonMap.get(\"SelectableQuests\");\n\t\tselectableQuests.clear();\n\t\tif (selectable.has(\"Quest\")) {\n\t\t\tselectable.forEach(jsonValue -> {\n\t\t\t\tQuest q = FactoryService.getQuests().get(jsonValue.getString(\"name\")).get();\n\t\t\t\tq.read(jsonValue);\n\t\t\t\taddQuest(q);\n\t\t\t});\n\t\t}\n\t\tif (selectable.has(\"Achievement\")) {\n\t\t\tselectable.forEach(jsonValue -> {\n\t\t\t\tAchievement a = achievements[jsonValue.getInt(\"index\")];\n\t\t\t\ta.readProgress(jsonValue.get(\"progress\"));\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Method for loading the {@link MissionManager} for the game\n\t *\n\t * @param json\n\t * @param jsonMap\n\t */\n\t@Override\n\tpublic void read(Json json, JsonValue jsonMap) {\n\t\tServiceLocator.getMissionManager().readReal(json, jsonMap);\n\t}\n}" }, { "identifier": "Reward", "path": "source/core/src/main/com/csse3200/game/missions/rewards/Reward.java", "snippet": "public abstract class Reward {\n\n\tprivate boolean isCollected;\n\n\tprotected Reward() {\n\t\tisCollected = false;\n\t}\n\n\tpublic boolean isCollected() {\n\t\treturn isCollected;\n\t}\n\n\tpublic void setCollected() {\n\t\tisCollected = true;\n\t}\n\n\tpublic abstract void collect();\n\n\tpublic void read(JsonValue jsonValue) {\n\t\tisCollected = jsonValue.getBoolean(\"collected\");\n\t}\n}" }, { "identifier": "GameTime", "path": "source/core/src/main/com/csse3200/game/services/GameTime.java", "snippet": "public class GameTime {\n\tprivate static Logger logger = LoggerFactory.getLogger(GameTime.class);\n\tprivate final long startTime;\n\tprivate float timeScale = 1f;\n\n\tpublic GameTime() {\n\t\tstartTime = TimeUtils.millis();\n\t\tlogger.debug(\"Setting game start time to {}\", startTime);\n\t}\n\n\t/**\n\t * Set the speed of time passing. This affects getDeltaTime()\n\t *\n\t * @param timeScale Time scale, where normal speed is 1.0, no time passing is 0.0\n\t */\n\tpublic void setTimeScale(float timeScale) {\n\t\tlogger.debug(\"Setting time scale to {}\", timeScale);\n\t\tthis.timeScale = timeScale;\n\t}\n\n\t/**\n\t * @return time passed since the last frame in seconds, scaled by time scale.\n\t */\n\tpublic float getDeltaTime() {\n\t\treturn Gdx.graphics.getDeltaTime() * timeScale;\n\t}\n\n\t/**\n\t * @return time passed since the last frame in seconds, not affected by time scale.\n\t */\n\tpublic float getRawDeltaTime() {\n\t\treturn Gdx.graphics.getDeltaTime();\n\t}\n\n\t/**\n\t * @return time passed since the game started in milliseconds\n\t */\n\tpublic long getTime() {\n\t\treturn TimeUtils.timeSinceMillis(startTime);\n\t}\n\n\tpublic long getTimeSince(long lastTime) {\n\t\treturn getTime() - lastTime;\n\t}\n}" }, { "identifier": "ServiceLocator", "path": "source/core/src/main/com/csse3200/game/services/ServiceLocator.java", "snippet": "public class ServiceLocator {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ServiceLocator.class);\n\tprivate static EntityService entityService;\n\tprivate static RenderService renderService;\n\tprivate static PhysicsService physicsService;\n\tprivate static InputService inputService;\n\tprivate static ResourceService resourceService;\n\tprivate static TimeService timeService;\n\tprivate static GameTime timeSource;\n\tprivate static GameArea gameArea;\n\tprivate static LightService lightService;\n\tprivate static GameAreaDisplay pauseMenuArea;\n\tprivate static GameAreaDisplay craftArea;\n\tprivate static GdxGame game;\n\tprivate static InventoryDisplayManager inventoryDisplayManager;\n\tprivate static CameraComponent cameraComponent;\n\tprivate static SaveLoadService saveLoadService;\n\tprivate static MissionManager missions;\n\tprivate static PlanetOxygenService planetOxygenService;\n\tprivate static SoundService soundService;\n\tprivate static UIService uiService;\n\n\tprivate static PlantCommandService plantCommandService;\n\tprivate static PlayerHungerService playerHungerService;\n\n\tprivate static PlayerMapService playerMapService;\n\n\tprivate static PlantInfoService plantInfoService;\n\tprivate static boolean cutSceneRunning; // true for running and false otherwise\n\n\tprivate static ParticleService particleService;\n\n\tpublic static PlantCommandService getPlantCommandService() {\n\t\treturn plantCommandService;\n\t}\n\n\tpublic static PlantInfoService getPlantInfoService() {\n\t\treturn plantInfoService;\n\t}\n\n\tpublic static boolean god = false;\n\n\tpublic static GameArea getGameArea() {\n\t\treturn gameArea;\n\t}\n\n\tpublic static CameraComponent getCameraComponent() {\n\t\treturn cameraComponent;\n\t}\n\n\tpublic static EntityService getEntityService() {\n\t\treturn entityService;\n\t}\n\n\tpublic static RenderService getRenderService() {\n\t\treturn renderService;\n\t}\n\n\tpublic static PhysicsService getPhysicsService() {\n\t\treturn physicsService;\n\t}\n\n\tpublic static InputService getInputService() {\n\t\treturn inputService;\n\t}\n\n\tpublic static ResourceService getResourceService() {\n\t\treturn resourceService;\n\t}\n\n\tpublic static GameTime getTimeSource() {\n\t\treturn timeSource;\n\t}\n\n\tpublic static TimeService getTimeService() {\n\t\treturn timeService;\n\t}\n\n\tpublic static LightService getLightService() {\n\t\treturn lightService;\n\t}\n\n\tpublic static MissionManager getMissionManager() {\n\t\treturn missions;\n\t}\n\n\tpublic static PlanetOxygenService getPlanetOxygenService() {\n\t\treturn planetOxygenService;\n\t}\n\n\tpublic static PlayerHungerService getPlayerHungerService() {\n\t\treturn playerHungerService;\n\t}\n\n\tpublic static PlayerMapService getPlayerMapService() {\n\t\treturn playerMapService;\n\t}\n\n\tpublic static SaveLoadService getSaveLoadService() {\n\t\treturn saveLoadService;\n\t}\n\n\tpublic static SoundService getSoundService() {\n\t\treturn soundService;\n\t}\n\n\tpublic static UIService getUIService() {\n\t\treturn uiService;\n\t}\n\n\tpublic static ParticleService getParticleService() {\n\t\treturn particleService;\n\t}\n\n\t/**\n\t * Sets the cutscene status to either running or not running.\n\t *\n\t * @param isRunning true if cutscene is running, false otherwise\n\t */\n\tpublic static void setCutSceneRunning(boolean isRunning) {\n\t\tcutSceneRunning = isRunning;\n\t}\n\n\t/**\n\t * Gets the cutscene status.\n\t *\n\t * @return true if cutscene is running, false otherwise\n\t */\n\tpublic static boolean getCutSceneStatus() {\n\t\treturn cutSceneRunning;\n\t}\n\n\tpublic static void registerGameArea(GameArea area) {\n\t\tlogger.debug(\"Registering game area {}\", area);\n\t\tgameArea = area;\n\t}\n\n\tpublic static void registerCameraComponent(CameraComponent camera) {\n\t\tlogger.debug(\"Registering game area {}\", camera);\n\t\tcameraComponent = camera;\n\t}\n\n\tpublic static void registerEntityService(EntityService service) {\n\t\tlogger.debug(\"Registering entity service {}\", service);\n\t\tentityService = service;\n\t}\n\n\tpublic static void registerRenderService(RenderService service) {\n\t\tlogger.debug(\"Registering render service {}\", service);\n\t\trenderService = service;\n\t}\n\n\tpublic static void registerPhysicsService(PhysicsService service) {\n\t\tlogger.debug(\"Registering physics service {}\", service);\n\t\tphysicsService = service;\n\t}\n\n\tpublic static void registerTimeService(TimeService service) {\n\t\tlogger.debug(\"Registering time service {}\", service);\n\t\ttimeService = service;\n\t}\n\n\tpublic static void registerInputService(InputService source) {\n\t\tlogger.debug(\"Registering input service {}\", source);\n\t\tinputService = source;\n\t}\n\n\tpublic static void registerResourceService(ResourceService source) {\n\t\tlogger.debug(\"Registering resource service {}\", source);\n\t\tresourceService = source;\n\t}\n\n\tpublic static void registerTimeSource(GameTime source) {\n\t\tlogger.debug(\"Registering time source {}\", source);\n\t\ttimeSource = source;\n\t}\n\n\tpublic static void registerMissionManager(MissionManager source) {\n\t\tlogger.debug(\"Registering mission manager {}\", source);\n\t\tmissions = source;\n\t}\n\n\tpublic static void registerUIService(UIService source) {\n\t\tlogger.debug(\"Registering UI service {}\", source);\n\t\tuiService = source;\n\t}\n\n\tpublic static void registerPlanetOxygenService(PlanetOxygenService source) {\n\t\tlogger.debug(\"Registering planet oxygen service {}\", source);\n\t\tplanetOxygenService = source;\n\t}\n\n\n\tpublic static void registerPlayerHungerService(PlayerHungerService source) {\n\t\tlogger.debug(\"Registering player hunger service {}\", source);\n\t\tplayerHungerService = source;\n\t}\n\n\tpublic static void registerPlayerMapService(PlayerMapService source) {\n\t\tlogger.debug(\"Registering player map service {}\", source);\n\t\tplayerMapService = source;\n\t}\n\n\tpublic static void registerPlantCommandService(PlantCommandService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantCommandService = source;\n\t}\n\n\tpublic static void registerPlantInfoService(PlantInfoService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantInfoService = source;\n\t}\n\n\tpublic static void registerLightService(LightService source) {\n\t\tlogger.debug(\"Registering light service {}\", source);\n\t\tlightService = source;\n\t}\n\n\tpublic static void registerInventoryDisplayManager(InventoryDisplayManager source) {\n\t\tlogger.debug(\"Registering inventory display manager {}\", source);\n\t\tinventoryDisplayManager = source;\n\t}\n\n\tpublic static void registerParticleService(ParticleService source) {\n\t\tparticleService = source;\n\t}\n\n\t/**\n\t * Registers the save/load service.\n\t *\n\t * @param source the service to register\n\t */\n\tpublic static void registerSaveLoadService(SaveLoadService source) {\n\t\tlogger.debug(\"Registering Save/Load service {}\", source);\n\t\tsaveLoadService = source;\n\t}\n\n\tpublic static void registerSoundService(SoundService source) {\n\t\tlogger.debug(\"Registering sound service {}\", source);\n\t\tsoundService = source;\n\t}\n\n\t/**\n\t * Clears all registered services.\n\t * Do not clear saveLoadService\n\t */\n\tpublic static void clear() {\n\t\tentityService = null;\n\t\trenderService = null;\n\t\tphysicsService = null;\n\t\ttimeSource = null;\n\t\tinputService = null;\n\t\tresourceService = null;\n\t\tgameArea = null;\n\t\tsoundService = null;\n\t\tlightService = null;\n\t\tparticleService = null;\n\t\ttimeService = null;\n\t\tuiService = null;\n\t}\n\n\tprivate ServiceLocator() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n\n\tpublic static void registerPauseArea(GameAreaDisplay area) {\n\t\tpauseMenuArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getPauseMenuArea() {\n\t\treturn pauseMenuArea;\n\t}\n\n\tpublic static InventoryDisplayManager getInventoryDisplayManager() {\n\t\treturn inventoryDisplayManager;\n\t}\n\n\tpublic static void registerCraftArea(GameAreaDisplay area) {\n\t\tcraftArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getCraftArea() {\n\t\treturn craftArea;\n\t}\n\n\tpublic static void registerGame(GdxGame gameVar) {\n\t\tgame = gameVar;\n\t}\n\n\tpublic static GdxGame getGame() {\n\t\treturn game;\n\t}\n\n\n}" }, { "identifier": "TimeService", "path": "source/core/src/main/com/csse3200/game/services/TimeService.java", "snippet": "public class TimeService {\n\tprivate static final Logger logger = LoggerFactory.getLogger(TimeService.class);\n\tprivate static final int MS_IN_MINUTE = 500;\n\tprivate static final int MORNING_HOUR = 6;\n\tprivate static final int NIGHT_HOUR = 20;\n\n\tprivate int minute;\n\tprivate int hour;\n\tprivate int day;\n\n\tprivate long timeBuffer;\n\tprivate boolean paused;\n\tprivate final EventHandler events;\n\n\tprivate static final String DAY_UPDATE = \"dayUpdate\";\n\n\tprivate static final String MINUTE_UPDATE = \"minuteUpdate\";\n\n\tprivate static final String HOUR_UPDATE = \"hourUpdate\";\n\n\n\t/**\n\t * Constructs a basic TimeService instance to track the in-game time\n\t */\n\tpublic TimeService() {\n\t\thour = MORNING_HOUR;\n\t\tday = 0;\n\t\tminute = 0;\n\t\tpaused = false;\n\t\tevents = new EventHandler();\n\t}\n\n\t/**\n\t * Returns whether the game is paused or not\n\t *\n\t * @return boolean value representing whether the game is paused or not\n\t */\n\tpublic boolean isPaused() {\n\t\treturn paused;\n\t}\n\n\t/**\n\t * Changes the pause state of the game\n\t *\n\t * @param state boolean value for whether the game is paused or not\n\t */\n\tpublic void setPaused(boolean state) {\n\t\tpaused = state;\n\t\tlogger.debug(\"Setting paused state to: {}\", paused);\n\t\tServiceLocator.getTimeSource().setTimeScale(state ? 0 : 1);\n\t}\n\n\t/**\n\t * Gets the current in-game hour\n\t *\n\t * @return in-game hour\n\t */\n\tpublic int getHour() {\n\t\treturn hour;\n\t}\n\n\t/**\n\t * Gets the current in-game day\n\t *\n\t * @return in-game day\n\t */\n\tpublic int getDay() {\n\t\treturn day;\n\t}\n\n\t/**\n\t * Gets the current in-game minute\n\t *\n\t * @return in-game minute\n\t */\n\tpublic int getMinute() {\n\t\treturn minute;\n\t}\n\n\t/**\n\t * Determines whether it is day or not\n\t *\n\t * @return whether it is day or not\n\t */\n\tpublic boolean isDay() {\n\t\treturn (hour >= MORNING_HOUR) && (hour < NIGHT_HOUR);\n\t}\n\n\t/**\n\t * Determines whether it is night or not\n\t *\n\t * @return whether it is night or not\n\t */\n\tpublic boolean isNight() {\n\t\treturn !isDay();\n\t}\n\n\t/**\n\t * Sets the in-game day to a certain value. Also updates the time buffer and triggers any necessary events\n\t *\n\t * @param day in-game day\n\t */\n\tpublic void setDay(int day) {\n\t\tif (day < 0) {\n\t\t\tlogger.warn(\"Incorrect day value given: {}\", day);\n\t\t\treturn;\n\t\t}\n\t\tlogger.debug(\"Day is being set to: {}\", this.day);\n\t\tthis.day = day;\n\t\tthis.timeBuffer = 0;\n\t\tevents.trigger(DAY_UPDATE);\n\t}\n\n\t/**\n\t * Sets the in-game hour to a certain value. Also updates the time buffer and triggers any necessary events\n\t *\n\t * @param hour in-game hour\n\t */\n\tpublic void setHour(int hour) {\n\t\tif (hour < 0 || hour > 23) {\n\t\t\tlogger.warn(\"Incorrect hour value given: {}\", hour);\n\t\t\treturn;\n\t\t}\n\t\tlogger.debug(\"Hour is being set to: {}\", this.hour);\n\t\tthis.hour = hour;\n\t\tthis.timeBuffer = 0;\n\t\tevents.trigger(HOUR_UPDATE);\n\t}\n\n\t/**\n\t * Sets the in-game minute to a certain value. Also updates the time buffer and triggers any necessary events\n\t *\n\t * @param minute in-game minute\n\t */\n\tpublic void setMinute(int minute) {\n\t\tif (minute < 0 || minute > 59) {\n\t\t\tlogger.warn(\"Incorrect minute value given: {}\", minute);\n\t\t\treturn;\n\t\t}\n\t\tlogger.debug(\"Minute is being set to: {}\", this.minute);\n\t\tthis.minute = minute;\n\t\tthis.timeBuffer = 0;\n\t\tevents.trigger(MINUTE_UPDATE);\n\t}\n\n\t/**\n\t * Sets the in-game hour to the nearest future hour passed in, rounded to 0 minutes.\n\t * Increments the day if necessary, updates the time buffer, and triggers any necessary events.\n\t *\n\t * @param hour in-game hour\n\t */\n\tpublic void setNearestTime(int hour) {\n\t\tsetNearestTime(hour, 0);\n\t}\n\n\t/**\n\t * Sets the in-game hour and minute to the nearest future value passed in.\n\t * Increments the day if necessary, updates the time buffer, and triggers any necessary events.\n\t *\n\t * @param hour in-game hour\n\t * @param minute in-game minute\n\t */\n\tpublic void setNearestTime(int hour, int minute) {\n\t\tif (this.minute > minute) {\n\t\t\tthis.hour += 1;\n\t\t}\n\t\tthis.minute = minute;\n\t\tevents.trigger(MINUTE_UPDATE);\n\n\t\tif (this.hour > hour) {\n\t\t\tthis.day += 1;\n\t\t\tevents.trigger(DAY_UPDATE);\n\t\t}\n\t\tthis.hour = hour;\n\t\tevents.trigger(HOUR_UPDATE);\n\n\t\tthis.timeBuffer = 0;\n\n\t\tlogger.debug(\"Time is being set to: {}d, {}h, {}m\", this.day, this.hour, this.minute);\n\t}\n\n\t/**\n\t * Gets the event handler for the TimeService\n\t *\n\t * @return event handler\n\t */\n\tpublic EventHandler getEvents() {\n\t\treturn events;\n\t}\n\n\t/**\n\t * Trigger relevant events once the hour has been updated.\n\t */\n\tprivate void triggerHourEvents() {\n\t\tif (hour == MORNING_HOUR) {\n\t\t\t// Made this an event so other entities can listen\n\t\t\tlogger.debug(\"Now night time\");\n\t\t\tevents.trigger(\"morningTime\");\n\t\t} else if (hour == NIGHT_HOUR) {\n\t\t\tlogger.debug(\"Now morning time\");\n\t\t\tevents.trigger(\"nightTime\");\n\t\t}\n\n\t\t// Always trigger an hour update event\n\t\tevents.trigger(HOUR_UPDATE);\n\t}\n\n\t/**\n\t * Tracks the in-game time stored in the time service. This method is called in the main game loop. It calculates\n\t * the time that has passed since it last checked the time and calculates whether in-game time has elapsed.\n\t */\n\tpublic void update() {\n\t\t// this time will be in ms\n\t\tfloat timePassed = ServiceLocator.getTimeSource().getDeltaTime() * 1000;\n\t\tif (paused) {\n\t\t\treturn;\n\t\t}\n\t\ttimeBuffer += (long) timePassed;\n\n\t\tif (timeBuffer < MS_IN_MINUTE) {\n\t\t\treturn;\n\t\t}\n\n\t\tint minutesPassed = (int) (timeBuffer / MS_IN_MINUTE);\n\t\tminute += minutesPassed;\n\t\ttimeBuffer -= ((long) minutesPassed * MS_IN_MINUTE);\n\n\t\t// If minute is between 0 and 59, hour hasn't elapsed - don't do anything\n\t\tif (minute < 60) {\n\t\t\tevents.trigger(MINUTE_UPDATE);\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"In-game hour has updated\");\n\n\t\tint hoursPassed = minute / 60;\n\t\thour += hoursPassed;\n\t\tminute -= (hoursPassed * 60);\n\t\tevents.trigger(MINUTE_UPDATE);\n\n\t\t// If hour is between 0 and 23, day hasn't elapsed, do nothing\n\t\tif (hour < 24) {\n\t\t\ttriggerHourEvents();\n\t\t\treturn;\n\t\t}\n\n\t\tlogger.debug(\"In-game day has updated\");\n\n\t\tint daysPassed = hour / 24;\n\t\tday += daysPassed;\n\t\thour -= (daysPassed * 24);\n\t\ttriggerHourEvents();\n\n\t\t// This event has to be triggered after the hour is checked the hour isn't 24 when the event is sent\n\t\tevents.trigger(DAY_UPDATE);\n\t}\n\n\tpublic void loadTime(int day, int hour, int minute) {\n\t\tsetDay(day);\n\t\tsetHour(hour);\n\t\tsetMinute(minute);\n\t}\n}" } ]
import com.badlogic.gdx.utils.JsonValue; 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.*;
7,110
package com.csse3200.game.missions.quests; class AutoQuestTest { private AutoQuest autoQuest1, autoQuest2, autoQuest3; private Reward r1, r2, r3; private boolean areQuestsRegistered = false; @BeforeEach public void init() { ServiceLocator.registerTimeSource(new GameTime());
package com.csse3200.game.missions.quests; class AutoQuestTest { private AutoQuest autoQuest1, autoQuest2, autoQuest3; private Reward r1, r2, r3; private boolean areQuestsRegistered = false; @BeforeEach public void init() { ServiceLocator.registerTimeSource(new GameTime());
ServiceLocator.registerTimeService(new TimeService());
4
2023-10-17 22:34:04+00:00
8k
moeinfatehi/PassiveDigger
src/PassiveDigger/Passive_Headers.java
[ { "identifier": "BurpExtender", "path": "src/burp/BurpExtender.java", "snippet": "public class BurpExtender extends JPanel implements IBurpExtender\r\n{\r\n \r\n public static IBurpExtenderCallbacks callbacks;\r\n static JScrollPane frame;\r\n public static PrintWriter output;\r\n public static String project_Name=\"PassiveDigger\";\r\n private static final String project_Version=\"2.0.0\";\r\n \r\n public BurpExtender() {\r\n// this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel();\r\n }\r\n \r\n @Override\r\n public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks)\r\n {\r\n // keep a reference to our callbacks object\r\n this.callbacks = callbacks;\r\n callbacks.registerHttpListener(new PassiveAnalyzer());\r\n output = new PrintWriter(callbacks.getStdout(), true);\r\n // create our UI\r\n SwingUtilities.invokeLater(new Runnable()\r\n {\r\n @Override\r\n public void run()\r\n {\r\n initComponents();\r\n // customize our UI components\r\n callbacks.customizeUiComponent(tab.panel);\r\n \r\n // add the custom tab to Burp's UI\r\n callbacks.addSuiteTab(tab.tb);\r\n callbacks.registerContextMenuFactory(new menuItem());\r\n \r\n }\r\n });\r\n }\r\n \r\n private void initComponents() {\r\n }// </editor-fold>\r\n \r\n public byte[] processProxyMessage(int messageReference, boolean messageIsRequest, String remoteHost, int remotePort, boolean serviceIsHttps, String httpMethod, String url,\r\n String resourceType, String statusCode, String responseContentType, byte message[], int action[])\r\n {\r\n return message;\r\n }\r\n \r\n public static String getProjectName(){\r\n return project_Name;\r\n }\r\n public static String getVersion(){\r\n return project_Version;\r\n }\r\n \r\n}" }, { "identifier": "IHttpRequestResponse", "path": "src/burp/IHttpRequestResponse.java", "snippet": "public interface IHttpRequestResponse\r\n{\r\n /**\r\n * This method is used to retrieve the request message.\r\n *\r\n * @return The request message.\r\n */\r\n byte[] getRequest();\r\n\r\n /**\r\n * This method is used to update the request message.\r\n *\r\n * @param message The new request message.\r\n */\r\n void setRequest(byte[] message);\r\n\r\n /**\r\n * This method is used to retrieve the response message.\r\n *\r\n * @return The response message.\r\n */\r\n byte[] getResponse();\r\n\r\n /**\r\n * This method is used to update the response message.\r\n *\r\n * @param message The new response message.\r\n */\r\n void setResponse(byte[] message);\r\n\r\n /**\r\n * This method is used to retrieve the user-annotated comment for this item,\r\n * if applicable.\r\n *\r\n * @return The user-annotated comment for this item, or null if none is set.\r\n */\r\n String getComment();\r\n\r\n /**\r\n * This method is used to update the user-annotated comment for this item.\r\n *\r\n * @param comment The comment to be assigned to this item.\r\n */\r\n void setComment(String comment);\r\n\r\n /**\r\n * This method is used to retrieve the user-annotated highlight for this\r\n * item, if applicable.\r\n *\r\n * @return The user-annotated highlight for this item, or null if none is\r\n * set.\r\n */\r\n String getHighlight();\r\n\r\n /**\r\n * This method is used to update the user-annotated highlight for this item.\r\n *\r\n * @param color The highlight color to be assigned to this item. Accepted\r\n * values are: red, orange, yellow, green, cyan, blue, pink, magenta, gray,\r\n * or a null String to clear any existing highlight.\r\n */\r\n void setHighlight(String color);\r\n\r\n /**\r\n * This method is used to retrieve the HTTP service for this request /\r\n * response.\r\n *\r\n * @return An\r\n * <code>IHttpService</code> object containing details of the HTTP service.\r\n */\r\n IHttpService getHttpService();\r\n\r\n /**\r\n * This method is used to update the HTTP service for this request /\r\n * response.\r\n *\r\n * @param httpService An\r\n * <code>IHttpService</code> object containing details of the new HTTP\r\n * service.\r\n */\r\n void setHttpService(IHttpService httpService);\r\n\r\n}\r" }, { "identifier": "IRequestInfo", "path": "src/burp/IRequestInfo.java", "snippet": "public interface IRequestInfo\r\n{\r\n /**\r\n * Used to indicate that there is no content.\r\n */\r\n static final byte CONTENT_TYPE_NONE = 0;\r\n /**\r\n * Used to indicate URL-encoded content.\r\n */\r\n static final byte CONTENT_TYPE_URL_ENCODED = 1;\r\n /**\r\n * Used to indicate multi-part content.\r\n */\r\n static final byte CONTENT_TYPE_MULTIPART = 2;\r\n /**\r\n * Used to indicate XML content.\r\n */\r\n static final byte CONTENT_TYPE_XML = 3;\r\n /**\r\n * Used to indicate JSON content.\r\n */\r\n static final byte CONTENT_TYPE_JSON = 4;\r\n /**\r\n * Used to indicate AMF content.\r\n */\r\n static final byte CONTENT_TYPE_AMF = 5;\r\n /**\r\n * Used to indicate unknown content.\r\n */\r\n static final byte CONTENT_TYPE_UNKNOWN = -1;\r\n\r\n /**\r\n * This method is used to obtain the HTTP method used in the request.\r\n *\r\n * @return The HTTP method used in the request.\r\n */\r\n String getMethod();\r\n\r\n /**\r\n * This method is used to obtain the URL in the request.\r\n *\r\n * @return The URL in the request.\r\n */\r\n URL getUrl();\r\n\r\n /**\r\n * This method is used to obtain the HTTP headers contained in the request.\r\n *\r\n * @return The HTTP headers contained in the request.\r\n */\r\n List<String> getHeaders();\r\n\r\n /**\r\n * This method is used to obtain the parameters contained in the request.\r\n *\r\n * @return The parameters contained in the request.\r\n */\r\n List<IParameter> getParameters();\r\n\r\n /**\r\n * This method is used to obtain the offset within the request where the\r\n * message body begins.\r\n *\r\n * @return The offset within the request where the message body begins.\r\n */\r\n int getBodyOffset();\r\n\r\n /**\r\n * This method is used to obtain the content type of the message body.\r\n *\r\n * @return An indication of the content type of the message body. Available\r\n * types are defined within this interface.\r\n */\r\n byte getContentType();\r\n}\r" }, { "identifier": "IResponseInfo", "path": "src/burp/IResponseInfo.java", "snippet": "public interface IResponseInfo\r\n{\r\n /**\r\n * This method is used to obtain the HTTP headers contained in the response.\r\n *\r\n * @return The HTTP headers contained in the response.\r\n */\r\n List<String> getHeaders();\r\n\r\n /**\r\n * This method is used to obtain the offset within the response where the\r\n * message body begins.\r\n *\r\n * @return The offset within the response where the message body begins.\r\n */\r\n int getBodyOffset();\r\n\r\n /**\r\n * This method is used to obtain the HTTP status code contained in the\r\n * response.\r\n *\r\n * @return The HTTP status code contained in the response.\r\n */\r\n short getStatusCode();\r\n\r\n /**\r\n * This method is used to obtain details of the HTTP cookies set in the\r\n * response.\r\n *\r\n * @return A list of <code>ICookie</code> objects representing the cookies\r\n * set in the response, if any.\r\n */\r\n List<ICookie> getCookies();\r\n\r\n /**\r\n * This method is used to obtain the MIME type of the response, as stated in\r\n * the HTTP headers.\r\n *\r\n * @return A textual label for the stated MIME type, or an empty String if\r\n * this is not known or recognized. The possible labels are the same as\r\n * those used in the main Burp UI.\r\n */\r\n String getStatedMimeType();\r\n\r\n /**\r\n * This method is used to obtain the MIME type of the response, as inferred\r\n * from the contents of the HTTP message body.\r\n *\r\n * @return A textual label for the inferred MIME type, or an empty String if\r\n * this is not known or recognized. The possible labels are the same as\r\n * those used in the main Burp UI.\r\n */\r\n String getInferredMimeType();\r\n}\r" } ]
import burp.BurpExtender; import burp.IHttpRequestResponse; import burp.IRequestInfo; import burp.IResponseInfo; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter;
4,751
} }); jScrollPane6.setViewportView(securityHeadersTable); if (securityHeadersTable.getColumnModel().getColumnCount() > 0) { securityHeadersTable.getColumnModel().getColumn(0).setPreferredWidth(150); securityHeadersTable.getColumnModel().getColumn(0).setMaxWidth(180); securityHeadersTable.getColumnModel().getColumn(1).setPreferredWidth(60); securityHeadersTable.getColumnModel().getColumn(1).setMaxWidth(80); securityHeadersTable.getColumnModel().getColumn(2).setPreferredWidth(200); } javax.swing.GroupLayout SecurityHeadersPanelLayout = new javax.swing.GroupLayout(SecurityHeadersPanel); SecurityHeadersPanel.setLayout(SecurityHeadersPanelLayout); SecurityHeadersPanelLayout.setHorizontalGroup( SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 265, Short.MAX_VALUE) .addComponent(updateSecurityHeadersButton)) .addComponent(jScrollPane4) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane6)) .addContainerGap()) ); SecurityHeadersPanelLayout.setVerticalGroup( SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(updateSecurityHeadersButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 179, Short.MAX_VALUE)) ); HeadersTabs.addTab("Security Headers", SecurityHeadersPanel); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HeadersTabs) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HeadersTabs) ); }// </editor-fold>//GEN-END:initComponents private void securityHeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_securityHeadersTableMouseClicked if(evt.getClickCount()==2){ int index=securityHeadersTable.getSelectedRow(); if(securityHeaderReqRespList[index]!=null){ reqRespForm.setReqResp(securityHeaderReqRespList[index]); reqRespForm jf=new reqRespForm(); jf.setLocationRelativeTo(null); jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); jf.tabs.setSelectedIndex(1); jf.setVisible(true); } } else{ setDescription(getDescription((String) securityHeadersTable.getValueAt(securityHeadersTable.getSelectedRow(), 0))); } }//GEN-LAST:event_securityHeadersTableMouseClicked private void updateSecurityHeadersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSecurityHeadersButtonActionPerformed for (int i = 0; i < securityHeadersTable.getRowCount(); i++) { if(!(boolean)securityHeadersTable.getValueAt(i, 1)){ for (int j = 0; j < HeadersTable.getRowCount(); j++) { if(HeadersTable.getValueAt(j, 1).equals(securityHeadersTable.getValueAt(i, 0))){ DefaultTableModel model=(DefaultTableModel)securityHeadersTable.getModel(); model.setValueAt(true, i, 1); model.setValueAt(HeadersTable.getValueAt(j, 2), i, 2); securityHeaderReqRespList[i]=headersReqRespList.get(j); break; } } } } }//GEN-LAST:event_updateSecurityHeadersButtonActionPerformed private void tableExceptionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tableExceptionButtonActionPerformed int[]rows=HeadersTable.getSelectedRows(); for(int i=rows.length-1;i>=0;i--){ String parameter=HeadersTable.getValueAt(rows[i], 3).toString(); addToExceptions(parameter); } removeExceptions(); }//GEN-LAST:event_tableExceptionButtonActionPerformed private void removeRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRowButtonActionPerformed int[]rows=HeadersTable.getSelectedRows(); for(int i=rows.length-1;i>=0;i--){ int thisInd=HeadersTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table removeHeadersTableRow(thisInd); } }//GEN-LAST:event_removeRowButtonActionPerformed private void exceptionRemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionRemoveButtonActionPerformed removeExceptions(); }//GEN-LAST:event_exceptionRemoveButtonActionPerformed private void exceptionFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_exceptionFieldActionPerformed private void HeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HeadersTableMouseClicked if(evt.getClickCount()==2){ int ind=HeadersTable.getSelectedRow(); int index=(int)HeadersTable.getValueAt(ind, 0)-1;
package PassiveDigger; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author "Moein Fatehi [email protected]" */ public class Passive_Headers extends javax.swing.JPanel { private static Scanner sc; private static List<IHttpRequestResponse> headersReqRespList=new ArrayList<>(); private static IHttpRequestResponse [] securityHeaderReqRespList= new IHttpRequestResponse [6]; /** * Creates new form HeadersPanel */ public Passive_Headers() { initComponents(); initialize(); } public static List<IHttpRequestResponse> getHeadersReqRespList(){ return headersReqRespList; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { HeadersTabs = new javax.swing.JTabbedPane(); HeadersPanel = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); HeadersTable = new javax.swing.JTable(); jLabel3 = new javax.swing.JLabel(); exceptionField = new javax.swing.JTextField(); exceptionRemoveButton = new javax.swing.JButton(); removeRowButton = new javax.swing.JButton(); tableExceptionButton = new javax.swing.JButton(); SecurityHeadersPanel = new javax.swing.JPanel(); jLabel6 = new javax.swing.JLabel(); updateSecurityHeadersButton = new javax.swing.JButton(); jScrollPane4 = new javax.swing.JScrollPane(); DescriptionField = new javax.swing.JTextArea(); jLabel7 = new javax.swing.JLabel(); jScrollPane6 = new javax.swing.JScrollPane(); securityHeadersTable = new javax.swing.JTable(); HeadersTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "Host", "Port", "Header", "Value" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, true, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); HeadersTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { HeadersTableMouseClicked(evt); } }); jScrollPane1.setViewportView(HeadersTable); if (HeadersTable.getColumnModel().getColumnCount() > 0) { HeadersTable.getColumnModel().getColumn(0).setPreferredWidth(45); HeadersTable.getColumnModel().getColumn(0).setMaxWidth(100); HeadersTable.getColumnModel().getColumn(1).setPreferredWidth(120); HeadersTable.getColumnModel().getColumn(1).setMaxWidth(200); HeadersTable.getColumnModel().getColumn(2).setPreferredWidth(60); HeadersTable.getColumnModel().getColumn(2).setMaxWidth(85); HeadersTable.getColumnModel().getColumn(3).setPreferredWidth(200); HeadersTable.getColumnModel().getColumn(3).setMaxWidth(300); } jLabel3.setText("Exceptions"); exceptionField.setText("Date,Content-Length,Set-Cookie,Content-Type,Connection,Last-Modified,CF-RAY,Expires,ETag,Location,Vary"); exceptionField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exceptionFieldActionPerformed(evt); } }); exceptionRemoveButton.setText("Remove"); exceptionRemoveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exceptionRemoveButtonActionPerformed(evt); } }); removeRowButton.setText("Remove"); removeRowButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeRowButtonActionPerformed(evt); } }); tableExceptionButton.setText("Exception"); tableExceptionButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tableExceptionButtonActionPerformed(evt); } }); javax.swing.GroupLayout HeadersPanelLayout = new javax.swing.GroupLayout(HeadersPanel); HeadersPanel.setLayout(HeadersPanelLayout); HeadersPanelLayout.setHorizontalGroup( HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HeadersPanelLayout.createSequentialGroup() .addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HeadersPanelLayout.createSequentialGroup() .addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(tableExceptionButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeRowButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addGroup(HeadersPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addGap(1, 1, 1) .addComponent(exceptionField, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(exceptionRemoveButton))) .addContainerGap()) ); HeadersPanelLayout.setVerticalGroup( HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HeadersPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(exceptionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(exceptionRemoveButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(HeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HeadersPanelLayout.createSequentialGroup() .addComponent(removeRowButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tableExceptionButton) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)) .addContainerGap()) ); HeadersTabs.addTab("Headers", HeadersPanel); jLabel6.setFont(new java.awt.Font("Ubuntu", 1, 12)); // NOI18N jLabel6.setForeground(new java.awt.Color(255, 150, 0)); jLabel6.setText("Security Headers"); updateSecurityHeadersButton.setText("Update From History"); updateSecurityHeadersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { updateSecurityHeadersButtonActionPerformed(evt); } }); DescriptionField.setColumns(20); DescriptionField.setRows(5); jScrollPane4.setViewportView(DescriptionField); jLabel7.setFont(new java.awt.Font("Ubuntu", 1, 12)); // NOI18N jLabel7.setForeground(new java.awt.Color(255, 150, 0)); jLabel7.setText("Description"); securityHeadersTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"X-XSS-Protection", null, null}, {"X-Frame-Options", null, null}, {"Content-Security-Policy", null, null}, {"X-Content-Type-Options", null, null}, {"Referrer-Policy", null, null}, {"Strict-Transport-Security", null, null} }, new String [] { "Header", "Status", "Value" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.Boolean.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); securityHeadersTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { securityHeadersTableMouseClicked(evt); } }); securityHeadersTable.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { securityHeadersTableKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { securityHeadersTableKeyReleased(evt); } }); jScrollPane6.setViewportView(securityHeadersTable); if (securityHeadersTable.getColumnModel().getColumnCount() > 0) { securityHeadersTable.getColumnModel().getColumn(0).setPreferredWidth(150); securityHeadersTable.getColumnModel().getColumn(0).setMaxWidth(180); securityHeadersTable.getColumnModel().getColumn(1).setPreferredWidth(60); securityHeadersTable.getColumnModel().getColumn(1).setMaxWidth(80); securityHeadersTable.getColumnModel().getColumn(2).setPreferredWidth(200); } javax.swing.GroupLayout SecurityHeadersPanelLayout = new javax.swing.GroupLayout(SecurityHeadersPanel); SecurityHeadersPanel.setLayout(SecurityHeadersPanelLayout); SecurityHeadersPanelLayout.setHorizontalGroup( SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 265, Short.MAX_VALUE) .addComponent(updateSecurityHeadersButton)) .addComponent(jScrollPane4) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane6)) .addContainerGap()) ); SecurityHeadersPanelLayout.setVerticalGroup( SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SecurityHeadersPanelLayout.createSequentialGroup() .addGroup(SecurityHeadersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(updateSecurityHeadersButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 179, Short.MAX_VALUE)) ); HeadersTabs.addTab("Security Headers", SecurityHeadersPanel); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HeadersTabs) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(HeadersTabs) ); }// </editor-fold>//GEN-END:initComponents private void securityHeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_securityHeadersTableMouseClicked if(evt.getClickCount()==2){ int index=securityHeadersTable.getSelectedRow(); if(securityHeaderReqRespList[index]!=null){ reqRespForm.setReqResp(securityHeaderReqRespList[index]); reqRespForm jf=new reqRespForm(); jf.setLocationRelativeTo(null); jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); jf.tabs.setSelectedIndex(1); jf.setVisible(true); } } else{ setDescription(getDescription((String) securityHeadersTable.getValueAt(securityHeadersTable.getSelectedRow(), 0))); } }//GEN-LAST:event_securityHeadersTableMouseClicked private void updateSecurityHeadersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateSecurityHeadersButtonActionPerformed for (int i = 0; i < securityHeadersTable.getRowCount(); i++) { if(!(boolean)securityHeadersTable.getValueAt(i, 1)){ for (int j = 0; j < HeadersTable.getRowCount(); j++) { if(HeadersTable.getValueAt(j, 1).equals(securityHeadersTable.getValueAt(i, 0))){ DefaultTableModel model=(DefaultTableModel)securityHeadersTable.getModel(); model.setValueAt(true, i, 1); model.setValueAt(HeadersTable.getValueAt(j, 2), i, 2); securityHeaderReqRespList[i]=headersReqRespList.get(j); break; } } } } }//GEN-LAST:event_updateSecurityHeadersButtonActionPerformed private void tableExceptionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tableExceptionButtonActionPerformed int[]rows=HeadersTable.getSelectedRows(); for(int i=rows.length-1;i>=0;i--){ String parameter=HeadersTable.getValueAt(rows[i], 3).toString(); addToExceptions(parameter); } removeExceptions(); }//GEN-LAST:event_tableExceptionButtonActionPerformed private void removeRowButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRowButtonActionPerformed int[]rows=HeadersTable.getSelectedRows(); for(int i=rows.length-1;i>=0;i--){ int thisInd=HeadersTable.convertRowIndexToModel(rows[i]); //to delete correctly in a sorted table removeHeadersTableRow(thisInd); } }//GEN-LAST:event_removeRowButtonActionPerformed private void exceptionRemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionRemoveButtonActionPerformed removeExceptions(); }//GEN-LAST:event_exceptionRemoveButtonActionPerformed private void exceptionFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exceptionFieldActionPerformed // TODO add your handling code here: }//GEN-LAST:event_exceptionFieldActionPerformed private void HeadersTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HeadersTableMouseClicked if(evt.getClickCount()==2){ int ind=HeadersTable.getSelectedRow(); int index=(int)HeadersTable.getValueAt(ind, 0)-1;
BurpExtender.output.println("table size: "+HeadersTable.getRowCount());
0
2023-10-23 12:13:00+00:00
8k
LuckPerms/rest-api-java-client
src/main/java/net/luckperms/rest/service/UserService.java
[ { "identifier": "CreateUserRequest", "path": "src/main/java/net/luckperms/rest/model/CreateUserRequest.java", "snippet": "public class CreateUserRequest extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n\n public CreateUserRequest(UUID uniqueId, String username) {\n this.uniqueId = uniqueId;\n this.username = username;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n}" }, { "identifier": "DemotionResult", "path": "src/main/java/net/luckperms/rest/model/DemotionResult.java", "snippet": "public class DemotionResult extends AbstractModel {\n private final boolean success;\n private final Status status;\n private final String groupFrom; // nullable\n private final String groupTo; // nullable\n\n public DemotionResult(boolean success, Status status, String groupFrom, String groupTo) {\n this.success = success;\n this.status = status;\n this.groupFrom = groupFrom;\n this.groupTo = groupTo;\n }\n\n public boolean success() {\n return this.success;\n }\n\n public Status status() {\n return this.status;\n }\n\n public String groupFrom() {\n return this.groupFrom;\n }\n\n public String groupTo() {\n return this.groupTo;\n }\n\n public enum Status {\n\n @SerializedName(\"success\")\n SUCCESS,\n\n @SerializedName(\"removed_from_first_group\")\n REMOVED_FROM_FIRST_GROUP,\n\n @SerializedName(\"malformed_track\")\n MALFORMED_TRACK,\n\n @SerializedName(\"not_on_track\")\n NOT_ON_TRACK,\n\n @SerializedName(\"ambiguous_call\")\n AMBIGUOUS_CALL,\n\n @SerializedName(\"undefined_failure\")\n UNDEFINED_FAILURE\n }\n}" }, { "identifier": "Metadata", "path": "src/main/java/net/luckperms/rest/model/Metadata.java", "snippet": "public class Metadata extends AbstractModel {\n private final Map<String, String> meta;\n private final String prefix; // nullable\n private final String suffix; // nullable\n private final String primaryGroup; // nullable\n\n public Metadata(Map<String, String> meta, String prefix, String suffix, String primaryGroup) {\n this.meta = meta;\n this.prefix = prefix;\n this.suffix = suffix;\n this.primaryGroup = primaryGroup;\n }\n\n public Map<String, String> meta() {\n return this.meta;\n }\n\n public String prefix() {\n return this.prefix;\n }\n\n public String suffix() {\n return this.suffix;\n }\n\n public String primaryGroup() {\n return this.primaryGroup;\n }\n}" }, { "identifier": "Node", "path": "src/main/java/net/luckperms/rest/model/Node.java", "snippet": "public class Node extends AbstractModel {\n private final String key;\n private final Boolean value;\n private final Set<Context> context;\n private final Long expiry;\n\n public Node(String key, Boolean value, Set<Context> context, Long expiry) {\n this.key = key;\n this.value = value;\n this.context = context;\n this.expiry = expiry;\n }\n\n public String key() {\n return this.key;\n }\n\n public Boolean value() {\n return this.value;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n\n public Long expiry() {\n return this.expiry;\n }\n}" }, { "identifier": "NodeType", "path": "src/main/java/net/luckperms/rest/model/NodeType.java", "snippet": "public enum NodeType {\n\n @SerializedName(\"regex_permission\")\n REGEX_PERMISSION,\n\n @SerializedName(\"inheritance\")\n INHERITANCE,\n\n @SerializedName(\"prefix\")\n PREFIX,\n\n @SerializedName(\"suffix\")\n SUFFIX,\n\n @SerializedName(\"meta\")\n META,\n\n @SerializedName(\"weight\")\n WEIGHT,\n\n @SerializedName(\"display_name\")\n DISPLAY_NAME;\n\n @Override\n public String toString() {\n return this.name().toLowerCase(Locale.ROOT);\n }\n}" }, { "identifier": "PermissionCheckRequest", "path": "src/main/java/net/luckperms/rest/model/PermissionCheckRequest.java", "snippet": "public class PermissionCheckRequest extends AbstractModel {\n private final String permission;\n private final QueryOptions queryOptions; // nullable\n\n public PermissionCheckRequest(String permission, QueryOptions queryOptions) {\n this.permission = permission;\n this.queryOptions = queryOptions;\n }\n\n public String permission() {\n return this.permission;\n }\n\n public QueryOptions queryOptions() {\n return this.queryOptions;\n }\n}" }, { "identifier": "PermissionCheckResult", "path": "src/main/java/net/luckperms/rest/model/PermissionCheckResult.java", "snippet": "public class PermissionCheckResult extends AbstractModel {\n private final Tristate result;\n private final Node node;\n\n public PermissionCheckResult(Tristate result, Node node) {\n this.result = result;\n this.node = node;\n }\n\n public Tristate result() {\n return this.result;\n }\n\n public Node node() {\n return this.node;\n }\n\n public enum Tristate {\n\n @SerializedName(\"true\")\n TRUE,\n\n @SerializedName(\"false\")\n FALSE,\n\n @SerializedName(\"undefined\")\n UNDEFINED\n }\n}" }, { "identifier": "PlayerSaveResult", "path": "src/main/java/net/luckperms/rest/model/PlayerSaveResult.java", "snippet": "public class PlayerSaveResult extends AbstractModel {\n private final Set<Outcome> outcomes;\n private final String previousUsername; // nullable\n private final Set<UUID> otherUniqueIds; // nullable\n\n public PlayerSaveResult(Set<Outcome> outcomes, String previousUsername, Set<UUID> otherUniqueIds) {\n this.outcomes = outcomes;\n this.previousUsername = previousUsername;\n this.otherUniqueIds = otherUniqueIds;\n }\n\n public Set<Outcome> outcomes() {\n return this.outcomes;\n }\n\n public String previousUsername() {\n return this.previousUsername;\n }\n\n public Set<UUID> otherUniqueIds() {\n return this.otherUniqueIds;\n }\n\n public enum Outcome {\n\n @SerializedName(\"clean_insert\")\n CLEAN_INSERT,\n\n @SerializedName(\"no_change\")\n NO_CHANGE,\n\n @SerializedName(\"username_updated\")\n USERNAME_UPDATED,\n\n @SerializedName(\"other_unique_ids_present_for_username\")\n OTHER_UNIQUE_IDS_PRESENT_FOR_USERNAME,\n }\n\n}" }, { "identifier": "PromotionResult", "path": "src/main/java/net/luckperms/rest/model/PromotionResult.java", "snippet": "public class PromotionResult extends AbstractModel {\n private final boolean success;\n private final Status status;\n private final String groupFrom; // nullable\n private final String groupTo; // nullable\n\n public PromotionResult(boolean success, Status status, String groupFrom, String groupTo) {\n this.success = success;\n this.status = status;\n this.groupFrom = groupFrom;\n this.groupTo = groupTo;\n }\n\n public boolean success() {\n return this.success;\n }\n\n public Status status() {\n return this.status;\n }\n\n public String groupFrom() {\n return this.groupFrom;\n }\n\n public String groupTo() {\n return this.groupTo;\n }\n\n public enum Status {\n\n @SerializedName(\"success\")\n SUCCESS,\n\n @SerializedName(\"added_to_first_group\")\n ADDED_TO_FIRST_GROUP,\n\n @SerializedName(\"malformed_track\")\n MALFORMED_TRACK,\n\n @SerializedName(\"end_of_track\")\n END_OF_TRACK,\n\n @SerializedName(\"ambiguous_call\")\n AMBIGUOUS_CALL,\n\n @SerializedName(\"undefined_failure\")\n UNDEFINED_FAILURE\n }\n}" }, { "identifier": "TemporaryNodeMergeStrategy", "path": "src/main/java/net/luckperms/rest/model/TemporaryNodeMergeStrategy.java", "snippet": "public enum TemporaryNodeMergeStrategy {\n\n @SerializedName(\"add_new_duration_to_existing\")\n ADD_NEW_DURATION_TO_EXISTING,\n\n @SerializedName(\"replace_existing_if_duration_longer\")\n REPLACE_EXISTING_IF_DURATION_LONGER,\n\n @SerializedName(\"none\")\n NONE\n\n}" }, { "identifier": "TrackRequest", "path": "src/main/java/net/luckperms/rest/model/TrackRequest.java", "snippet": "public class TrackRequest extends AbstractModel {\n private final String track;\n private final Set<Context> context;\n\n public TrackRequest(String track, Set<Context> context) {\n this.track = track;\n this.context = context;\n }\n\n public String track() {\n return this.track;\n }\n\n public Set<Context> context() {\n return this.context;\n }\n}" }, { "identifier": "UpdateUserRequest", "path": "src/main/java/net/luckperms/rest/model/UpdateUserRequest.java", "snippet": "public class UpdateUserRequest extends AbstractModel {\n private final String username;\n\n public UpdateUserRequest(String username) {\n this.username = username;\n }\n\n public String username() {\n return this.username;\n }\n}" }, { "identifier": "User", "path": "src/main/java/net/luckperms/rest/model/User.java", "snippet": "public class User extends AbstractModel {\n private final UUID uniqueId;\n private final String username;\n private final List<String> parentGroups;\n private final List<Node> nodes;\n private final Metadata metadata;\n\n public User(UUID uniqueId, String username, List<String> parentGroups, List<Node> nodes, Metadata metadata) {\n this.uniqueId = uniqueId;\n this.username = username;\n this.parentGroups = parentGroups;\n this.nodes = nodes;\n this.metadata = metadata;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n\n public List<String> parentGroups() {\n return this.parentGroups;\n }\n\n public List<Node> nodes() {\n return this.nodes;\n }\n\n public Metadata metadata() {\n return this.metadata;\n }\n}" }, { "identifier": "UserLookupResult", "path": "src/main/java/net/luckperms/rest/model/UserLookupResult.java", "snippet": "public class UserLookupResult extends AbstractModel {\n private final String username;\n private final UUID uniqueId;\n\n public UserLookupResult(String username, UUID uniqueId) {\n this.username = username;\n this.uniqueId = uniqueId;\n }\n\n public String username() {\n return this.username;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n}" }, { "identifier": "UserSearchResult", "path": "src/main/java/net/luckperms/rest/model/UserSearchResult.java", "snippet": "public class UserSearchResult extends AbstractModel {\n private final UUID uniqueId;\n private final Collection<Node> results;\n\n public UserSearchResult(UUID uniqueId, Collection<Node> results) {\n this.uniqueId = uniqueId;\n this.results = results;\n }\n\n public UUID uniqueId() {\n return this.uniqueId;\n }\n\n public Collection<Node> results() {\n return this.results;\n }\n}" } ]
import net.luckperms.rest.model.CreateUserRequest; import net.luckperms.rest.model.DemotionResult; 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.TemporaryNodeMergeStrategy; import net.luckperms.rest.model.TrackRequest; 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 retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.HTTP; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; import retrofit2.http.Query; import java.util.List; import java.util.Set; import java.util.UUID;
3,845
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * 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 net.luckperms.rest.service; public interface UserService { @GET("/user") Call<Set<UUID>> list(); @POST("/user") Call<PlayerSaveResult> create(@Body CreateUserRequest req); @GET("/user/lookup") Call<UserLookupResult> lookup(@Query("username") String username); @GET("/user/lookup") Call<UserLookupResult> lookup(@Query("uniqueId") UUID uniqueId); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByKey(@Query("key") String key); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByKeyStartsWith(@Query("keyStartsWith") String keyStartsWith); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByMetaKey(@Query("metaKey") String metaKey); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByType(@Query("type") NodeType type); @GET("/user/{uniqueId}") Call<User> get(@Path("uniqueId") UUID uniqueId); @PATCH("/user/{uniqueId}") Call<Void> update(@Path("uniqueId") UUID uniqueId, @Body UpdateUserRequest req); @DELETE("/user/{uniqueId}") Call<Void> delete(@Path("uniqueId") UUID uniqueId); @GET("/user/{uniqueId}/nodes") Call<List<Node>> nodes(@Path("uniqueId") UUID uniqueId); @POST("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node); @POST("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy); @PATCH("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes); @PATCH("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy); @PUT("/user/{uniqueId}/nodes") Call<Void> nodesSet(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes); @DELETE("/user/{uniqueId}/nodes") Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId); @HTTP(method = "DELETE", path = "/user/{uniqueId}/nodes", hasBody = true) Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes); @GET("/user/{uniqueId}/meta") Call<Metadata> metadata(@Path("uniqueId") UUID uniqueId); @GET("/user/{uniqueId}/permissionCheck") Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Query("permission") String permission); @POST("/user/{uniqueId}/permissionCheck") Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Body PermissionCheckRequest req); @POST("/user/{uniqueId}/promote")
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <[email protected]> * 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 net.luckperms.rest.service; public interface UserService { @GET("/user") Call<Set<UUID>> list(); @POST("/user") Call<PlayerSaveResult> create(@Body CreateUserRequest req); @GET("/user/lookup") Call<UserLookupResult> lookup(@Query("username") String username); @GET("/user/lookup") Call<UserLookupResult> lookup(@Query("uniqueId") UUID uniqueId); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByKey(@Query("key") String key); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByKeyStartsWith(@Query("keyStartsWith") String keyStartsWith); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByMetaKey(@Query("metaKey") String metaKey); @GET("/user/search") Call<List<UserSearchResult>> searchNodesByType(@Query("type") NodeType type); @GET("/user/{uniqueId}") Call<User> get(@Path("uniqueId") UUID uniqueId); @PATCH("/user/{uniqueId}") Call<Void> update(@Path("uniqueId") UUID uniqueId, @Body UpdateUserRequest req); @DELETE("/user/{uniqueId}") Call<Void> delete(@Path("uniqueId") UUID uniqueId); @GET("/user/{uniqueId}/nodes") Call<List<Node>> nodes(@Path("uniqueId") UUID uniqueId); @POST("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node); @POST("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body Node node, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy); @PATCH("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes); @PATCH("/user/{uniqueId}/nodes") Call<List<Node>> nodesAdd(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes, @Query("temporaryNodeMergeStrategy") TemporaryNodeMergeStrategy temporaryNodeMergeStrategy); @PUT("/user/{uniqueId}/nodes") Call<Void> nodesSet(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes); @DELETE("/user/{uniqueId}/nodes") Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId); @HTTP(method = "DELETE", path = "/user/{uniqueId}/nodes", hasBody = true) Call<Void> nodesDelete(@Path("uniqueId") UUID uniqueId, @Body List<Node> nodes); @GET("/user/{uniqueId}/meta") Call<Metadata> metadata(@Path("uniqueId") UUID uniqueId); @GET("/user/{uniqueId}/permissionCheck") Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Query("permission") String permission); @POST("/user/{uniqueId}/permissionCheck") Call<PermissionCheckResult> permissionCheck(@Path("uniqueId") UUID uniqueId, @Body PermissionCheckRequest req); @POST("/user/{uniqueId}/promote")
Call<PromotionResult> promote(@Path("uniqueId") UUID uniqueId, @Body TrackRequest req);
8
2023-10-22 16:07:30+00:00
8k
EvanAatrox/hubbo
hubbo-config/src/main/java/cn/hubbo/configuration/security/SpringSecurityConfig.java
[ { "identifier": "JWTProperties", "path": "hubbo-common/src/main/java/cn/hubbo/common/domain/to/properties/JWTProperties.java", "snippet": "@Component\n@ConfigurationProperties(prefix = \"token\")\n@Data\npublic class JWTProperties {\n\n\n Map<String, Object> header = new HashMap<>();\n\n\n /* 类型 */\n private String type = \"JWT\";\n\n\n /* 使用的加密算法 */\n private String algorithm;\n\n\n /* token的有效期,单位为秒 */\n @DurationUnit(ChronoUnit.SECONDS)\n private Duration duration;\n\n\n /* token加密的密钥 */\n private String secretKey;\n\n @PostConstruct\n public void init() {\n header.put(\"typ\", type);\n header.put(\"alg\", algorithm);\n }\n\n\n}" }, { "identifier": "AccessDecisionManagerImpl", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/AccessDecisionManagerImpl.java", "snippet": "public class AccessDecisionManagerImpl implements AccessDecisionManager {\n\n /**\n * Resolves an access control decision for the passed parameters.\n *\n * @param authentication the caller invoking the method (not null)\n * @param object the secured object being called\n * @param configAttributes the configuration attributes associated with the secured\n * object being invoked\n * @throws AccessDeniedException if access is denied as the authentication does not\n * hold a required authority or ACL privilege\n * @throws InsufficientAuthenticationException if access is denied as the\n * authentication does not provide a sufficient level of trust\n */\n @Override\n public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {\n for (GrantedAuthority authority : authentication.getAuthorities()) {\n System.out.println(authority);\n }\n }\n\n /**\n * Indicates whether this <code>AccessDecisionManager</code> is able to process\n * authorization requests presented with the passed <code>ConfigAttribute</code>.\n * <p>\n * This allows the <code>AbstractSecurityInterceptor</code> to check every\n * configuration attribute can be consumed by the configured\n * <code>AccessDecisionManager</code> and/or <code>RunAsManager</code> and/or\n * <code>AfterInvocationManager</code>.\n * </p>\n *\n * @param attribute a configuration attribute that has been configured against the\n * <code>AbstractSecurityInterceptor</code>\n * @return true if this <code>AccessDecisionManager</code> can support the passed\n * configuration attribute\n */\n @Override\n public boolean supports(ConfigAttribute attribute) {\n return true;\n }\n\n /**\n * Indicates whether the <code>AccessDecisionManager</code> implementation is able to\n * provide access control decisions for the indicated secured object type.\n *\n * @param clazz the class that is being queried\n * @return <code>true</code> if the implementation can process the indicated class\n */\n @Override\n public boolean supports(Class<?> clazz) {\n return true;\n }\n}" }, { "identifier": "CustomFilterInvocationSecurityMetadataSource", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/CustomFilterInvocationSecurityMetadataSource.java", "snippet": "public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {\n\n\n @Override\n public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {\n if (object instanceof FilterInvocation filterInvocation) {\n HttpServletRequest request = filterInvocation.getRequest();\n return SecurityConfig.createList(\"admin\");\n }\n return null;\n }\n\n @Override\n public Collection<ConfigAttribute> getAllConfigAttributes() {\n return null;\n }\n\n @Override\n public boolean supports(Class<?> clazz) {\n return true;\n }\n\n}" }, { "identifier": "DynamicFilter", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/DynamicFilter.java", "snippet": "public class DynamicFilter extends AbstractSecurityInterceptor implements Filter {\n\n private FilterInvocationSecurityMetadataSource invocationSecurityMetadataSource;\n\n\n private AccessDecisionManager accessDecisionManager;\n\n private AntPathMatcher antPathMatcher;\n\n\n public DynamicFilter(FilterInvocationSecurityMetadataSource invocationSecurityMetadataSource, AccessDecisionManager accessDecisionManager) {\n this.invocationSecurityMetadataSource = invocationSecurityMetadataSource;\n this.accessDecisionManager = accessDecisionManager;\n super.setAccessDecisionManager(accessDecisionManager);\n this.antPathMatcher = new AntPathMatcher();\n }\n\n @Override\n public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {\n if (servletRequest instanceof HttpServletRequest request && servletResponse instanceof HttpServletResponse response) {\n FilterInvocation filterInvocation = new FilterInvocation(request, response, filterChain);\n //直接放行OPTIONS 请求\n if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {\n filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());\n return;\n }\n // 放行白名单资源\n List<String> ignorePathPatterns = List.of(\"/test/**\", \"/user/**\");\n for (String pattern : ignorePathPatterns) {\n if (antPathMatcher.match(pattern, request.getRequestURI().toString())) {\n filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());\n return;\n }\n }\n InterceptorStatusToken token = super.beforeInvocation(filterInvocation);\n try {\n filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());\n } finally {\n super.afterInvocation(token, null);\n }\n\n }\n }\n\n\n @Override\n public Class<?> getSecureObjectClass() {\n return FilterInvocation.class;\n }\n\n\n @Override\n public SecurityMetadataSource obtainSecurityMetadataSource() {\n return invocationSecurityMetadataSource;\n }\n\n\n}" }, { "identifier": "FormAndJsonLoginFilter", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/FormAndJsonLoginFilter.java", "snippet": "@Slf4j\n@SuppressWarnings({\"unused\"})\npublic class FormAndJsonLoginFilter extends UsernamePasswordAuthenticationFilter {\n\n\n private final AuthenticationManager authenticationManager;\n\n\n private final RedisTemplate<String, Object> redisTemplate;\n\n\n private final ValueOperations<String, Object> ops;\n\n\n /* 用户token信息缓存时间 */\n private Duration duration = Duration.ofDays(1);\n\n\n /* Jwt配置信息 */\n private JWTProperties jwtProperties;\n\n public FormAndJsonLoginFilter(AuthenticationManager authenticationManager, RedisTemplate<String, Object> redisTemplate, JWTProperties jwtProperties) {\n super(authenticationManager);\n super.setPostOnly(true);\n super.setFilterProcessesUrl(\"/user/login\");\n this.authenticationManager = authenticationManager;\n this.redisTemplate = redisTemplate;\n this.ops = redisTemplate.opsForValue();\n this.jwtProperties = jwtProperties;\n }\n\n\n /**\n * @param request 请求\n * @param response 响应\n * @return 认证信息\n * @throws AuthenticationException 失败信息,异常的明细详见CSDN 程序三两行的博客描述\n * https://blog.csdn.net/qq_34491508/article/details/126010263\n */\n @Override\n public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {\n String contentType = request.getContentType();\n LoginUserVO userVO = null;\n UsernamePasswordAuthenticationToken authenticationToken = null;\n if (MediaType.APPLICATION_JSON.includes(MediaType.valueOf(contentType))) {\n try {\n userVO = ServletUtils.getRequiredData(request, LoginUserVO.class);\n } catch (Exception ignored) {\n }\n // 校验提交的登录信息是否有效,无效则抛出不充分的认证信息错误\n if (Objects.isNull(userVO) || StringUtils.isBlank(userVO.getUsername()) || StringUtils.isBlank(userVO.getRawPasswd())) {\n throw new InsufficientAuthenticationException(\"登录信息不完整\");\n }\n //TODO 校验验证码是否一致,否则抛出CaptchaNotValidException\n checkCaptchaIsValid(userVO);\n authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(userVO.getUsername(), userVO.getRawPasswd());\n } else {\n String username = ServletUtils.getParameterOrDefault(request, \"username\");\n String rawPasswd = ServletUtils.getParameterOrDefault(request, \"rawPasswd\");\n if (StringUtils.isBlank(username) || StringUtils.isEmpty(rawPasswd)) {\n throw new InsufficientAuthenticationException(\"登录信息不完整\");\n }\n authenticationToken = UsernamePasswordAuthenticationToken.unauthenticated(username, rawPasswd);\n }\n this.setDetails(request, authenticationToken);\n return authenticationManager.authenticate(authenticationToken);\n }\n\n /**\n * 认证成功地回调\n *\n * @param request 请求\n * @param response 响应\n * @param chain 过滤器链\n * @param authResult 认证信息\n * @throws IOException 异常信息\n * @throws ServletException 异常信息\n */\n @Override\n protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {\n log.info(\"认证信息{}\", authResult);\n if (authResult instanceof UsernamePasswordAuthenticationToken authenticationToken) {\n if (authenticationToken.getPrincipal() instanceof SecurityUser securityUser) {\n User userDetail = securityUser.getUserDetail();\n ops.set(RedisConstants.USER_TOKEN_PREFIX.concat(userDetail.getUsername()), userDetail, duration);\n String uuid = IdUtil.fastUUID();\n JWTObject jwtObject = JWTTokenBuilder.create()\n .id(uuid)\n .claim(userDetail.getUsername())\n .timeout(jwtProperties.getDuration())\n .sign(jwtProperties.getSecretKey()).build();\n // TODO 将token信息存入redis中,后期token续期需要使用到,即使token的值一直在变化,但是token的uuid应该始终不变了\n ops.set(RedisConstants.USER_TOKEN_CACHE_PREFIX.concat(uuid), jwtObject.getToken(), duration);\n Result result = new Result(ResponseStatusEnum.SUCCESS).add(\"token\", jwtObject.getToken());\n ServletUtils.reposeObjectWithJson(response, result);\n }\n } else {\n chain.doFilter(request, response);\n }\n }\n\n\n /**\n * TODO 校验验证码\n *\n * @param loginUserVO 校验验证码是否一致,否则抛出CaptchaNotValidException\n */\n private void checkCaptchaIsValid(LoginUserVO loginUserVO) {\n\n }\n\n\n}" }, { "identifier": "JwtTokenFilter", "path": "hubbo-security/src/main/java/cn/hubbo/security/filter/JwtTokenFilter.java", "snippet": "public class JwtTokenFilter extends OncePerRequestFilter {\n\n\n private RedisTemplate<String, Object> redisTemplate;\n\n private ValueOperations<String, Object> ops;\n\n private JWTProperties jwtProperties;\n\n public JwtTokenFilter(RedisTemplate<String, Object> redisTemplate, JWTProperties jwtProperties) {\n this.redisTemplate = redisTemplate;\n this.ops = redisTemplate.opsForValue();\n this.jwtProperties = jwtProperties;\n }\n\n @Override\n protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {\n String headerValue = request.getHeader(WebConstants.TOKEN_HEADER);\n if (StringUtils.isNotBlank(headerValue)) {\n // 验证token\n String token = headerValue.replace(WebConstants.TOKEN_VALUE_PREFIX, \"\");\n JWTObject jwtObject = JWTTokenBuilder.parseJWTToken(token, jwtProperties);\n if (jwtObject.isLegal()) {\n String uuid = jwtObject.getUuid();\n String storageToken = (String) this.ops.get(RedisConstants.USER_TOKEN_CACHE_PREFIX.concat(uuid));\n // 和服务端token比对,后期需要进行token的需求操作\n if (token.equals(storageToken)) {\n User user = (User) this.ops.get(RedisConstants.USER_TOKEN_PREFIX.concat(jwtObject.getUsername()));\n SecurityUser securityUser = new SecurityUser();\n securityUser.setUserDetail(user);\n UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());\n authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));\n SecurityContextHolder.getContext().setAuthentication(authenticationToken);\n }\n }\n }\n filterChain.doFilter(request, response);\n }\n\n\n}" }, { "identifier": "AccessDeniedHandlerImpl", "path": "hubbo-security/src/main/java/cn/hubbo/security/handler/AccessDeniedHandlerImpl.java", "snippet": "@Slf4j\npublic class AccessDeniedHandlerImpl implements AccessDeniedHandler {\n\n\n @Override\n public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {\n log.error(\"访问受限\", accessDeniedException);\n Result result = new Result(ResponseStatusEnum.ERROR)\n .add(\"detail\", \"访问受限制\");\n ServletUtils.reposeObjectWithJson(response, result);\n }\n\n\n}" }, { "identifier": "AuthenticationEntryPointImpl", "path": "hubbo-security/src/main/java/cn/hubbo/security/handler/AuthenticationEntryPointImpl.java", "snippet": "@Slf4j\npublic class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {\n\n\n /**\n * 认证失败的回调\n * TODO 相同的一段时间内同一账户认证失败次数达到5次之后就需要锁定账户,24小时之后恢复\n *\n * @param request 请求\n * @param response 响应\n * @param authException 异常信息\n * @throws IOException 异常信息\n * @throws ServletException 异常信息\n */\n @Override\n public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {\n log.error(\"认证失败信息\", authException);\n String detailMessage = \"认证失败\";\n // TODO 待完善\n if (authException instanceof BadCredentialsException) {\n detailMessage = \"账号或者密码错误\";\n } else if (authException instanceof InsufficientAuthenticationException) {\n // 未提交用户登录名或者密码,或者验证码等信息才会抛出这个错误\n detailMessage = \"请检查登录参数是否齐全\";\n } else if (authException instanceof AccountStatusException) {\n // 账号状态异常\n detailMessage = \"账号已经被锁定,无法进行操作\";\n } else if (authException instanceof CaptchaNotValidException) {\n detailMessage = \"请检查验证码是否有误\";\n } else if (authException instanceof AuthenticationCredentialsNotFoundException) {\n detailMessage = \"无权限访问保护资源\";\n }\n addRequestToRestrictedAccessList(request);\n Result result = new Result(ResponseStatusEnum.ERROR).add(\"detail\", detailMessage);\n ServletUtils.reposeObjectWithJson(response, result);\n }\n\n\n /**\n * @param request 记录下客户端的错误请求信息,超出限制后服务端将会拒绝与客户端相同IP的所有请求\n */\n private void addRequestToRestrictedAccessList(HttpServletRequest request) {\n String clientIP = ServletUtils.getClientIP(request);\n if (!NetUtil.isInnerIP(clientIP)) {\n ClientInfo clientInfo = ServletUtils.getClientInfo(request);\n // TODO 记录异常信息和客户端信息\n log.info(\"记录下一次异常行为,客户端信息{}\", clientInfo);\n }\n }\n\n\n}" } ]
import cn.hubbo.common.domain.to.properties.JWTProperties; import cn.hubbo.security.filter.AccessDecisionManagerImpl; import cn.hubbo.security.filter.CustomFilterInvocationSecurityMetadataSource; import cn.hubbo.security.filter.DynamicFilter; import cn.hubbo.security.filter.FormAndJsonLoginFilter; import cn.hubbo.security.filter.JwtTokenFilter; import cn.hubbo.security.handler.AccessDeniedHandlerImpl; import cn.hubbo.security.handler.AuthenticationEntryPointImpl; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.filter.OncePerRequestFilter; import java.util.List;
4,705
package cn.hubbo.configuration.security; /** * @author 张晓华 * @version V1.0 * @Package cn.hubbo.configuration.security * @date 2023/10/20 23:51 * @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利 */ @Configuration @AllArgsConstructor public class SpringSecurityConfig { private UserDetailsService userDetailsService; private AuthenticationConfiguration authenticationConfiguration; private RedisTemplate<String, Object> redisTemplate; private JWTProperties jwtProperties; /** * @return 密码加密工具 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * @return 用户信息校验的工具 */ @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); return daoAuthenticationProvider; } @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); httpSecurity.csrf(AbstractHttpConfigurer::disable) .sessionManagement(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)) .passwordManagement(AbstractHttpConfigurer::disable) .anonymous(AbstractHttpConfigurer::disable) .rememberMe(AbstractHttpConfigurer::disable) .headers(AbstractHttpConfigurer::disable) .authenticationManager(authenticationManager()) .httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{})) .permitAll() .anyRequest() .authenticated()) .authenticationProvider(authenticationProvider()) .exceptionHandling(web -> web .accessDeniedHandler(accessDeniedHandler()) .authenticationEntryPoint(authenticationEntryPoint())) //.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class) .addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } /** * @return 放行的资源 */ @Bean public WebSecurityCustomizer webSecurityCustomizer() { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{})); } @Bean public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) { FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties); loginFilter.setPostOnly(true); loginFilter.setFilterProcessesUrl("/user/login"); loginFilter.setAuthenticationManager(authenticationManager); loginFilter.setAllowSessionCreation(false); return loginFilter; } @Bean public AccessDeniedHandler accessDeniedHandler() {
package cn.hubbo.configuration.security; /** * @author 张晓华 * @version V1.0 * @Package cn.hubbo.configuration.security * @date 2023/10/20 23:51 * @Copyright © 2023-2025 版权所有,未经授权均为剽窃,作者保留一切权利 */ @Configuration @AllArgsConstructor public class SpringSecurityConfig { private UserDetailsService userDetailsService; private AuthenticationConfiguration authenticationConfiguration; private RedisTemplate<String, Object> redisTemplate; private JWTProperties jwtProperties; /** * @return 密码加密工具 */ @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } /** * @return 用户信息校验的工具 */ @Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); return daoAuthenticationProvider; } @Bean public AuthenticationManager authenticationManager() throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); httpSecurity.csrf(AbstractHttpConfigurer::disable) .sessionManagement(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)) .passwordManagement(AbstractHttpConfigurer::disable) .anonymous(AbstractHttpConfigurer::disable) .rememberMe(AbstractHttpConfigurer::disable) .headers(AbstractHttpConfigurer::disable) .authenticationManager(authenticationManager()) .httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorization -> authorization.requestMatchers(ignorePathPatterns.toArray(new String[]{})) .permitAll() .anyRequest() .authenticated()) .authenticationProvider(authenticationProvider()) .exceptionHandling(web -> web .accessDeniedHandler(accessDeniedHandler()) .authenticationEntryPoint(authenticationEntryPoint())) //.addFilterBefore(dynamicFilter(), FilterSecurityInterceptor.class) .addFilterBefore(oncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(loginFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } /** * @return 放行的资源 */ @Bean public WebSecurityCustomizer webSecurityCustomizer() { List<String> ignorePathPatterns = List.of("/test/**", "/user/login"); return web -> web.ignoring().requestMatchers(ignorePathPatterns.toArray(new String[]{})); } @Bean public FormAndJsonLoginFilter loginFilter(AuthenticationManager authenticationManager) { FormAndJsonLoginFilter loginFilter = new FormAndJsonLoginFilter(authenticationManager, redisTemplate, jwtProperties); loginFilter.setPostOnly(true); loginFilter.setFilterProcessesUrl("/user/login"); loginFilter.setAuthenticationManager(authenticationManager); loginFilter.setAllowSessionCreation(false); return loginFilter; } @Bean public AccessDeniedHandler accessDeniedHandler() {
return new AccessDeniedHandlerImpl();
6
2023-10-18 09:38:29+00:00
8k
RoessinghResearch/senseeact
SenSeeActService/src/main/java/nl/rrd/senseeact/service/controller/AccessController.java
[ { "identifier": "ProjectDataModule", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/ProjectDataModule.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown=true)\npublic class ProjectDataModule extends JsonObject {\n\tprivate String name;\n\tprivate List<String> tables = new ArrayList<>();\n\n\tpublic ProjectDataModule() {\n\t}\n\n\tpublic ProjectDataModule(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic List<String> getTables() {\n\t\treturn tables;\n\t}\n\n\tpublic void setTables(List<String> tables) {\n\t\tthis.tables = tables;\n\t}\n\n\tpublic void addTable(String table) {\n\t\ttables.add(table);\n\t}\n}" }, { "identifier": "ProjectUserAccessRule", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/ProjectUserAccessRule.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown=true)\npublic class ProjectUserAccessRule extends JsonObject {\n\t@JsonInclude(JsonInclude.Include.NON_NULL)\n\tprivate Map<String,Object> grantee = null;\n\t@JsonInclude(JsonInclude.Include.NON_NULL)\n\tprivate Map<String,Object> subject = null;\n\tprivate List<ProjectUserAccessRestriction> accessRestriction = null;\n\n\t/**\n\t * Returns the public profile of the grantee. This is only set when you\n\t * query for the access rules of a specified subject. The result is a map\n\t * with selected fields from the {@link User User} object. It should include\n\t * at least the fields \"userid\" and \"emailVerified\".\n\t *\n\t * @return the grantee or null\n\t */\n\tpublic Map<String, Object> getGrantee() {\n\t\treturn grantee;\n\t}\n\n\t/**\n\t * Sets the public profile of the grantee. This should only be set at a\n\t * query for the access rules of a specified subject. It is a map with\n\t * selected fields from the {@link User User} object. It should include at\n\t * least the fields \"userid\" and \"emailVerified\".\n\t *\n\t * @param grantee the grantee or null\n\t */\n\tpublic void setGrantee(Map<String, Object> grantee) {\n\t\tthis.grantee = grantee;\n\t}\n\n\t/**\n\t * Returns the public profile of the subject. This is only set when you\n\t * query for the access rules of a specified grantee. The result is a map\n\t * with selected fields from the {@link User User} object. It should include\n\t * at least the field \"userid\".\n\t *\n\t * @return the subject or null\n\t */\n\tpublic Map<String, Object> getSubject() {\n\t\treturn subject;\n\t}\n\n\t/**\n\t * Sets the public profile of the subject. This should only be set at a\n\t * query for the access rules of a specified grantee. It is is a map with\n\t * selected fields from the {@link User User} object. It should include\n\t * at least the field \"userid\".\n\t *\n\t * @param subject the subject or null\n\t */\n\tpublic void setSubject(Map<String, Object> subject) {\n\t\tthis.subject = subject;\n\t}\n\n\t/**\n\t * Returns the access restriction. If the grantee has full access to the\n\t * subject's data, then this method returns null.\n\t *\n\t * @return the access restriction or null\n\t */\n\tpublic List<ProjectUserAccessRestriction> getAccessRestriction() {\n\t\treturn accessRestriction;\n\t}\n\n\t/**\n\t * Sets the access restriction. If the grantee has full access to the\n\t * subject's data, then this should be null.\n\t *\n\t * @param accessRestriction the access restriction or null\n\t */\n\tpublic void setAccessRestriction(\n\t\t\tList<ProjectUserAccessRestriction> accessRestriction) {\n\t\tthis.accessRestriction = accessRestriction;\n\t}\n}" }, { "identifier": "QueryRunner", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/QueryRunner.java", "snippet": "public class QueryRunner {\n\n\t/**\n\t * Runs a query on the authentication database. If the HTTP request is\n\t * specified, it will validate the authentication token. If there is no\n\t * token in the request, or the token is empty or invalid, it throws an\n\t * HttpException with 401 Unauthorized. If the request is null, it will not\n\t * validate anything. This can be used for a login or signup.\n\t * \n\t * @param query the query\n\t * @param versionName the protocol version name (see {@link ProtocolVersion\n\t * ProtocolVersion})\n\t * @param request the HTTP request or null\n\t * @param response the HTTP response (to add header WWW-Authenticate in\n\t * case of 401 Unauthorized)\n\t * @return the query result\n\t * @throws HttpException if the query should return an HTTP error status\n\t * @throws Exception if an unexpected error occurs. This results in HTTP\n\t * error status 500 Internal Server Error.\n\t */\n\tpublic static <T> T runAuthQuery(AuthQuery<T> query,\n\t\t\tString versionName, HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws HttpException, Exception {\n\t\tProtocolVersion version;\n\t\ttry {\n\t\t\tversion = ProtocolVersion.forVersionName(versionName);\n\t\t} catch (IllegalArgumentException ex) {\n\t\t\tthrow new BadRequestException(\"Unknown protocol version: \" +\n\t\t\t\t\tversionName);\n\t\t}\n\t\tDatabaseConnection conn = null;\n\t\ttry {\n\t\t\tDatabaseLoader dbLoader = DatabaseLoader.getInstance();\n\t\t\tconn = dbLoader.openConnection();\n\t\t\tDatabase authDb = dbLoader.initAuthDatabase(conn);\n\t\t\tUser user = null;\n\t\t\tif (request != null)\n\t\t\t\tuser = validateToken(version, request, response, authDb, null);\n\t\t\treturn query.runQuery(version, authDb, user);\n\t\t} catch (UnauthorizedException ex) {\n\t\t\tresponse.addHeader(\"WWW-Authenticate\", \"None\");\n\t\t\tthrow ex;\n\t\t} catch (HttpException ex) {\n\t\t\tthrow ex;\n\t\t} catch (Exception ex) {\n\t\t\tLogger logger = AppComponents.getLogger(\n\t\t\t\t\tQueryRunner.class.getSimpleName());\n\t\t\tString stackTrace;\n\t\t\tStringWriter stringWriter = new StringWriter();\n\t\t\ttry (PrintWriter writer = new PrintWriter(stringWriter)) {\n\t\t\t\tex.printStackTrace(writer);\n\t\t\t\tstackTrace = stringWriter.getBuffer().toString();\n\t\t\t}\n\t\t\tlogger.error(\"Internal Server Error in auth query: \" +\n\t\t\t\t\tex.getMessage() + \": \" + stackTrace, ex);\n\t\t\tthrow new InternalServerErrorException();\n\t\t} finally {\n\t\t\tif (conn != null)\n\t\t\t\tconn.close();\n\t\t}\n\t}\n\t\n\t/**\n\t * Runs a query on a project database. It will validate the authentication\n\t * token in the specified HTTP request. If no token is specified, or the\n\t * token is empty or invalid, it throws an HttpException with\n\t * 401 Unauthorized.\n\t * \n\t * @param query the query\n\t * @param versionName the protocol version name (see {@link ProtocolVersion\n\t * ProtocolVersion})\n\t * @param project the project code\n\t * @param request the HTTP request\n\t * @param response the HTTP response (to add header WWW-Authenticate in\n\t * case of 401 Unauthorized)\n\t * @return the query result\n\t * @throws HttpException if the query should return an HTTP error status\n\t * @throws Exception if an unexpected error occurs. This results in HTTP\n\t * error status 500 Internal Server Error.\n\t */\n\tpublic static <T> T runProjectQuery(ProjectQuery<T> query,\n\t\t\tString versionName, String project, HttpServletRequest request,\n\t\t\tHttpServletResponse response) throws HttpException, Exception {\n\t\treturn runProjectQuery(query, versionName, project, request, response,\n\t\t\t\tnull);\n\t}\n\n\tpublic static <T> T runProjectQuery(ProjectQuery<T> query,\n\t\t\tString versionName, String project, HttpServletRequest request,\n\t\t\tHttpServletResponse response, String logId) throws HttpException,\n\t\t\tException {\n\t\tLogger logger = AppComponents.getLogger(\n\t\t\t\tQueryRunner.class.getSimpleName());\n\t\tif (logId != null) {\n\t\t\tlogger.info(\"Run project query {} start, project {}\", logId, project);\n\t\t}\n\t\tProtocolVersion version;\n\t\ttry {\n\t\t\tversion = ProtocolVersion.forVersionName(versionName);\n\t\t} catch (IllegalArgumentException ex) {\n\t\t\tthrow new BadRequestException(\"Unknown protocol version: \" +\n\t\t\t\t\tversionName);\n\t\t}\n\t\tDatabaseConnection conn = null;\n\t\ttry {\n\t\t\tDatabaseLoader dbLoader = DatabaseLoader.getInstance();\n\t\t\tif (logId != null) {\n\t\t\t\tlogger.info(\"Run project query {} before open database connection, project {}\",\n\t\t\t\t\t\tlogId, project);\n\t\t\t}\n\t\t\tconn = dbLoader.openConnection();\n\t\t\tif (logId != null) {\n\t\t\t\tlogger.info(\"Run project query {} after open database connection, project {}\",\n\t\t\t\t\t\tlogId, project);\n\t\t\t}\n\t\t\tDatabase authDb = dbLoader.initAuthDatabase(conn);\n\t\t\tif (logId != null) {\n\t\t\t\tlogger.info(\"Run project query {} after init auth database, project {}\",\n\t\t\t\t\t\tlogId, project);\n\t\t\t}\n\t\t\tUser user = validateToken(version, request, response, authDb,\n\t\t\t\t\tproject);\n\t\t\tif (logId != null) {\n\t\t\t\tlogger.info(\"Run project query {} validated token, project {}, user {}\",\n\t\t\t\t\t\tlogId, project, user.getUserid());\n\t\t\t}\n\t\t\tBaseProject baseProject =\n\t\t\t\t\tProjectControllerExecution.findUserProject(project, authDb,\n\t\t\t\t\tuser);\n\t\t\tDatabase projectDb = dbLoader.initProjectDatabase(conn, project);\n\t\t\tif (logId != null) {\n\t\t\t\tlogger.info(\"Run project query {} after init sample database, project {}, user {}\",\n\t\t\t\t\t\tlogId, project, user.getUserid());\n\t\t\t}\n\t\t\tT result = query.runQuery(version, authDb, projectDb, user,\n\t\t\t\t\tbaseProject);\n\t\t\tif (logId != null) {\n\t\t\t\tlogger.info(\"Run project query {} after run query, project {}, user {}\",\n\t\t\t\t\t\tlogId, project, user.getUserid());\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch (UnauthorizedException ex) {\n\t\t\tresponse.addHeader(\"WWW-Authenticate\", \"None\");\n\t\t\tthrow ex;\n\t\t} catch (HttpException ex) {\n\t\t\tthrow ex;\n\t\t} catch (Exception ex) {\n\t\t\tString stackTrace;\n\t\t\tStringWriter stringWriter = new StringWriter();\n\t\t\ttry (PrintWriter writer = new PrintWriter(stringWriter)) {\n\t\t\t\tex.printStackTrace(writer);\n\t\t\t\tstackTrace = stringWriter.getBuffer().toString();\n\t\t\t}\n\t\t\tlogger.error(\"Internal Server Error in project query: \" +\n\t\t\t\t\tex.getMessage() + \": \" + stackTrace, ex);\n\t\t\tthrow new InternalServerErrorException();\n\t\t} finally {\n\t\t\tif (conn != null)\n\t\t\t\tconn.close();\n\t\t}\n\t}\n\n\t/**\n\t * Validates the authentication token in the specified HTTP request. If the\n\t * validation fails, this method throws an HttpException with\n\t * 401 Unauthorized. This happens in the following cases:\n\t *\n\t * <p><ul>\n\t * <li>No token is specified</li>\n\t * <li>The token is empty or invalid</li>\n\t * <li>The authenticated user is inactive</li>\n\t * </ul></p>\n\t *\n\t * <p>An error code is included with the exception.</p>\n\t *\n\t * <p>If the validation succeeds, this method will return the user object\n\t * for the authenticated user.</p>\n\t *\n\t * <p>The general token can be specified in header X-Auth-Token or in cookie\n\t * authToken. In addition to the general token, this method can validate SSO\n\t * tokens for specific projects. In that case this method also checks if the\n\t * user is a member of that project. If the request accesses a specific\n\t * project, it also checks whether that is the same as the SSO project.\n\t * Furthermore it checks the user role. You cannot authenticate as an admin\n\t * using an SSO token. And if you authenticate as a professional, you can\n\t * only access project data, and not for example the user profile or user\n\t * access functions.</p>\n\t *\n\t * <p>In protocol versions since 6.0.0, the SSO token should contain the\n\t * user ID. In older versions it should contain the email address of the\n\t * user.</p>\n\t *\n\t * <p>The general token may be configured so that the token and authToken\n\t * cookie should be extended at every successful validation. In that case\n\t * this method will set the extended cookie in the specified HTTP\n\t * response.</p>\n\t * \n\t * @param authDb the authentication database\n\t * @param request the HTTP request\n\t * @param response the HTTP response\n\t * @param project the code of the project that the user wants to access,\n\t * or null\n\t * @return the authenticated user\n\t * @throws UnauthorizedException if no token is specified, or the token is\n\t * empty or invalid\n\t * @throws DatabaseException if a database error occurs\n\t */\n\tprivate static User validateToken(ProtocolVersion version,\n\t\t\tHttpServletRequest request, HttpServletResponse response,\n\t\t\tDatabase authDb, String project) throws HttpException, Exception {\n\t\tValidateTokenResult result = getAuthenticatedUser(version, request,\n\t\t\t\tresponse, authDb, project);\n\t\tif (!result.getUser().isActive()) {\n\t\t\tthrow new UnauthorizedException(ErrorCode.ACCOUNT_INACTIVE,\n\t\t\t\t\t\"Account has been deactivated\");\n\t\t}\n\t\tif (result.getAuthDetails() != null && result.getAuthDetails()\n\t\t\t\t.isAutoExtendCookie()) {\n\t\t\tZonedDateTime now = DateTimeUtils.nowMs();\n\t\t\tAuthToken.createToken(version, result.getUser(), now,\n\t\t\t\t\tresult.getAuthDetails().getAutoExtendCookieMinutes(), true,\n\t\t\t\t\ttrue, response);\n\t\t}\n\t\tUser user = result.getUser();\n\t\tsynchronized (AuthControllerExecution.AUTH_LOCK) {\n\t\t\tUserCache userCache = UserCache.getInstance();\n\t\t\tZonedDateTime now = DateTimeUtils.nowMs(user.toTimeZone());\n\t\t\tuser.setLastActive(now);\n\t\t\tuserCache.updateUser(authDb, user);\n\t\t}\n\t\treturn user;\n\t}\n\n\tprivate static ValidateTokenResult getAuthenticatedUser(\n\t\t\tProtocolVersion version, HttpServletRequest request,\n\t\t\tHttpServletResponse response, Database authDb, String project)\n\t\t\tthrows HttpException, Exception {\n\t\tString token = request.getHeader(\"X-Auth-Token\");\n\t\tif (token != null)\n\t\t\treturn validateDefaultToken(token);\n\t\tSSOTokenRepository ssoRepo = AppComponents.get(\n\t\t\t\tSSOTokenRepository.class);\n\t\tfor (SSOToken ssoToken : ssoRepo.getTokens()) {\n\t\t\tif (ssoToken.requestHasToken(request)) {\n\t\t\t\treturn ssoToken.validateToken(version, request, response,\n\t\t\t\t\t\tauthDb, project);\n\t\t\t}\n\t\t}\n\t\ttoken = findAuthTokenCookie(request);\n\t\tif (token != null && !token.isEmpty())\n\t\t\treturn validateDefaultToken(token);\n\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_NOT_FOUND,\n\t\t\t\t\"Authentication token not found\");\n\t}\n\n\tprivate static String findAuthTokenCookie(HttpServletRequest request) {\n\t\tCookie[] cookies = request.getCookies();\n\t\tif (cookies == null)\n\t\t\treturn null;\n\t\tfor (Cookie cookie : cookies) {\n\t\t\tif (cookie.getName().equals(\"authToken\"))\n\t\t\t\treturn cookie.getValue();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Validates a token from request header X-Auth-Token. If it's empty or\n\t * invalid, it will throw an HttpException with 401 Unauthorized. Otherwise\n\t * it will return the user object for the authenticated user.\n\t * \n\t * @param token the authentication token (not null)\n\t * @return the authenticated user\n\t * @throws UnauthorizedException if the token is empty or invalid\n\t */\n\tpublic static ValidateTokenResult validateDefaultToken(String token)\n\t\t\tthrows UnauthorizedException {\n\t\tLogger logger = AppComponents.getLogger(\n\t\t\t\tQueryRunner.class.getSimpleName());\n\t\tif (token.trim().isEmpty()) {\n\t\t\tlogger.info(\"Invalid auth token: Token empty\");\n\t\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_INVALID,\n\t\t\t\t\t\"Authentication token invalid\");\n\t\t}\n\t\tAuthDetails details;\n\t\ttry {\n\t\t\tdetails = AuthToken.parseToken(token);\n\t\t} catch (ExpiredAuthTokenException ex) {\n\t\t\tlogger.info(\"Expired auth token: \" + ex.getMessage());\n\t\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_EXPIRED,\n\t\t\t\t\t\"Authentication token expired\");\n\t\t} catch (InvalidAuthTokenException ex) {\n\t\t\tlogger.info(\"Invalid auth token: \" + ex.getMessage());\n\t\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_INVALID,\n\t\t\t\t\t\"Authentication token invalid\");\n\t\t}\n\t\tUserCache userCache = UserCache.getInstance();\n\t\tString userid;\n\t\tUser user;\n\t\tif (details.getUserid() != null) {\n\t\t\tuserid = details.getUserid();\n\t\t\tuser = userCache.findByUserid(details.getUserid());\n\t\t} else {\n\t\t\tuserid = details.getEmail();\n\t\t\tuser = userCache.findByEmail(details.getEmail());\n\t\t}\n\t\tif (user == null) {\n\t\t\tlogger.info(\"Invalid auth token: User not found: \" + userid);\n\t\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_INVALID,\n\t\t\t\t\t\"Authentication token invalid\");\n\t\t}\n\t\tlong now = System.currentTimeMillis();\n\t\tif (details.getExpiration() != null &&\n\t\t\t\tdetails.getExpiration().getTime() < now) {\n\t\t\tZonedDateTime time = ZonedDateTime.ofInstant(\n\t\t\t\t\tdetails.getExpiration().toInstant(),\n\t\t\t\t\tZoneId.systemDefault());\n\t\t\tlogger.info(\"Expired auth token: \" + time.format(\n\t\t\t\t\tDateTimeUtils.ZONED_FORMAT));\n\t\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_EXPIRED,\n\t\t\t\t\t\"Authentication token expired\");\n\t\t}\n\t\tif (!AuthDetails.hashSalt(user.getSalt()).equals(details.getHash())) {\n\t\t\tlogger.info(\"Invalid auth token: Invalid salt hash\");\n\t\t\tthrow new UnauthorizedException(ErrorCode.AUTH_TOKEN_INVALID,\n\t\t\t\t\t\"Authentication token invalid\");\n\t\t}\n\t\treturn new ValidateTokenResult(user, details);\n\t}\n}" }, { "identifier": "HttpException", "path": "SenSeeActServiceLib/src/main/java/nl/rrd/senseeact/service/exception/HttpException.java", "snippet": "public abstract class HttpException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate HttpError error;\n\n\t/**\n\t * Constructs a new HTTP exception with default error code 0.\n\t * \n\t * @param message the error message\n\t */\n\tpublic HttpException(String message) {\n\t\tsuper(message);\n\t\terror = new HttpError(null, message);\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP exception.\n\t * \n\t * @param code the error code (default null)\n\t * @param message the error message\n\t */\n\tpublic HttpException(String code, String message) {\n\t\tsuper(message);\n\t\terror = new HttpError(code, message);\n\t}\n\t\n\t/**\n\t * Constructs a new HTTP exception with the specified error.\n\t * \n\t * @param error the error\n\t */\n\tpublic HttpException(HttpError error) {\n\t\tsuper(error.getMessage());\n\t\tthis.error = error;\n\t}\n\n\t/**\n\t * Returns the error details.\n\t * \n\t * @return the error details\n\t */\n\tpublic HttpError getError() {\n\t\treturn error;\n\t}\n\t\n\t/**\n\t * Returns the HTTP exception for the specified HTTP status code.\n\t * Unsupported status codes will be mapped to an {@link\n\t * InternalServerErrorException InternalServerErrorException}.\n\t * \n\t * @param statusCode the HTTP status code\n\t * @param error the error details\n\t * @return the HTTP exception\n\t */\n\tpublic static HttpException forStatus(int statusCode, HttpError error) {\n\t\tswitch (statusCode) {\n\t\tcase 400:\n\t\t\treturn new BadRequestException(error);\n\t\tcase 401:\n\t\t\treturn new UnauthorizedException(error);\n\t\tcase 403:\n\t\t\treturn new ForbiddenException(error);\n\t\tcase 404:\n\t\t\treturn new NotFoundException(error);\n\t\tcase 501:\n\t\t\treturn new NotImplementedException(error);\n\t\tdefault:\n\t\t\treturn new InternalServerErrorException(error);\n\t\t}\n\t}\n}" }, { "identifier": "PermissionRecord", "path": "SenSeeActService/src/main/java/nl/rrd/senseeact/service/model/PermissionRecord.java", "snippet": "public class PermissionRecord extends AbstractDatabaseObject {\n\t/**\n\t * This permission allows users to write records to a project table without\n\t * a user field. This kind of tables is used for general project resources.\n\t * Parameters:\n\t *\n\t * - project: project code\n\t * - table: table name (wildcard * for all tables)\n\t */\n\tpublic static final String PERMISSION_WRITE_RESOURCE_TABLE =\n\t\t\t\"write_resource_table\";\n\n\tpublic static final List<String> PERMISSIONS = List.of(\n\t\t\tPERMISSION_WRITE_RESOURCE_TABLE\n\t);\n\n\t@DatabaseField(value=DatabaseType.STRING, index=true)\n\tprivate String user;\n\t@DatabaseField(value=DatabaseType.STRING)\n\tprivate String permission;\n\n\t// JSON code for paramsMap\n\t@DatabaseField(value=DatabaseType.TEXT, json=true)\n\tprivate String params;\n\n\tprivate Map<String,Object> paramsMap = new LinkedHashMap<>();\n\n\tpublic String getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(String user) {\n\t\tthis.user = user;\n\t}\n\n\tpublic String getPermission() {\n\t\treturn permission;\n\t}\n\n\tpublic void setPermission(String permission) {\n\t\tthis.permission = permission;\n\t}\n\n\tpublic String getParams() {\n\t\treturn JsonMapper.generate(paramsMap);\n\t}\n\n\tpublic void setParams(String params) throws ParseException {\n\t\tparamsMap = JsonMapper.parse(params, new TypeReference<>() {});\n\t}\n\n\tpublic Map<String,Object> getParamsMap() {\n\t\treturn paramsMap;\n\t}\n\n\tpublic void setParamsMap(Map<String,Object> paramsMap) {\n\t\tthis.paramsMap = paramsMap;\n\t}\n}" } ]
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.parameters.RequestBody; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.rrd.senseeact.client.model.ProjectDataModule; import nl.rrd.senseeact.client.model.ProjectUserAccessRule; import nl.rrd.senseeact.service.QueryRunner; import nl.rrd.senseeact.service.exception.HttpException; import nl.rrd.senseeact.service.model.PermissionRecord; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map;
5,569
package nl.rrd.senseeact.service.controller; @RestController @RequestMapping("/v{version}/access") public class AccessController { private static final Object WRITE_LOCK = new Object(); private AccessControllerExecution exec = new AccessControllerExecution(); @RequestMapping(value="/project/{project}/modules", method=RequestMethod.GET) public List<ProjectDataModule> getModuleList( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @PathVariable("project") String project) throws HttpException, Exception { return QueryRunner.runProjectQuery( (version, authDb, projectDb, user, srvProject) -> exec.getModuleList(project), versionName, project, request, response); } @RequestMapping(value="/project/{project}/grantee/list", method=RequestMethod.GET)
package nl.rrd.senseeact.service.controller; @RestController @RequestMapping("/v{version}/access") public class AccessController { private static final Object WRITE_LOCK = new Object(); private AccessControllerExecution exec = new AccessControllerExecution(); @RequestMapping(value="/project/{project}/modules", method=RequestMethod.GET) public List<ProjectDataModule> getModuleList( HttpServletRequest request, HttpServletResponse response, @PathVariable("version") @Parameter(hidden = true) String versionName, @PathVariable("project") String project) throws HttpException, Exception { return QueryRunner.runProjectQuery( (version, authDb, projectDb, user, srvProject) -> exec.getModuleList(project), versionName, project, request, response); } @RequestMapping(value="/project/{project}/grantee/list", method=RequestMethod.GET)
public List<ProjectUserAccessRule> getGranteeList(
1
2023-10-24 09:36:50+00:00
8k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/auton/Auton.java
[ { "identifier": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Training training;\n\n public static Swerve swerve;\n public static Intake intake;\n public static Slide slide;\n public static LEDs leds;\n public static Pilot pilot;\n // public static Auton auton;\n\n /**\n * This method cancels all commands and returns subsystems to their default commands and the\n * gamepad configs are reset so that new bindings can be assigned based on mode This method\n * should be called when each mode is intialized\n */\n public static void resetCommandsAndButtons() {\n CommandScheduler.getInstance().cancelAll(); // Disable any currently running commands\n CommandScheduler.getInstance().getActiveButtonLoop().clear();\n\n // Reset Config for all gamepads and other button bindings\n pilot.resetConfig();\n }\n\n /* ROBOT INIT (Initialization) */\n /** This method is called once when the robot is first powered on. */\n public void robotInit() {\n try {\n RobotTelemetry.print(\"--- Robot Init Starting ---\");\n\n /** Set up the config */\n config = new RobotConfig();\n\n /**\n * Intialize the Subsystems of the robot. Subsystems are how we divide up the robot\n * code. Anything with an output that needs to be independently controlled is a\n * subsystem Something that don't have an output are alos subsystems.\n */\n training = new Training();\n swerve = new Swerve();\n intake = new Intake(config.intakeAttached);\n slide = new Slide(true);\n pilot = new Pilot();\n leds = new LEDs();\n\n /** Intialize Telemetry and Auton */\n telemetry = new RobotTelemetry();\n // auton = new Auton();\n advantageKitInit();\n\n /**\n * Set Default Commands this method should exist for each subsystem that has default\n * command these must be done after all the subsystems are intialized\n */\n TrainingCommands.setupDefaultCommand();\n SwerveCommands.setupDefaultCommand();\n IntakeCommands.setupDefaultCommand();\n SlideCommands.setupDefaultCommand();\n LEDsCommands.setupDefaultCommand();\n PilotCommands.setupDefaultCommand();\n\n RobotTelemetry.print(\"--- Robot Init Complete ---\");\n } catch (Throwable t) {\n // intercept error and log it\n CrashTracker.logThrowableCrash(t);\n throw t;\n }\n }\n\n /* ROBOT PERIODIC */\n /**\n * This method is called periodically the entire time the robot is running. Periodic methods are\n * called every 20 ms (50 times per second) by default Since the robot software is always\n * looping you shouldn't pause the execution of the robot code This ensures that new values are\n * updated from the gamepads and sent to the motors\n */\n public void robotPeriodic() {\n try {\n /**\n * Runs the Scheduler. This is responsible for polling buttons, adding newly-scheduled\n * commands, running already-scheduled commands, removing finished or interrupted commands,\n * and running subsystem periodic() methods. This must be called from the robot's periodic\n * block in order for anything in the Command-based framework to work.\n */\n CommandScheduler.getInstance().run();\n } catch (Throwable t) {\n // intercept error and log it\n CrashTracker.logThrowableCrash(t);\n throw t;\n }\n\n }\n\n /* DISABLED MODE */\n /** This mode is run when the robot is disabled All motor/accuator outputs are turned off */\n\n /** This method is called once when disabled starts */\n public void disabledInit() {\n RobotTelemetry.print(\"### Disabled Init Starting ### \");\n\n resetCommandsAndButtons();\n\n RobotTelemetry.print(\"### Disabled Init Complete ### \");\n }\n\n /** This method is called periodically while disabled. */\n public void disabledPeriodic() {}\n\n /** This method is called once when disabled exits */\n public void disabledExit() {\n RobotTelemetry.print(\"### Disabled Exit### \");\n }\n\n /* AUTONOMOUS MODE (AUTO) */\n /**\n * This mode is run when the DriverStation Software is set to autonomous and enabled. In this\n * mode the robot is not able to read values from the gamepads\n */\n\n /** This method is called once when autonomous starts */\n public void autonomousInit() {\n try {\n RobotTelemetry.print(\"@@@ Auton Init Starting @@@ \");\n resetCommandsAndButtons();\n\n RobotTelemetry.print(\"@@@ Auton Init Complete @@@ \");\n } catch (Throwable t) {\n // intercept error and log it\n CrashTracker.logThrowableCrash(t);\n throw t;\n }\n }\n\n /** This method is called periodically during autonomous. */\n public void autonomousPeriodic() {\n }\n\n /** This method is called once when autonomous exits */\n public void autonomousExit() {\n RobotTelemetry.print(\"@@@ Auton Exit @@@ \");\n }\n\n /* TELEOP MODE */\n /**\n * This mode is run when the DriverStation Software is set to teleop and enabled. In this mode\n * the robot is fully enabled and can move it's outputs and read values from the gamepads\n */\n\n /** This method is called once when teleop starts */\n public void teleopInit() {\n try {\n RobotTelemetry.print(\"!!! Teleop Init Starting !!! \");\n resetCommandsAndButtons();\n\n RobotTelemetry.print(\"!!! Teleop Init Complete !!! \");\n } catch (Throwable t) {\n // intercept error and log it\n CrashTracker.logThrowableCrash(t);\n throw t;\n }\n\n }\n\n /** This method is called periodically during operator control. */\n public void teleopPeriodic() {}\n\n /** This method is called once when teleop exits */\n public void teleopExit() {\n RobotTelemetry.print(\"!!! Teleop Exit !!! \");\n }\n\n /* TEST MODE */\n /**\n * This mode is run when the DriverStation Software is set to test and enabled. In this mode the\n * is fully enabled and can move it's outputs and read values from the gamepads. This mode is\n * never enabled by the competition field It can be used to test specific features or modes of\n * the robot\n */\n\n /** This method is called once when test mode starts */\n public void testInit() {\n try {\n RobotTelemetry.print(\"~~~ Test Init Starting ~~~ \");\n resetCommandsAndButtons();\n\n RobotTelemetry.print(\"~~~ Test Init Complete ~~~ \");\n } catch (Throwable t) {\n // intercept error and log it\n CrashTracker.logThrowableCrash(t);\n throw t;\n }\n }\n\n /** This method is called periodically during test. */\n public void testPeriodic() {}\n\n /** This method is called once when the robot exits test mode */\n public void testExit() {\n RobotTelemetry.print(\"~~~ Test Exit ~~~ \");\n }\n\n /* SIMULATION MODE */\n /**\n * This mode is run when the software is running in simulation and not on an actual robot. This\n * mode is never enabled by the competition field\n */\n\n /** This method is called once when a simulation starts */\n public void simulationInit() {\n RobotTelemetry.print(\"$$$ Simulation Init Starting $$$ \");\n\n RobotTelemetry.print(\"$$$ Simulation Init Complete $$$ \");\n }\n\n /** This method is called periodically during simulation. */\n public void simulationPeriodic() {}\n\n /** This method is called once at the end of RobotInit to begin logging */\n public void advantageKitInit() {\n // Set up data receivers & replay source\n switch (Robot.config.getRobotType()) {\n case SIM:\n // Running a physics simulator, log to NT\n Logger.addDataReceiver(new NT4Publisher());\n break;\n\n default:\n // Running on a real robot, log to a USB stick\n Logger.addDataReceiver(new WPILOGWriter(\"/U\"));\n Logger.addDataReceiver(new NT4Publisher());\n break;\n }\n\n // Start AdvantageKit logger\n Logger.start();\n }\n}" }, { "identifier": "RobotTelemetry", "path": "src/main/java/frc/robot/RobotTelemetry.java", "snippet": "public class RobotTelemetry extends Telemetry {\n\n /* What to publish over networktables for telemetry */\n NetworkTableInstance inst = NetworkTableInstance.getDefault();\n\n /* Robot pose for field positioning */\n NetworkTable table = inst.getTable(\"Pose\");\n DoubleArrayPublisher fieldPub = table.getDoubleArrayTopic(\"robotPose\").publish();\n StringPublisher fieldTypePub = table.getStringTopic(\".type\").publish();\n\n /* Robot speeds for general checking */\n NetworkTable driveStats = inst.getTable(\"Drive\");\n DoublePublisher velocityX = driveStats.getDoubleTopic(\"Velocity X\").publish();\n DoublePublisher velocityY = driveStats.getDoubleTopic(\"Velocity Y\").publish();\n DoublePublisher speed = driveStats.getDoubleTopic(\"Speed\").publish();\n DoublePublisher odomPeriod = driveStats.getDoubleTopic(\"Odometry Period\").publish();\n\n /* Keep a reference of the last pose to calculate the speeds */\n Pose2d m_lastPose = new Pose2d();\n double lastTime = Utils.getCurrentTimeSeconds();\n\n /* Mechanisms to represent the swerve module states */\n Mechanism2d[] m_moduleMechanisms =\n new Mechanism2d[] {\n new Mechanism2d(1, 1),\n new Mechanism2d(1, 1),\n new Mechanism2d(1, 1),\n new Mechanism2d(1, 1),\n };\n /* A direction and length changing ligament for speed representation */\n MechanismLigament2d[] m_moduleSpeeds =\n new MechanismLigament2d[] {\n m_moduleMechanisms[0]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n m_moduleMechanisms[1]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n m_moduleMechanisms[2]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n m_moduleMechanisms[3]\n .getRoot(\"RootSpeed\", 0.5, 0.5)\n .append(new MechanismLigament2d(\"Speed\", 0.5, 0)),\n };\n /* A direction changing and length constant ligament for module direction */\n MechanismLigament2d[] m_moduleDirections =\n new MechanismLigament2d[] {\n m_moduleMechanisms[0]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n m_moduleMechanisms[1]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n m_moduleMechanisms[2]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n m_moduleMechanisms[3]\n .getRoot(\"RootDirection\", 0.5, 0.5)\n .append(\n new MechanismLigament2d(\n \"Direction\", 0.1, 0, 0, new Color8Bit(Color.kWhite))),\n };\n\n public RobotTelemetry() {\n super();\n Logger.recordMetadata(\"RobotType\", Robot.config.getRobotType().name());\n\n Robot.swerve.registerTelemetry((b) -> telemeterize(b));\n }\n\n /* Accept the swerve drive state and telemeterize it to smartdashboard */\n public void telemeterize(DriveState state) {\n /* Telemeterize the pose */\n Pose2d pose = state.Pose;\n fieldTypePub.set(\"Field2d\");\n fieldPub.set(new double[] {pose.getX(), pose.getY(), pose.getRotation().getDegrees()});\n\n /* Telemeterize the robot's general speeds */\n double currentTime = Utils.getCurrentTimeSeconds();\n double diffTime = currentTime - lastTime;\n lastTime = currentTime;\n Translation2d distanceDiff = pose.minus(m_lastPose).getTranslation();\n m_lastPose = pose;\n\n Translation2d velocities = distanceDiff.div(diffTime);\n\n speed.set(velocities.getNorm());\n velocityX.set(velocities.getX());\n velocityY.set(velocities.getY());\n odomPeriod.set(state.OdometryPeriod);\n\n /* Telemeterize the module's states */\n for (int i = 0; i < 4; ++i) {\n m_moduleSpeeds[i].setAngle(state.ModuleStates[i].angle);\n m_moduleDirections[i].setAngle(state.ModuleStates[i].angle);\n m_moduleSpeeds[i].setLength(state.ModuleStates[i].speedMetersPerSecond / (2 * 6));\n\n SmartDashboard.putData(\"Module \" + i, m_moduleMechanisms[i]);\n }\n }\n}" }, { "identifier": "AutoBalance", "path": "src/main/java/frc/robot/auton/commands/AutoBalance.java", "snippet": "public class AutoBalance extends Command {\n public double currentAngle = 100;\n private double currentRate = 100;\n private double angleOffset;\n private boolean shouldDrive;\n Command driveCommand;\n\n public AutoBalance() {\n addRequirements(Robot.swerve);\n }\n\n @Override\n public void initialize() {}\n\n @Override\n public void execute() {}\n\n private double driveSpeed() {\n return 0;\n }\n\n private double currentAngle() {\n return 0;\n }\n\n @Override\n public void end(boolean interrupted) {}\n\n @Override\n public boolean isFinished() {\n return false;\n }\n}" }, { "identifier": "AutonConfig", "path": "src/main/java/frc/robot/auton/config/AutonConfig.java", "snippet": "public class AutonConfig {\n // TODO: #1 @EDPendleton24: The PID constants have to be different for Translation and Rotation\n public static final double kP = 5.0;\n public static final double kI = 0.0;\n public static final double kD = 0.0;\n public static final double maxModuleSpeed = 4.5;\n public static final double driveBaseRadius = 0.4;\n\n public static HolonomicPathFollowerConfig AutonPathFollowerConfig =\n new HolonomicPathFollowerConfig( // HolonomicPathFollowerConfig, this should likely\n // live in your Constants class\n new PIDConstants(kP, kI, kD), // Translation PID constants\n new PIDConstants(kP, kI, kD), // Rotation PID constants\n maxModuleSpeed, // Max module speed, in m/s\n driveBaseRadius, // Drive base radius in meters. Distance from robot center to\n // furthest module.\n new ReplanningConfig() // Default path replanning config. See the API for\n // the options here\n );\n}" }, { "identifier": "ApplyChassisSpeeds", "path": "src/main/java/frc/robot/swerve/commands/ApplyChassisSpeeds.java", "snippet": "public class ApplyChassisSpeeds implements Request {\n\n public static Command run(Supplier<ChassisSpeeds> speeds, BooleanSupplier isOpenLoop) {\n return Robot.swerve.applyRequest(\n () ->\n new ApplyChassisSpeeds()\n .withSpeeds(speeds.get())\n .withIsOpenLoop(isOpenLoop.getAsBoolean()));\n }\n\n public static Consumer<ChassisSpeeds> robotRelativeOutput(boolean isOpenLoop) {\n return (speeds) ->\n Robot.swerve.setControlMode(\n new ApplyChassisSpeeds().withIsOpenLoop(isOpenLoop).withSpeeds(speeds));\n }\n\n /** The chassis speeds to apply to the drivetrain. */\n public ChassisSpeeds Speeds = new ChassisSpeeds();\n /** The center of rotation to rotate around. */\n public Translation2d CenterOfRotation = new Translation2d(0, 0);\n /** True to use open-loop control while stopped. */\n public boolean IsOpenLoop = false;\n\n public StatusCode apply(ControlRequestParameters parameters, Module... modulesToApply) {\n SwerveModuleState[] states =\n parameters.kinematics.toSwerveModuleStates(Speeds, CenterOfRotation);\n Robot.swerve.writeSetpoints(states);\n for (int i = 0; i < modulesToApply.length; ++i) {\n modulesToApply[i].apply(states[i], IsOpenLoop);\n }\n\n return StatusCode.OK;\n }\n\n public ApplyChassisSpeeds withSpeeds(ChassisSpeeds speeds) {\n this.Speeds = speeds;\n return this;\n }\n\n public ApplyChassisSpeeds withCenterOfRotation(Translation2d centerOfRotation) {\n this.CenterOfRotation = centerOfRotation;\n return this;\n }\n\n public ApplyChassisSpeeds withIsOpenLoop(boolean isOpenLoop) {\n this.IsOpenLoop = isOpenLoop;\n return this;\n }\n}" } ]
import com.pathplanner.lib.auto.AutoBuilder; import com.pathplanner.lib.auto.NamedCommands; import com.pathplanner.lib.commands.PathPlannerAuto; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.PrintCommand; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Robot; import frc.robot.RobotTelemetry; import frc.robot.auton.commands.AutoBalance; import frc.robot.auton.config.AutonConfig; import frc.robot.swerve.commands.ApplyChassisSpeeds;
4,776
package frc.robot.auton; public class Auton extends SubsystemBase { public static final SendableChooser<Command> autonChooser = new SendableChooser<>(); private static boolean autoMessagePrinted = true; private static double autonStart = 0; // A chooser for autonomous commands public static void setupSelectors() { autonChooser.setDefaultOption("Clean Side 3", new PathPlannerAuto("Clean Side 3")); // autonChooser.addOption("Clean3", AutoPaths.CleanSide()); } // Setup the named commands public static void setupNamedCommands() { // Register Named Commands NamedCommands.registerCommand("autoBalance", new AutoBalance()); } // Subsystem Documentation: // https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems.html public Auton() { configureAutoBuilder(); // configures the auto builder setupNamedCommands(); // registers named commands setupSelectors(); // runs the command to start the chooser for auto on shuffleboard RobotTelemetry.print("Auton Subsystem Initialized: "); } // Configures the auto builder to use to run autons public static void configureAutoBuilder() { // Configure the AutoBuilder last AutoBuilder.configureHolonomic( Robot.swerve::getPose, // Robot pose supplier Robot.swerve ::resetPose, // Method to reset odometry (will be called if your auto has a // starting pose) Robot.swerve ::getRobotRelativeSpeeds, // ChassisSpeeds supplier. MUST BE ROBOT RELATIVE
package frc.robot.auton; public class Auton extends SubsystemBase { public static final SendableChooser<Command> autonChooser = new SendableChooser<>(); private static boolean autoMessagePrinted = true; private static double autonStart = 0; // A chooser for autonomous commands public static void setupSelectors() { autonChooser.setDefaultOption("Clean Side 3", new PathPlannerAuto("Clean Side 3")); // autonChooser.addOption("Clean3", AutoPaths.CleanSide()); } // Setup the named commands public static void setupNamedCommands() { // Register Named Commands NamedCommands.registerCommand("autoBalance", new AutoBalance()); } // Subsystem Documentation: // https://docs.wpilib.org/en/stable/docs/software/commandbased/subsystems.html public Auton() { configureAutoBuilder(); // configures the auto builder setupNamedCommands(); // registers named commands setupSelectors(); // runs the command to start the chooser for auto on shuffleboard RobotTelemetry.print("Auton Subsystem Initialized: "); } // Configures the auto builder to use to run autons public static void configureAutoBuilder() { // Configure the AutoBuilder last AutoBuilder.configureHolonomic( Robot.swerve::getPose, // Robot pose supplier Robot.swerve ::resetPose, // Method to reset odometry (will be called if your auto has a // starting pose) Robot.swerve ::getRobotRelativeSpeeds, // ChassisSpeeds supplier. MUST BE ROBOT RELATIVE
ApplyChassisSpeeds.robotRelativeOutput(
4
2023-10-23 17:01:53+00:00
8k
imart302/DulceNectar-BE
src/main/java/com/dulcenectar/java/services/OrderServiceImpl.java
[ { "identifier": "CreateOrderRequestDto", "path": "src/main/java/com/dulcenectar/java/dtos/order/CreateOrderRequestDto.java", "snippet": "public class CreateOrderRequestDto implements RequestDto<Order> {\n\t\n\n\tpublic static class OrderItem {\n\t\tprivate Integer productId;\n\t\tprivate Integer quantity;\n\t\t\n\t\tpublic OrderItem(Integer productId, Integer quantity) {\n\t\t\tsuper();\n\t\t\tthis.productId = productId;\n\t\t\tthis.quantity = quantity;\n\t\t}\n\t\t\n\t\tpublic OrderItem() {}\n\t\t\n\t\tpublic Integer getProductId() {\n\t\t\treturn productId;\n\t\t}\n\t\t\n\t\tpublic void setProductId(Integer productId) {\n\t\t\tthis.productId = productId;\n\t\t}\n\t\t\n\t\tpublic Integer getQuantity() {\n\t\t\treturn quantity;\n\t\t}\n\t\t\n\t\tpublic void setQuantity(Integer quantity) {\n\t\t\tthis.quantity = quantity;\n\t\t}\n\t\t\n\t}\n\n\tprivate Float totalGross;\n\tprivate String address;\n\tprivate List<OrderItem> orderItems;\n\n\tpublic CreateOrderRequestDto(Float totalGross, String address, List<OrderItem> orderItems) {\n\t\tsuper();\n\t\tthis.totalGross = totalGross;\n\t\tthis.address = address;\n\t\tthis.orderItems = orderItems;\n\t}\n\n\tpublic List<OrderItem> getOrderItems() {\n\t\treturn orderItems;\n\t}\n\tpublic CreateOrderRequestDto(){\n\t\tsuper();\n\t}\n\t\n public Float getTotalGross() {\n return totalGross;\n }\n\n public void setTotalGross(Float totalGross) {\n this.totalGross = totalGross;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public Order toEntity() {\n Order order = new Order();\n order.setTotalGross(this.totalGross);\n order.setAddress(this.address);\n return order;\n }\n\n}" }, { "identifier": "GetOrderResponseDto", "path": "src/main/java/com/dulcenectar/java/dtos/order/GetOrderResponseDto.java", "snippet": "public class GetOrderResponseDto implements ResponseDto<Order> {\n\n\tpublic static class OrderItem {\n\t\tprivate Integer productId;\n\t\tprivate long quantity;\n\t\t\n\t\tpublic OrderItem(Integer productId, long quantity) {\n\t\t\tsuper();\n\t\t\tthis.productId = productId;\n\t\t\tthis.quantity = quantity;\n\t\t}\n\t\t\n\t\tpublic OrderItem() {}\n\t\t\n\t\tpublic Integer getProductId() {\n\t\t\treturn productId;\n\t\t}\n\t\t\n\t\tpublic void setProductId(Integer productId) {\n\t\t\tthis.productId = productId;\n\t\t}\n\t\t\n\t\tpublic long getQuantity() {\n\t\t\treturn quantity;\n\t\t}\n\t\t\n\t\tpublic void setQuantity(long quantity) {\n\t\t\tthis.quantity = quantity;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"OrderItem [productId=\" + productId + \", quantity=\" + quantity + \"]\";\n\t\t}\n\t\t\n\t}\n\t\n\tInteger id;\n\tDouble totalGross;\n\tString createdAt;\n\tList<OrderItem> orderItems;\n\t\n\t\n\tpublic GetOrderResponseDto() {\n\t\tsuper();\n\t}\n\n\t@Override\n\tpublic ResponseDto<Order> fromEntity(Order entity) {\n\t\t\n\t\tList<OrderItem> orderItems = entity.getOrderProducts().stream().map((orderProduct) -> {\n\t\t\tOrderItem ot = new OrderItem();\n\t\t\tot.setProductId(orderProduct.getProduct().getId());\n\t\t\tot.setQuantity(orderProduct.getQuantity());\n\t\t\t\n\t\t\treturn ot;\n\t\t}).toList();\n\t\t\n\t\tthis.id = entity.getId();\n\t\tthis.totalGross = entity.getTotalGross();\n\t\tthis.orderItems = orderItems;\n\t\tthis.createdAt = entity.getCreatedAt().format(DateTimeFormatter.ofPattern(\"dd/MM/yyyy HH:mm\"));\n\t\t\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"GetOrderReponseDto [id=\" + id + \", totalGross=\" + totalGross + \", orderItems=\" + orderItems + \"]\";\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Double getTotalGross() {\n\t\treturn totalGross;\n\t}\n\n\tpublic void setTotalGross(Double totalGross) {\n\t\tthis.totalGross = totalGross;\n\t}\n\n\tpublic List<OrderItem> getOrderItems() {\n\t\treturn orderItems;\n\t}\n\n\tpublic void setOrderItems(List<OrderItem> orderItems) {\n\t\tthis.orderItems = orderItems;\n\t}\n\n\tpublic String getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(String createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n}" }, { "identifier": "OrderNotFoundException", "path": "src/main/java/com/dulcenectar/java/exceptions/OrderNotFoundException.java", "snippet": "public class OrderNotFoundException extends RuntimeException {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -8894947839572684859L;\n\n\t\n\tpublic OrderNotFoundException() {\n\t\tsuper(\"No existe esta order\");\n\t}\n\t\n}" }, { "identifier": "Order", "path": "src/main/java/com/dulcenectar/java/models/Order.java", "snippet": "@Entity\n@Table(name = \"orders\")\npublic class Order {\n\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\tprivate Integer id;\n\tprivate Double totalGross;\n\tprivate String address;\n\t@CreationTimestamp\n\tprivate LocalDateTime createdAt;\n\t\n\t@ManyToOne\n\t@JoinColumn(name = \"user_id\")\n\tprivate User user;\n\t\n\t@OneToMany(mappedBy=\"order\", cascade = CascadeType.ALL, orphanRemoval = true)\n\tprivate List<OrderProducts> orderProducts;\n\n\tpublic Order(Integer id, Double totalGross, String address, LocalDateTime createdAt, User user,\n\t\t\tList<OrderProducts> orderProducts) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.totalGross = totalGross;\n\t\tthis.address = address;\n\t\tthis.createdAt = createdAt;\n\t\tthis.user = user;\n\t\tthis.orderProducts = orderProducts;\n\t}\n\t\n\tpublic Order(Integer id) {\n\t\tsuper();\n\t\tthis.id = id;\n\t}\n\n\tpublic Order() {\n\t\tsuper();\n\t}\n\n\tpublic void setId(Integer orderId) {\n\t\tthis.id = orderId;\n\t}\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\n\tpublic double getTotalGross() {\n\t\treturn totalGross;\n\t}\n\n\tpublic void setTotalGross(double totalGross) {\n\t\tthis.totalGross = totalGross;\n\t}\n\n\tpublic String getAddress() {\n\t\treturn address;\n\t}\n\n\tpublic void setAddress(String address) {\n\t\tthis.address = address;\n\t}\n\n\tpublic List<OrderProducts> getOrderProducts() {\n\t\treturn this.orderProducts;\n\t}\n\n\tpublic void setOrderProducts(List<OrderProducts> orderProducts) {\n\t\tthis.orderProducts = orderProducts;\n\t}\n\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic User getUser() {\n\t\treturn user;\n\t}\n\n\tpublic void setUser(User user) {\n\t\tthis.user = user;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Order [id=\" + id + \", totalGross=\" + totalGross + \", address=\" + address + \", createdAt=\" + createdAt\n\t\t\t\t+ \", user=\" + user + \", orderProducts=\" + orderProducts + \"]\";\n\t}\n}" }, { "identifier": "OrderProducts", "path": "src/main/java/com/dulcenectar/java/models/OrderProducts.java", "snippet": "@Entity\n@Table(name = \"order_products\")\npublic class OrderProducts {\n\t\n\t@Embeddable\n\tpublic static class OrderProductId implements Serializable {\n\t\t\n\t\t/**\n\t\t * \n\t\t */\n\t\tprivate static final long serialVersionUID = 1L;\n\t\t@Column(name = \"order_id\")\n\t\tprivate Integer orderId;\n\t\t@Column(name = \"product_id\")\n\t\tprivate Integer productId;\n\t\t\n\t\tpublic OrderProductId(Integer orderId, Integer productId) {\n\t\t\tsuper();\n\t\t\tthis.orderId = orderId;\n\t\t\tthis.productId = productId;\n\t\t}\n\t\t\n\t\tpublic OrderProductId() {\n\t\t\tsuper();\n\t\t}\n\n\t\tpublic Integer getOrderId() {\n\t\t\treturn orderId;\n\t\t}\n\n\t\tpublic void setOrderId(Integer orderId) {\n\t\t\tthis.orderId = orderId;\n\t\t}\n\n\t\tpublic Integer getProductId() {\n\t\t\treturn productId;\n\t\t}\n\n\t\tpublic void setProductId(Integer productId) {\n\t\t\tthis.productId = productId;\n\t\t}\n\t\t\n\t}\n\t\n//\t@Id\n//\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\t\n\t@EmbeddedId\n\tprivate OrderProductId id;\n\tprivate Integer quantity;\n\t\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@MapsId(\"orderId\")\n\t@JoinColumn(name = \"order_id\")\n\tprivate Order order;\n\t\t\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@MapsId(\"productId\")\n\t@JoinColumn(name = \"product_id\")\n\tprivate Product product;\n\n\tpublic OrderProducts(OrderProductId id, Integer quantity, Order order, Product product) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.quantity = quantity;\n\t\tthis.order = order;\n\t\tthis.product = product;\n\t}\n\t\n\tpublic OrderProducts() {\n\t\tsuper();\n\t}\n\n\n\tpublic OrderProductId getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(OrderProductId id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Integer getQuantity() {\n\t\treturn quantity;\n\t}\n\n\tpublic void setQuantity(Integer quantity) {\n\t\tthis.quantity = quantity;\n\t}\n\n\tpublic Order getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(Order order) {\n\t\tthis.order = order;\n\t}\n\n\tpublic Product getProduct() {\n\t\treturn product;\n\t}\n\n\tpublic void setProduct(Product product) {\n\t\tthis.product = product;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"OrderProducts [quantity=\" + quantity + \", product=\" + product + \"]\";\n\t}\n\t\n}" }, { "identifier": "Product", "path": "src/main/java/com/dulcenectar/java/models/Product.java", "snippet": "@Entity\n@Table(name=\"products\")\npublic class Product {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n\tprivate String name;\n\tprivate String info;\n\n\tprivate Float gram;\n\tprivate String imgUrl;\n\tprivate Double price;\n\tprivate Long stock;\n\tprivate String typeGram;\n\t@CreationTimestamp\n\tprivate LocalDateTime createdAt;\n\t@UpdateTimestamp\n\tprivate LocalDateTime updatedAt;\n\n\t\n\t@ManyToOne\n\t@JoinColumn(name=\"category_id\", nullable=false)\n\tprivate Category category;\n/*\n * Quiza este no se necesie, como mencionaan en la clase, Oder no tiene relacion fundamental con las ordenes, mas que nada User es el que usa las orderPoducts\n * @OneToMany(mappedBy = \"Product\")\n * Private Set<OrderProducts> orderProduct;\n * \n */\n\n/*\n * Aqui, EN el conolador de reviews ya hay un et rEviews, se necesiaia aqui?`\n * El frontEnd no usa ninguna paina que muestre los reviews de un producto, pero tiene una seccion con todas las reviews\n * En esa seccion se haía un filtro\n * @OneToMany(mappedBy = \"Product\")\n * Private Set<Review> = reviewsList;\n * \n */\n\n\n\t\n\n\n\tpublic Product(Integer id, String name, String info, Float gram, String imgUrl, Double price,\n\t\t\tLong stock, String typeGram, LocalDateTime createdAt, LocalDateTime updatedAt, Category category) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.info = info;\n\t\tthis.gram = gram;\n\t\tthis.imgUrl = imgUrl;\n\t\tthis.price = price;\n\t\tthis.stock = stock;\n\t\tthis.typeGram = typeGram;\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t\tthis.category = category;\n\t}\n\t\n\tpublic Product(Integer id) {\n\t\tthis.id = id;\n\t}\n\t\n\tpublic Product() {\n\t\t\n\t}\n\n\tpublic Integer getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Integer id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getInfo() {\n\t\treturn info;\n\t}\n\n\tpublic void setInfo(String info) {\n\t\tthis.info = info;\n\t}\n\n\tpublic Float getGram() {\n\t\treturn gram;\n\t}\n\n\tpublic void setGram(Float gram) {\n\t\tthis.gram = gram;\n\t}\n\n\tpublic String getImgUrl() {\n\t\treturn imgUrl;\n\t}\n\n\tpublic void setImgUrl(String imgUrl) {\n\t\tthis.imgUrl = imgUrl;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic Long getStock() {\n\t\treturn stock;\n\t}\n\n\tpublic void setStock(Long stock) {\n\t\tthis.stock = stock;\n\t}\n\n\tpublic String getTypeGram() {\n\t\treturn typeGram;\n\t}\n\n\tpublic void setTypeGram(String typeGram) {\n\t\tthis.typeGram = typeGram;\n\t}\n\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\tpublic LocalDateTime getUpdatedAt() {\n\t\treturn updatedAt;\n\t}\n\n\tpublic void setUpdatedAt(LocalDateTime updatedAt) {\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Product [id=\" + id + \", name=\" + name + \", info=\" + info + \", gram=\" + gram\n\t\t\t\t+ \", imgUrl=\" + imgUrl + \", price=\" + price + \", stock=\" + stock + \", typeGram=\" + typeGram\n\t\t\t\t+ \", createdAt=\" + createdAt + \", updatedAt=\" + updatedAt + \"]\";\n\t}\n}" }, { "identifier": "OrderProductsRepository", "path": "src/main/java/com/dulcenectar/java/repositories/OrderProductsRepository.java", "snippet": "public interface OrderProductsRepository extends CrudRepository <OrderProducts, Integer> {\n\n}" }, { "identifier": "OrderRepository", "path": "src/main/java/com/dulcenectar/java/repositories/OrderRepository.java", "snippet": "public interface OrderRepository extends CrudRepository<Order, Integer> {\n\n\tList<Order> findAllByUserId(Integer userId);\n\tboolean existsById(Long orderId);\n // Puedes agregar consultas personalizadas si es necesario\n}" }, { "identifier": "UserDetailsImpl", "path": "src/main/java/com/dulcenectar/java/security/UserDetailsImpl.java", "snippet": "public class UserDetailsImpl extends User implements UserDetails {\n\t\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = -1833377617454173091L;\n\t\n\tpublic UserDetailsImpl() {\n\t\tsuper();\n\t}\n\n\tpublic UserDetailsImpl(Integer id, String firstName, String lastName, String email, String password, Role role,\n\t\t\tLocalDateTime createdAt, LocalDateTime updatedAt) {\n\t\tsuper(id, firstName, lastName, email, password, role, createdAt, updatedAt);\n\t}\n\n\tpublic UserDetailsImpl(Integer id, String firstName, String lastName, String email, String password) {\n\t\tsuper(id, firstName, lastName, email, password);\n\t}\n\n\tpublic UserDetailsImpl(Integer id) {\n\t\tsuper(id);\n\t}\n\n\t@Override\n\tpublic Collection<? extends GrantedAuthority> getAuthorities() {\n\t\treturn List.of(new SimpleGrantedAuthority((role.name())));\n\t}\n\n\t@Override\n\tpublic String getPassword() {\n\t\treturn this.getPassword();\n\t}\n\n\t@Override\n\tpublic String getUsername() {\n\t\treturn email;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonExpired() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isAccountNonLocked() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isCredentialsNonExpired() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isEnabled() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"UserDetailsImpl [id=\" + id + \", email=\" + email + \", password=\" + password + \", role=\" + role + \"]\";\n\t}\n\t\n}" }, { "identifier": "OrderService", "path": "src/main/java/com/dulcenectar/java/services/interfaces/OrderService.java", "snippet": "public interface OrderService {\n\tpublic Integer createNewOrder(CreateOrderRequestDto order);\n\tpublic List<GetOrderResponseDto> getOrders();\n\tpublic String deleteOrder(Integer orderId);\n}" } ]
import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import com.dulcenectar.java.dtos.order.CreateOrderRequestDto; import com.dulcenectar.java.dtos.order.GetOrderResponseDto; import com.dulcenectar.java.exceptions.OrderNotFoundException; import com.dulcenectar.java.models.Order; import com.dulcenectar.java.models.OrderProducts; import com.dulcenectar.java.models.Product; import com.dulcenectar.java.repositories.OrderProductsRepository; import com.dulcenectar.java.repositories.OrderRepository; import com.dulcenectar.java.security.UserDetailsImpl; import com.dulcenectar.java.services.interfaces.OrderService;
4,640
package com.dulcenectar.java.services; @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderRepository orderRepository; private final OrderProductsRepository orderProductsRepository; public OrderServiceImpl(OrderRepository orderRepository, OrderProductsRepository orderProductsRepository) { super(); this.orderRepository = orderRepository; this.orderProductsRepository = orderProductsRepository; } public Integer createNewOrder(CreateOrderRequestDto order) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl user = (UserDetailsImpl)authentication.getPrincipal(); List<CreateOrderRequestDto.OrderItem> orderItems = order.getOrderItems(); Order orderEntity = new Order(); orderEntity.setUser(user); orderEntity.setAddress(order.getAddress()); orderEntity.setTotalGross(order.getTotalGross()); Order savedOrder = this.orderRepository.save(orderEntity); List<OrderProducts> orderProductList = orderItems.stream().map((item) -> { OrderProducts op = new OrderProducts(); op.setOrder(savedOrder); op.setQuantity(item.getQuantity()); op.setProduct(new Product(item.getProductId())); op.setId(new OrderProducts.OrderProductId(savedOrder.getId(), item.getProductId())); return op; }).toList(); this.orderProductsRepository.saveAll(orderProductList); return savedOrder.getId(); }
package com.dulcenectar.java.services; @Service public class OrderServiceImpl implements OrderService { @Autowired private OrderRepository orderRepository; private final OrderProductsRepository orderProductsRepository; public OrderServiceImpl(OrderRepository orderRepository, OrderProductsRepository orderProductsRepository) { super(); this.orderRepository = orderRepository; this.orderProductsRepository = orderProductsRepository; } public Integer createNewOrder(CreateOrderRequestDto order) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl user = (UserDetailsImpl)authentication.getPrincipal(); List<CreateOrderRequestDto.OrderItem> orderItems = order.getOrderItems(); Order orderEntity = new Order(); orderEntity.setUser(user); orderEntity.setAddress(order.getAddress()); orderEntity.setTotalGross(order.getTotalGross()); Order savedOrder = this.orderRepository.save(orderEntity); List<OrderProducts> orderProductList = orderItems.stream().map((item) -> { OrderProducts op = new OrderProducts(); op.setOrder(savedOrder); op.setQuantity(item.getQuantity()); op.setProduct(new Product(item.getProductId())); op.setId(new OrderProducts.OrderProductId(savedOrder.getId(), item.getProductId())); return op; }).toList(); this.orderProductsRepository.saveAll(orderProductList); return savedOrder.getId(); }
public List<GetOrderResponseDto> getOrders() {
1
2023-10-24 00:07:39+00:00
8k
DaveScott99/ToyStore-JSP
src/main/java/br/com/toyStore/servlet/Servlet.java
[ { "identifier": "CategoryDAO", "path": "src/main/java/br/com/toyStore/dao/CategoryDAO.java", "snippet": "public class CategoryDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate Category category;\n\n\tpublic CategoryDAO(Connection conn) {\n\t\tthis.conn = conn;\n\t}\n\n\tpublic void insert(Category category) {\n\t\ttry {\n\t\t\tif (category != null) {\n\t\t\t\tString SQL = \"INSERT INTO TOY_STORE.CATEGORY (NAME_CATEGORY, IMAGE_NAME_CATEGORY) values (?, ?)\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, category.getName());\n\t\t\t\tps.setString(2, category.getImageName());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao inserir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void update(Category category) {\n\t\ttry {\n\t\t\tif (category != null) {\n\t\t\t\tString SQL = \"UPDATE alunos set nome=?, email=?, endereco=?, datanascimento=?, \"\n\t\t\t\t\t\t+ \"periodo=? WHERE ra=?\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\t//ps.setString(1, aluno.getNome());\n\t\t\t\t//ps.setString(2, aluno.getEmail());\n\t\t\t\t//ps.setString(3, aluno.getEndereco());\n\t\t\t\t//ps.setDate(4, new java.sql.Date(aluno.getDataNascimento().getTime()));\n\t\t\t\t//ps.setString(5, aluno.getPeriodo());\n\t\t\t\t//ps.setInt(6, aluno.getRa());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao alterar dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void delete(Integer idCategory) {\n\t\ttry {\n\t\t\tString SQL = \"DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idCategory);\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao excluir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic Category findByName(String idCategory) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.CATEGORY AS CAT WHERE CAT.NAME_CATEGORY =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setString(1, idCategory);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_category\");\n\t\t\t\tString name = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\t\t\t\t\n\t\t\t\tcategory = new Category();\n\t\t\t\tcategory.setId(id);\n\t\t\t\tcategory.setName(name);\n\t\t\t\tcategory.setImageName(imageCategory);\n\t\t\t\n\t\t\t}\n\t\t\treturn category;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic Category findById(int idCategory) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.CATEGORY AS CAT WHERE CAT.ID_CATEGORY =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idCategory);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_category\");\n\t\t\t\tString name = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\n\t\t\t\tcategory = new Category();\n\t\t\t\tcategory.setId(id);\n\t\t\t\tcategory.setName(name);\n\t\t\t\tcategory.setImageName(imageCategory);\n\t\t\t}\n\t\t\treturn category;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic List<Category> findAll() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.CATEGORY AS CAT ORDER BY CAT.NAME_CATEGORY\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Category> list = new ArrayList<Category>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_category\");\n\t\t\t\tString name = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\n\t\t\t\tcategory = new Category();\n\t\t\t\tcategory.setId(id);\n\t\t\t\tcategory.setName(name);\n\t\t\t\tcategory.setImageName(imageCategory);\n\n\t\t\t\tlist.add(category);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n}" }, { "identifier": "ProductDAO", "path": "src/main/java/br/com/toyStore/dao/ProductDAO.java", "snippet": "public class ProductDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate Product product;\n\n\tpublic ProductDAO(Connection conn) {\n\t\tthis.conn = conn;\n\t}\n\n\tpublic void insert(Product product) {\n\t\ttry {\n\t\t\tif (product != null) {\n\t\t\t\tString SQL = \"INSERT INTO TOY_STORE.PRODUCT (NAME_PRODUCT, PRICE_PRODUCT, DESCRIPTION_PRODUCT, IMAGE_NAME_PRODUCT, BRAND_PRODUCT, ID_CATEGORY) values \"\n\t\t\t\t\t\t+ \"(?, ?, ?, ?, ?, ?)\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, product.getName());\n\t\t\t\tps.setDouble(2, product.getPrice());\n\t\t\t\tps.setString(3, product.getDescription());\n\t\t\t\tps.setString(4, product.getImageName());\n\t\t\t\tps.setString(5, product.getBrand());\n\t\t\t\tps.setLong(6, product.getCategory().getId());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao inserir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void update(Product product) {\n\t\ttry {\n\t\t\tif (product != null) {\n\t\t\t\tString SQL = \"UPDATE TOY_STORE.PRODUCT set NAME_PRODUCT=?, PRICE_PRODUCT=?, DESCRIPTION_PRODUCT=?, IMAGE_NAME_PRODUCT=?, ID_CATEGORY=?, BRAND_PRODUCT=? WHERE ID_PRODUCT=?\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, product.getName());\n\t\t\t\tps.setDouble(2, product.getPrice());\n\t\t\t\tps.setString(3, product.getDescription());\n\t\t\t\tps.setString(4, product.getImageName());\n\t\t\t\tps.setLong(5, product.getCategory().getId());\n\t\t\t\tps.setString(6, product.getBrand());\n\t\t\t\tps.setLong(7, product.getId());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao alterar dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void delete(Integer idProduct) {\n\t\ttry {\n\t\t\tString SQL = \"DELETE FROM TOY_STORE.PRODUCT AS PROD WHERE PROD.ID_PRODUCT =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idProduct);\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao excluir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic Product findById(int idProduct) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_PRODUCT =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idProduct);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\n\t\t\t\tlong idCategory = rs.getInt(\"id_category\");\n\t\t\t\tString nameCategory = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setBrand(brand);\n\n\t\t\t\tproduct.setCategory(new Category(idCategory, nameCategory, imageCategory));\n\t\t\t}\n\t\t\treturn product;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic List<Product> findProductsByCategory(int idCategory) {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY WHERE PROD.ID_CATEGORY = ?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idCategory);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setBrand(brand);\n\n\t\t\t\tlist.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic List<Product> findAll() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD ORDER BY PROD.NAME_PRODUCT\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setBrand(brand);\n\t\t\t\t\n\t\t\t\tlist.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic List<Product> findAllForAdmin() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD INNER JOIN TOY_STORE.CATEGORY AS CAT ON PROD.ID_CATEGORY = CAT.ID_CATEGORY ORDER BY PROD.NAME_PRODUCT\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\tString image = rs.getString(\"image_name_product\");\n\n\t\t\t\tlong idCategory = rs.getInt(\"id_category\");\n\t\t\t\tString nameCategory = rs.getString(\"name_category\");\n\t\t\t\tString imageCategory = rs.getString(\"image_name_category\");\n\t\t\t\t\n\t\t\t\tString brand = rs.getString(\"brand_product\");\n\t\t\t\t\n\t\t\t\tproduct = new Product();\n\t\t\t\tproduct.setId(id);\n\t\t\t\tproduct.setName(name);\n\t\t\t\tproduct.setPrice(price);\n\t\t\t\tproduct.setDescription(description);\n\t\t\t\tproduct.setImageName(image);\n\t\t\t\tproduct.setCategory(new Category(idCategory, nameCategory, imageCategory));\n\t\t\t\tproduct.setBrand(brand);\n\t\t\t\t\n\t\t\t\tlist.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n}" }, { "identifier": "UserDAO", "path": "src/main/java/br/com/toyStore/dao/UserDAO.java", "snippet": "public class UserDAO {\n\tprivate Connection conn;\n\tprivate PreparedStatement ps;\n\tprivate ResultSet rs;\n\tprivate User user;\n\n\tpublic UserDAO(Connection conn) {\n\t\tthis.conn = conn;\n\t}\n\n\tpublic void insert(User user) {\n\t\ttry {\n\t\t\tif (user != null) {\n\t\t\t\tString SQL = \"INSERT INTO TOY_STORE.USER (USERNAME_USER, PASSWORD_USER) values \"\n\t\t\t\t\t\t+ \"(?, ?)\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\tps.setString(1, user.getUsername());\n\t\t\t\tps.setString(2, user.getPassword());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao inserir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void update(Product product) {\n\t\ttry {\n\t\t\tif (product != null) {\n\t\t\t\tString SQL = \"UPDATE alunos set nome=?, email=?, endereco=?, datanascimento=?, \"\n\t\t\t\t\t\t+ \"periodo=? WHERE ra=?\";\n\t\t\t\tps = conn.prepareStatement(SQL);\n\t\t\t\t//ps.setString(1, aluno.getNome());\n\t\t\t\t//ps.setString(2, aluno.getEmail());\n\t\t\t\t//ps.setString(3, aluno.getEndereco());\n\t\t\t\t//ps.setDate(4, new java.sql.Date(aluno.getDataNascimento().getTime()));\n\t\t\t\t//ps.setString(5, aluno.getPeriodo());\n\t\t\t\t//ps.setInt(6, aluno.getRa());\n\t\t\t\tps.executeUpdate();\n\t\t\t}\n\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao alterar dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic void delete(Integer idUser) {\n\t\ttry {\n\t\t\tString SQL = \"DELETE FROM TOY_STORE.USER AS PROD WHERE ID_USEr=?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idUser);\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(\"Erro ao excluir dados \" + sqle);\n\t\t} finally {\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic User findByUsername(String username) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.USER WHERE USERNAME_USER = ?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setString(1, username);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tint id = rs.getInt(\"id_user\");\n\t\t\t\tString usernameUser = rs.getString(\"username_user\");\n\t\t\t\tString passwordUser = rs.getString(\"password_user\");\n\n\t\t\t\tuser = new User();\n\t\t\t\tuser.setId(id);\n\t\t\t\tuser.setUsername(usernameUser);\n\t\t\t\tuser.setPassword(passwordUser);\n\t\t\t}\n\t\t\treturn user;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\t\n\tpublic User findById(int idUser) {\n\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.USER WHERE ID_USER =?\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\tps.setInt(1, idUser);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tint id = rs.getInt(\"id_user\");\n\t\t\t\tString username = rs.getString(\"username_user\");\n\t\t\t\tString password = rs.getString(\"password_user\");\n\n\t\t\t\tuser.setId(id);\n\t\t\t\tuser.setUsername(username);\n\t\t\t\tuser.setPassword(password);\n\t\t\t}\n\t\t\treturn user;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n\n\tpublic List<Product> findAll() {\n\t\ttry {\n\t\t\tString SQL = \"SELECT * FROM TOY_STORE.PRODUCT AS PROD ORDER BY PROD.NAME_PRODUCT\";\n\t\t\tps = conn.prepareStatement(SQL);\n\t\t\trs = ps.executeQuery();\n\t\t\tList<Product> list = new ArrayList<Product>();\n\t\t\twhile (rs.next()) {\n\t\t\t\tlong id = rs.getInt(\"id_product\");\n\t\t\t\tString name = rs.getString(\"name_product\");\n\t\t\t\tString description = rs.getString(\"description_product\");\n\t\t\t\tdouble price = rs.getDouble(\"price_product\");\n\t\t\t\t\n\t\t\t\t//product = new Product();\n\t\t\t\t//product.setId(id);\n\t\t\t\t//product.setName(name);\n\t\t\t\t//product.setPrice(price);\n\t\t\t\t//product.setDescription(description);\n\t\t\t\t\n\t\t\t\t//list.add(product);\n\t\t\t}\n\t\t\treturn list;\n\t\t} catch (SQLException sqle) {\n\t\t\tthrow new DbException(sqle.getMessage());\n\t\t} finally {\n\t\t\tConnectionFactory.closeResultSet(rs);\n\t\t\tConnectionFactory.closeStatement(ps);\n\t\t}\n\t}\n}" }, { "identifier": "DbException", "path": "src/main/java/br/com/toyStore/exception/DbException.java", "snippet": "public class DbException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic DbException(String msg) {\n\t\tsuper(msg);\n\t}\n\t\n}" }, { "identifier": "Category", "path": "src/main/java/br/com/toyStore/model/Category.java", "snippet": "public class Category {\n\n\tprivate Long id;\n\tprivate String name;\n\tprivate String imageName;\n\t\t\n\tpublic Category() {\n\t}\n\n\tpublic Category(Long id, String name, String imageName) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\t\n}" }, { "identifier": "Product", "path": "src/main/java/br/com/toyStore/model/Product.java", "snippet": "public class Product implements Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Long id;\n\tprivate String name;\n\tprivate Double price;\n\tprivate String imageName;\n\tprivate String brand;\n\tprivate String description;\n\t\n\tprivate Category category;\n\t\n\tpublic Product() {\n\t}\n\n\tpublic Product(Long id, String name, Double price, String imageName, String brand, String description,\n\t\t\tCategory category) {\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.price = price;\n\t\tthis.imageName = imageName;\n\t\tthis.brand = brand;\n\t\tthis.description = description;\n\t\tthis.category = category;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic Double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(Double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic Category getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(Category category) {\n\t\tthis.category = category;\n\t}\n\n\tpublic String getImageName() {\n\t\treturn imageName;\n\t}\n\n\tpublic void setImageName(String imageName) {\n\t\tthis.imageName = imageName;\n\t}\n\n\tpublic String getBrand() {\n\t\treturn brand;\n\t}\n\n\tpublic void setBrand(String brand) {\n\t\tthis.brand = brand;\n\t}\n\t\n}" }, { "identifier": "User", "path": "src/main/java/br/com/toyStore/model/User.java", "snippet": "public class User {\n\n\tprivate int id;\n\tprivate String username;\n\tprivate String password;\n\t\n\tpublic User() {\n\t}\n\t\n\tpublic User(int id, String username, String password) {\n\t\tthis.id = id;\n\t\tthis.username = username;\n\t\tthis.password = password;\n\t}\n\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(int id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\t\n\t\n}" }, { "identifier": "ConnectionFactory", "path": "src/main/java/br/com/toyStore/util/ConnectionFactory.java", "snippet": "public class ConnectionFactory {\n\nprivate static Connection conn = null;\n\t\n\tpublic static Connection getConnection() {\n\t\tif (conn == null) {\n\t\t\ttry {\n\t\t\t\t\n\t\t\t\tClass.forName(\"com.mysql.jdbc.Driver\");\n\t\t\t\t\n\t\t\t\tString login = \"root\";\n\t\t\t\tString senha = \"1305\";\n\t\t\t\tString url = \"jdbc:mysql://localhost:3306/TOY_STORE?useUnicode=true&characterEncoding=UTF-8\";\n\t\t\t\tconn = DriverManager.getConnection(url,login,senha);\n\t\t\t}\n\t\t\tcatch(SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t} \n\t\t\tcatch (ClassNotFoundException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\treturn conn;\n\t}\n\t\n\tpublic static void closeConnection() {\n\t\tif (conn != null) {\n\t\t\ttry {\n\t\t\t\tconn.close();\n\t\t\t}\n\t\t\tcatch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeStatement(Statement st) {\n\t\tif (st != null) {\n\t\t\ttry {\n\t\t\t\tst.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void closeResultSet(ResultSet rs) {\n\t\tif (rs != null) {\n\t\t\ttry {\n\t\t\t\trs.close();\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new DbException(e.getMessage());\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt,\n\t\t\tResultSet rs) throws Exception {\n\t\tclose(conn, stmt, rs);\n\t}\n\n\tpublic static void closeConnection(Connection conn, Statement stmt)\n\t\t\tthrows Exception {\n\t\tclose(conn, stmt, null);\n\t}\n\n\tpublic static void closeConnection(Connection conn) throws Exception {\n\t\tclose(conn, null, null);\n\t}\n\n\tprivate static void close(Connection conn, Statement stmt, ResultSet rs)\n\t\t\tthrows Exception {\n\t\ttry {\n\t\t\tif (rs != null)\n\t\t\t\trs.close();\n\t\t\tif (stmt != null)\n\t\t\t\tstmt.close();\n\t\t\tif (conn != null)\n\t\t\t\tconn.close();\n\t\t} catch (Exception e) {\n\t\t\tthrow new Exception(e.getMessage());\n\t\t}\n\t}\n\t\n}" } ]
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import br.com.toyStore.dao.CategoryDAO; import br.com.toyStore.dao.ProductDAO; import br.com.toyStore.dao.UserDAO; import br.com.toyStore.exception.DbException; import br.com.toyStore.model.Category; import br.com.toyStore.model.Product; import br.com.toyStore.model.User; import br.com.toyStore.util.ConnectionFactory;
6,008
package br.com.toyStore.servlet; @WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories", "/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin", "/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"}) @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 100 // 100 MB ) public class Servlet extends HttpServlet { private static final long serialVersionUID = 1L; ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection()); CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection());
package br.com.toyStore.servlet; @WebServlet(urlPatterns = { "/Servlet", "/home", "/catalog", "/categories", "/selectProduct", "/selectCategory", "/insertProduct", "/insertCategory", "/login", "/admin", "/updateProduct", "/selectProductUpdate", "/deleteProduct", "/newProduct"}) @MultipartConfig( fileSizeThreshold = 1024 * 1024 * 1, // 1 MB maxFileSize = 1024 * 1024 * 10, // 10 MB maxRequestSize = 1024 * 1024 * 100 // 100 MB ) public class Servlet extends HttpServlet { private static final long serialVersionUID = 1L; ProductDAO productDao = new ProductDAO(ConnectionFactory.getConnection()); CategoryDAO categoryDao = new CategoryDAO(ConnectionFactory.getConnection());
UserDAO userDao = new UserDAO(ConnectionFactory.getConnection());
2
2023-10-20 02:51:14+00:00
8k
MYSTD/BigDataApiTest
data-governance-assessment/src/main/java/com/std/dga/governance/service/impl/GovernanceAssessDetailServiceImpl.java
[ { "identifier": "Assessor", "path": "data-governance-assessment/src/main/java/com/std/dga/assessor/Assessor.java", "snippet": "public abstract class Assessor {\n\n public final GovernanceAssessDetail doAssessor(AssessParam assessParam){\n\n// System.out.println(\"Assessor 管理流程\");\n GovernanceAssessDetail governanceAssessDetail = new GovernanceAssessDetail();\n governanceAssessDetail.setAssessDate(assessParam.getAssessDate());\n governanceAssessDetail.setMetricId(assessParam.getTableMetaInfo().getId()+\"\");\n governanceAssessDetail.setTableName(assessParam.getTableMetaInfo().getTableName());\n governanceAssessDetail.setSchemaName(assessParam.getTableMetaInfo().getSchemaName());\n governanceAssessDetail.setMetricName(assessParam.getGovernanceMetric().getMetricName());\n governanceAssessDetail.setGovernanceType(assessParam.getGovernanceMetric().getGovernanceType());\n governanceAssessDetail.setTecOwner(assessParam.getTableMetaInfo().getTableMetaInfoExtra().getTecOwnerUserName());\n governanceAssessDetail.setCreateTime(new Date());\n //默认先给满分, 在考评器查找问题的过程中,如果有问题,再按照指标的要求重新给分。\n governanceAssessDetail.setAssessScore(BigDecimal.TEN);\n\n try {\n checkProblem(governanceAssessDetail, assessParam);\n }catch (Exception e) {\n governanceAssessDetail.setAssessScore(BigDecimal.ZERO);\n governanceAssessDetail.setIsAssessException(\"1\");\n //记录异常信息\n //简单记录\n //governanceAssessDetail.setAssessExceptionMsg( e.getMessage());\n\n //详细记录\n StringWriter stringWriter = new StringWriter() ;\n PrintWriter msgPrintWriter = new PrintWriter(stringWriter) ;\n e.printStackTrace( msgPrintWriter);\n governanceAssessDetail.setAssessExceptionMsg( stringWriter.toString().substring( 0, Math.min( 2000 , stringWriter.toString().length())) );\n }\n\n return governanceAssessDetail;\n }\n\n public abstract void checkProblem(GovernanceAssessDetail governanceAssessDetail , AssessParam assessParam) throws Exception;\n}" }, { "identifier": "TDsTaskDefinition", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskDefinition.java", "snippet": "@Data\n@TableName(\"t_ds_task_definition\")\npublic class TDsTaskDefinition implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * self-increasing id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * encoding\n */\n private Long code;\n\n /**\n * task definition name\n */\n private String name;\n\n /**\n * task definition version\n */\n private Integer version;\n\n /**\n * description\n */\n private String description;\n\n /**\n * project code\n */\n private Long projectCode;\n\n /**\n * task definition creator id\n */\n private Integer userId;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * job priority\n */\n private Byte taskPriority;\n\n /**\n * worker grouping\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * number of failed retries\n */\n private Integer failRetryTimes;\n\n /**\n * failed retry interval\n */\n private Integer failRetryInterval;\n\n /**\n * timeout flag:0 close, 1 open\n */\n private Byte timeoutFlag;\n\n /**\n * timeout notification policy: 0 warning, 1 fail\n */\n private Byte timeoutNotifyStrategy;\n\n /**\n * timeout length,unit: minute\n */\n private Integer timeout;\n\n /**\n * delay execution time,unit: minute\n */\n private Integer delayTime;\n\n /**\n * resource id, separated by comma\n */\n private String resourceIds;\n\n /**\n * create time\n */\n private Date createTime;\n\n /**\n * update time\n */\n private Date updateTime;\n\n @TableField(exist = false)\n private String taskSql; // 任务SQL\n}" }, { "identifier": "TDsTaskInstance", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/bean/TDsTaskInstance.java", "snippet": "@Data\n@TableName(\"t_ds_task_instance\")\npublic class TDsTaskInstance implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * key\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * task name\n */\n private String name;\n\n /**\n * task type\n */\n private String taskType;\n\n /**\n * task definition code\n */\n private Long taskCode;\n\n /**\n * task definition version\n */\n private Integer taskDefinitionVersion;\n\n /**\n * process instance id\n */\n private Integer processInstanceId;\n\n /**\n * Status: 0 commit succeeded, 1 running, 2 prepare to pause, 3 pause, 4 prepare to stop, 5 stop, 6 fail, 7 succeed, 8 need fault tolerance, 9 kill, 10 wait for thread, 11 wait for dependency to complete\n */\n private Byte state;\n\n /**\n * task submit time\n */\n private Date submitTime;\n\n /**\n * task start time\n */\n private Date startTime;\n\n /**\n * task end time\n */\n private Date endTime;\n\n /**\n * host of task running on\n */\n private String host;\n\n /**\n * task execute path in the host\n */\n private String executePath;\n\n /**\n * task log path\n */\n private String logPath;\n\n /**\n * whether alert\n */\n private Byte alertFlag;\n\n /**\n * task retry times\n */\n private Integer retryTimes;\n\n /**\n * pid of task\n */\n private Integer pid;\n\n /**\n * yarn app id\n */\n private String appLink;\n\n /**\n * job custom parameters\n */\n private String taskParams;\n\n /**\n * 0 not available, 1 available\n */\n private Byte flag;\n\n /**\n * retry interval when task failed \n */\n private Integer retryInterval;\n\n /**\n * max retry times\n */\n private Integer maxRetryTimes;\n\n /**\n * task instance priority:0 Highest,1 High,2 Medium,3 Low,4 Lowest\n */\n private Integer taskInstancePriority;\n\n /**\n * worker group id\n */\n private String workerGroup;\n\n /**\n * environment code\n */\n private Long environmentCode;\n\n /**\n * this config contains many environment variables config\n */\n private String environmentConfig;\n\n private Integer executorId;\n\n /**\n * task first submit time\n */\n private Date firstSubmitTime;\n\n /**\n * task delay execution time\n */\n private Integer delayTime;\n\n /**\n * var_pool\n */\n private String varPool;\n\n /**\n * dry run flag: 0 normal, 1 dry run\n */\n private Byte dryRun;\n}" }, { "identifier": "TDsTaskDefinitionService", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/service/TDsTaskDefinitionService.java", "snippet": "@DS(\"dolphinscheduler\")\npublic interface TDsTaskDefinitionService extends IService<TDsTaskDefinition> {\n\n List<TDsTaskDefinition> selectList();\n\n}" }, { "identifier": "TDsTaskInstanceService", "path": "data-governance-assessment/src/main/java/com/std/dga/dolphinscheduler/service/TDsTaskInstanceService.java", "snippet": "@DS(\"dolphinscheduler\")\npublic interface TDsTaskInstanceService extends IService<TDsTaskInstance> {\n\n List<TDsTaskInstance> selectList(String assessDate);\n\n List<TDsTaskInstance> selectFailedTask(String taskName, String assessDate);\n\n List<TDsTaskInstance> selectBeforeNDaysInstance(String taskName, String startDate, String assessDate);\n}" }, { "identifier": "AssessParam", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/AssessParam.java", "snippet": "@Data\npublic class AssessParam {\n\n private String assessDate ;\n private TableMetaInfo tableMetaInfo ;\n private GovernanceMetric governanceMetric ;\n\n private Map<String ,TableMetaInfo> tableMetaInfoMap ; // 所有表\n\n private TDsTaskDefinition tDsTaskDefinition ; // 该指标需要的任务定义\n\n private TDsTaskInstance tDsTaskInstance ; // 该指标需要的任务状态信息(当日)\n\n}" }, { "identifier": "GovernanceAssessDetail", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetail.java", "snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetail implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 指标项id\n */\n private String metricId;\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n /**\n * 考评得分\n */\n private BigDecimal assessScore;\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n /**\n * 考评备注\n */\n private String assessComment;\n\n /**\n * 考评是否异常\n */\n private String isAssessException;\n\n /**\n * 异常信息\n */\n private String assessExceptionMsg;\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n\n /**\n * 创建日期\n */\n private Date createTime;\n}" }, { "identifier": "GovernanceAssessDetailVO", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceAssessDetailVO.java", "snippet": "@Data\n@TableName(\"governance_assess_detail\")\npublic class GovernanceAssessDetailVO {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 考评日期\n */\n private String assessDate;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n\n /**\n * 指标项名称\n */\n private String metricName;\n\n /**\n * 技术负责人\n */\n private String tecOwner;\n\n\n /**\n * 考评问题项\n */\n private String assessProblem;\n\n\n\n /**\n * 治理处理路径\n */\n private String governanceUrl;\n}" }, { "identifier": "GovernanceMetric", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/bean/GovernanceMetric.java", "snippet": "@Data\n@TableName(\"governance_metric\")\npublic class GovernanceMetric implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 指标名称\n */\n private String metricName;\n\n /**\n * 指标编码\n */\n private String metricCode;\n\n /**\n * 指标描述\n */\n private String metricDesc;\n\n /**\n * 治理类型\n */\n private String governanceType;\n\n /**\n * 指标参数\n */\n private String metricParamsJson;\n\n /**\n * 治理连接\n */\n private String governanceUrl;\n\n /**\n * 跳过考评的表名(多表逗号分割)\n */\n private String skipAssessTables;\n\n /**\n * 是否启用\n */\n private String isDisabled;\n}" }, { "identifier": "GovernanceAssessDetailMapper", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/mapper/GovernanceAssessDetailMapper.java", "snippet": "@Mapper\n@DS(\"dga\")\npublic interface GovernanceAssessDetailMapper extends BaseMapper<GovernanceAssessDetail> {\n\n}" }, { "identifier": "GovernanceAssessDetailService", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/service/GovernanceAssessDetailService.java", "snippet": "public interface GovernanceAssessDetailService extends IService<GovernanceAssessDetail> {\n\n void mainAssess( String assessDate);\n\n List<GovernanceAssessDetailVO> getProblemList(String governanceType, Integer pageNo, Integer pageSize);\n\n Map<String, Long> getProblemNum();\n}" }, { "identifier": "GovernanceMetricService", "path": "data-governance-assessment/src/main/java/com/std/dga/governance/service/GovernanceMetricService.java", "snippet": "public interface GovernanceMetricService extends IService<GovernanceMetric> {\n\n}" }, { "identifier": "TableMetaInfo", "path": "data-governance-assessment/src/main/java/com/std/dga/meta/bean/TableMetaInfo.java", "snippet": "@Data\n@TableName(\"table_meta_info\")\npublic class TableMetaInfo implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 表id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 表名\n */\n private String tableName;\n\n /**\n * 库名\n */\n private String schemaName;\n\n /**\n * 字段名json ( 来源:hive)\n */\n private String colNameJson;\n\n /**\n * 分区字段名json( 来源:hive)\n */\n private String partitionColNameJson;\n\n /**\n * hdfs所属人 ( 来源:hive)\n */\n private String tableFsOwner;\n\n /**\n * 参数信息 ( 来源:hive)\n */\n private String tableParametersJson;\n\n /**\n * 表备注 ( 来源:hive)\n */\n private String tableComment;\n\n /**\n * hdfs路径 ( 来源:hive)\n */\n private String tableFsPath;\n\n /**\n * 输入格式( 来源:hive)\n */\n private String tableInputFormat;\n\n /**\n * 输出格式 ( 来源:hive)\n */\n private String tableOutputFormat;\n\n /**\n * 行格式 ( 来源:hive)\n */\n private String tableRowFormatSerde;\n\n /**\n * 表创建时间 ( 来源:hive)\n */\n private Date tableCreateTime;\n\n /**\n * 表类型 ( 来源:hive)\n */\n private String tableType;\n\n /**\n * 分桶列 ( 来源:hive)\n */\n private String tableBucketColsJson;\n\n /**\n * 分桶个数 ( 来源:hive)\n */\n private Long tableBucketNum;\n\n /**\n * 排序列 ( 来源:hive)\n */\n private String tableSortColsJson;\n\n /**\n * 数据量大小 ( 来源:hdfs)\n */\n private Long tableSize=0L;\n\n /**\n * 所有副本数据总量大小 ( 来源:hdfs)\n */\n private Long tableTotalSize=0L;\n\n /**\n * 最后修改时间 ( 来源:hdfs)\n */\n private Date tableLastModifyTime;\n\n /**\n * 最后访问时间 ( 来源:hdfs)\n */\n private Date tableLastAccessTime;\n\n /**\n * 当前文件系统容量 ( 来源:hdfs)\n */\n private Long fsCapcitySize;\n\n /**\n * 当前文件系统使用量 ( 来源:hdfs)\n */\n private Long fsUsedSize;\n\n /**\n * 当前文件系统剩余量 ( 来源:hdfs)\n */\n private Long fsRemainSize;\n\n /**\n * 考评日期 \n */\n private String assessDate;\n\n /**\n * 创建时间 (自动生成)\n */\n private Date createTime;\n\n /**\n * 更新时间 (自动生成)\n */\n private Date updateTime;\n\n\n /**\n * 额外辅助信息\n */\n @TableField(exist = false)\n private TableMetaInfoExtra tableMetaInfoExtra;\n\n}" }, { "identifier": "TableMetaInfoMapper", "path": "data-governance-assessment/src/main/java/com/std/dga/meta/mapper/TableMetaInfoMapper.java", "snippet": "@Mapper\n@DS(\"dga\")\npublic interface TableMetaInfoMapper extends BaseMapper<TableMetaInfo> {\n\n @Select(\n \"SELECT ti.*, te.* , ti.id ti_id , te.id te_id\\n\" +\n \"FROM table_meta_info ti JOIN table_meta_info_extra te\\n\" +\n \"ON ti.schema_name = te.schema_name AND ti.table_name = te.table_name \\n\" +\n \"WHERE ti.assess_date = #{assessDate} \"\n )\n @ResultMap(\"meta_result_map\")\n List<TableMetaInfo> selectTableMetaInfoList(String assessDate);\n\n @Select(\"${sql}\")\n List<TableMetaInfoVO> selectTableMetaInfoVoList(String sql);\n @Select(\"${sql}\")\n Integer selectTableMetaInfoCount(String sql);\n}" }, { "identifier": "SpringBeanProvider", "path": "data-governance-assessment/src/main/java/com/std/dga/util/SpringBeanProvider.java", "snippet": "@Component\npublic class SpringBeanProvider implements ApplicationContextAware {\n\n ApplicationContext applicationContext ;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n this.applicationContext = applicationContext ;\n }\n\n /**\n * 通过组件的名字,从容器中获取到对应的组件对象\n */\n public <T> T getBeanByName(String beanName , Class<T> tClass){\n T bean = applicationContext.getBean(beanName, tClass);\n return bean ;\n }\n}" } ]
import com.baomidou.dynamic.datasource.annotation.DS; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.std.dga.assessor.Assessor; import com.std.dga.dolphinscheduler.bean.TDsTaskDefinition; import com.std.dga.dolphinscheduler.bean.TDsTaskInstance; import com.std.dga.dolphinscheduler.service.TDsTaskDefinitionService; import com.std.dga.dolphinscheduler.service.TDsTaskInstanceService; import com.std.dga.governance.bean.AssessParam; import com.std.dga.governance.bean.GovernanceAssessDetail; import com.std.dga.governance.bean.GovernanceAssessDetailVO; import com.std.dga.governance.bean.GovernanceMetric; import com.std.dga.governance.mapper.GovernanceAssessDetailMapper; import com.std.dga.governance.service.GovernanceAssessDetailService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.std.dga.governance.service.GovernanceMetricService; import com.std.dga.meta.bean.TableMetaInfo; import com.std.dga.meta.mapper.TableMetaInfoMapper; import com.std.dga.util.SpringBeanProvider; import com.sun.codemodel.internal.JForEach; import org.apache.tomcat.util.threads.ThreadPoolExecutor; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
5,212
package com.std.dga.governance.service.impl; /** * <p> * 治理考评结果明细 服务实现类 * </p> * * @author std * @since 2023-10-10 */ @Service @DS("dga")
package com.std.dga.governance.service.impl; /** * <p> * 治理考评结果明细 服务实现类 * </p> * * @author std * @since 2023-10-10 */ @Service @DS("dga")
public class GovernanceAssessDetailServiceImpl extends ServiceImpl<GovernanceAssessDetailMapper, GovernanceAssessDetail> implements GovernanceAssessDetailService {
9
2023-10-20 10:13:43+00:00
8k
RaulGB88/MOD-034-Microservicios-con-Java
REM20231023/demo/src/main/java/com/example/application/resources/ActorResource.java
[ { "identifier": "ActorService", "path": "REM20231023/catalogo/src/main/java/com/example/domains/contracts/services/ActorService.java", "snippet": "public interface ActorService extends ProjectionDomainService<Actor, Integer> {\n\tList<Actor> novedades(Timestamp fecha);\n}" }, { "identifier": "Film", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/Film.java", "snippet": "@Entity\n@Table(name=\"film\")\n@NamedQuery(name=\"Film.findAll\", query=\"SELECT f FROM Film f\")\npublic class Film extends EntityBase<Film> implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\tpublic static enum Rating {\n\t GENERAL_AUDIENCES(\"G\"),\n\t PARENTAL_GUIDANCE_SUGGESTED(\"PG\"),\n\t PARENTS_STRONGLY_CAUTIONED(\"PG-13\"),\n\t RESTRICTED(\"R\"),\n\t ADULTS_ONLY(\"NC-17\");\n\n\t String value;\n\t \n\t Rating(String value) {\n\t this.value = value;\n\t }\n\n\t public String getValue() {\n\t return value;\n\t }\n\t\tpublic static Rating getEnum(String value) {\n\t\t\tswitch (value) {\n\t\t\tcase \"G\": return Rating.GENERAL_AUDIENCES;\n\t\t\tcase \"PG\": return Rating.PARENTAL_GUIDANCE_SUGGESTED;\n\t\t\tcase \"PG-13\": return Rating.PARENTS_STRONGLY_CAUTIONED;\n\t\t\tcase \"R\": return Rating.RESTRICTED;\n\t\t\tcase \"NC-17\": return Rating.ADULTS_ONLY;\n\t\t\tcase \"\": return null;\n\t\t\tdefault:\n\t\t\t\tthrow new IllegalArgumentException(\"Unexpected value: \" + value);\n\t\t\t}\n\t\t}\n\t\tpublic static final String[] VALUES = {\"G\", \"PG\", \"PG-13\", \"R\", \"NC-17\"};\n\t}\n\t@Converter\n\tprivate static class RatingConverter implements AttributeConverter<Rating, String> {\n\t @Override\n\t public String convertToDatabaseColumn(Rating rating) {\n\t if (rating == null) {\n\t return null;\n\t }\n\t return rating.getValue();\n\t }\n\t @Override\n\t public Rating convertToEntityAttribute(String value) {\n\t if (value == null) {\n\t return null;\n\t }\n\n\t return Rating.getEnum(value);\n\t }\n\t}\n\n\t@Id\n\t@GeneratedValue(strategy=GenerationType.IDENTITY)\n\t@Column(name=\"film_id\", unique=true, nullable=false)\n\tprivate int filmId;\n\n\t@Lob\n\tprivate String description;\n\n\t@Column(name=\"last_update\", insertable = false, updatable = false, nullable=false)\n\tprivate Timestamp lastUpdate;\n\n\t@Positive\n\tprivate Integer length;\n\n\t@Convert(converter = RatingConverter.class)\n\tprivate Rating rating;\n\n\t//@Temporal(TemporalType.DATE)\n\t//@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy\")\n\t@Min(1901) @Max(2155)\n\t@Column(name=\"release_year\")\n\tprivate Short releaseYear;\n\n\t@NotNull\n\t@Positive\n\t@Column(name=\"rental_duration\", nullable=false)\n\tprivate Byte rentalDuration;\n\n\t@NotNull\n @Digits(integer=2, fraction=2)\n\t@DecimalMin(value = \"0.0\", inclusive = false)\n\t@Column(name=\"rental_rate\", nullable=false, precision=10, scale=2)\n\tprivate BigDecimal rentalRate;\n\n\t@NotNull\n @Digits(integer=3, fraction=2)\n\t@DecimalMin(value = \"0.0\", inclusive = false)\n\t@Column(name=\"replacement_cost\", nullable=false, precision=10, scale=2)\n\tprivate BigDecimal replacementCost;\n\n\t@NotBlank\n\t@Size(max = 128)\n\t@Column(nullable=false, length=128)\n\tprivate String title;\n\n\t//bi-directional many-to-one association to Language\n\t@ManyToOne\n\t@JoinColumn(name=\"language_id\")\n\t@NotNull\n\tprivate Language language;\n\n\t//bi-directional many-to-one association to Language\n\t@ManyToOne\n\t@JoinColumn(name=\"original_language_id\")\n\tprivate Language languageVO;\n\n\t//bi-directional many-to-one association to FilmActor\n\t@OneToMany(mappedBy=\"film\", cascade = CascadeType.ALL, orphanRemoval = true)\n\t@JsonIgnore\n\tprivate List<FilmActor> filmActors = new ArrayList<FilmActor>();\n\n\t//bi-directional many-to-one association to FilmCategory\n\t@OneToMany(mappedBy=\"film\", cascade = CascadeType.ALL, orphanRemoval = true)\n\t@JsonIgnore\n\tprivate List<FilmCategory> filmCategories = new ArrayList<FilmCategory>();\n\n\tpublic Film() {\n\t}\n\n\tpublic Film(int filmId) {\n\t\tthis.filmId = filmId;\n\t}\n\n\tpublic Film(int filmId, @NotBlank @Size(max = 128) String title, String description, @Min(1895) Short releaseYear,\n\t\t\t@NotNull Language language, Language languageVO, @Positive Byte rentalDuration,\n\t\t\t@Positive @DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 2, fraction = 2) BigDecimal rentalRate,\n\t\t\t@Positive Integer length,\n\t\t\t@DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 3, fraction = 2) BigDecimal replacementCost,\n\t\t\tRating rating) {\n\t\tsuper();\n\t\tthis.filmId = filmId;\n\t\tthis.title = title;\n\t\tthis.description = description;\n\t\tthis.releaseYear = releaseYear;\n\t\tthis.language = language;\n\t\tthis.languageVO = languageVO;\n\t\tthis.rentalDuration = rentalDuration;\n\t\tthis.rentalRate = rentalRate;\n\t\tthis.length = length;\n\t\tthis.replacementCost = replacementCost;\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Film(@NotBlank @Size(max = 128) String title,\n\t\t\t@NotNull Language language, \n\t\t\t@Positive Byte rentalDuration,\n\t\t\t@Positive @DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 2, fraction = 2) BigDecimal rentalRate,\n\t\t\t@Positive int length,\n\t\t\t@DecimalMin(value = \"0.0\", inclusive = false) @Digits(integer = 3, fraction = 2) BigDecimal replacementCost) {\n\t\tsuper();\n\t\tthis.title = title;\n\t\tthis.language = language;\n\t\tthis.rentalDuration = rentalDuration;\n\t\tthis.rentalRate = rentalRate;\n\t\tthis.length = length;\n\t\tthis.replacementCost = replacementCost;\n\t}\n\n\tpublic int getFilmId() {\n\t\treturn this.filmId;\n\t}\n\n\tpublic void setFilmId(int filmId) {\n\t\tthis.filmId = filmId;\n\t\tif(filmActors != null && filmActors.size() > 0)\n\t\t\tfilmActors.forEach(item -> { if(item.getId().getFilmId() != filmId) item.getId().setFilmId(filmId); });\n\t\tif(filmCategories != null && filmCategories.size() > 0)\n\t\t\tfilmCategories.forEach(item -> { if(item.getId().getFilmId() != filmId) item.getId().setFilmId(filmId); });\n\t}\n\n\tpublic String getDescription() {\n\t\treturn this.description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic Timestamp getLastUpdate() {\n\t\treturn this.lastUpdate;\n\t}\n\n\tpublic void setLastUpdate(Timestamp lastUpdate) {\n\t\tthis.lastUpdate = lastUpdate;\n\t}\n\n\tpublic Integer getLength() {\n\t\treturn this.length;\n\t}\n\n\tpublic void setLength(Integer length) {\n\t\tthis.length = length;\n\t}\n\n\tpublic Rating getRating() {\n\t\treturn this.rating;\n\t}\n\n\tpublic void setRating(Rating rating) {\n\t\tthis.rating = rating;\n\t}\n\n\tpublic Short getReleaseYear() {\n\t\treturn this.releaseYear;\n\t}\n\n\tpublic void setReleaseYear(Short releaseYear) {\n\t\tthis.releaseYear = releaseYear;\n\t}\n\n\tpublic Byte getRentalDuration() {\n\t\treturn this.rentalDuration;\n\t}\n\n\tpublic void setRentalDuration(Byte rentalDuration) {\n\t\tthis.rentalDuration = rentalDuration;\n\t}\n\n\tpublic BigDecimal getRentalRate() {\n\t\treturn this.rentalRate;\n\t}\n\n\tpublic void setRentalRate(BigDecimal rentalRate) {\n\t\tthis.rentalRate = rentalRate;\n\t}\n\n\tpublic BigDecimal getReplacementCost() {\n\t\treturn this.replacementCost;\n\t}\n\n\tpublic void setReplacementCost(BigDecimal replacementCost) {\n\t\tthis.replacementCost = replacementCost;\n\t}\n\n\tpublic String getTitle() {\n\t\treturn this.title;\n\t}\n\n\tpublic void setTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic Language getLanguage() {\n\t\treturn this.language;\n\t}\n\n\tpublic void setLanguage(Language language) {\n\t\tthis.language = language;\n\t}\n\n\tpublic Language getLanguageVO() {\n\t\treturn this.languageVO;\n\t}\n\n\tpublic void setLanguageVO(Language languageVO) {\n\t\tthis.languageVO = languageVO;\n\t}\n\n\t// Gestión de actores\n\n\tpublic List<Actor> getActors() {\n\t\treturn this.filmActors.stream().map(item -> item.getActor()).toList();\n\t}\n\tpublic void setActors(List<Actor> source) {\n\t\tif(filmActors == null || !filmActors.isEmpty()) clearActors();\n\t\tsource.forEach(item -> addActor(item));\n\t}\n\tpublic void clearActors() {\n\t\tfilmActors = new ArrayList<FilmActor>() ;\n\t}\n\tpublic void addActor(Actor actor) {\n\t\tFilmActor filmActor = new FilmActor(this, actor);\n\t\tfilmActors.add(filmActor);\n\t}\n\tpublic void addActor(int actorId) {\n\t\taddActor(new Actor(actorId));\n\t}\n\tpublic void removeActor(Actor actor) {\n\t\tvar filmActor = filmActors.stream().filter(item -> item.getActor().equals(actor)).findFirst();\n\t\tif(filmActor.isEmpty())\n\t\t\treturn;\n\t\tfilmActors.remove(filmActor.get());\n\t}\n\n\t// Gestión de categorias\n\n\tpublic List<Category> getCategories() {\n\t\treturn this.filmCategories.stream().map(item -> item.getCategory()).toList();\n\t}\n\tpublic void setCategories(List<Category> source) {\n\t\tif(filmCategories == null || !filmCategories.isEmpty()) clearCategories();\n\t\tsource.forEach(item -> addCategory(item));\n\t}\n\tpublic void clearCategories() {\n\t\tfilmCategories = new ArrayList<FilmCategory>() ;\n\t}\n\tpublic void addCategory(Category item) {\n\t\tFilmCategory filmCategory = new FilmCategory(this, item);\n\t\tfilmCategories.add(filmCategory);\n\t}\n\tpublic void addCategory(int id) {\n\t\taddCategory(new Category(id));\n\t}\n\tpublic void removeCategory(Category ele) {\n\t\tvar filmCategory = filmCategories.stream().filter(item -> item.getCategory().equals(ele)).findFirst();\n\t\tif(filmCategory.isEmpty())\n\t\t\treturn;\n\t\tfilmCategories.remove(filmCategory.get());\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(filmId);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tFilm other = (Film) obj;\n\t\treturn filmId == other.filmId;\n\t}\n\n\tpublic Film merge(Film target) {\n\t\ttarget.title = title;\n\t\ttarget.description = description;\n\t\ttarget.releaseYear = releaseYear;\n\t\ttarget.language = language;\n\t\ttarget.languageVO = languageVO;\n\t\ttarget.rentalDuration = rentalDuration;\n\t\ttarget.rentalRate = rentalRate;\n\t\ttarget.length = length;\n\t\ttarget.replacementCost = replacementCost;\n\t\ttarget.rating = rating;\n\t\t// Borra los actores que sobran\n\t\ttarget.getActors().stream()\n\t\t\t.filter(item -> !getActors().contains(item))\n\t\t\t.forEach(item -> target.removeActor(item));\n\t\t// Añade los actores que faltan\n\t\tgetActors().stream()\n\t\t\t.filter(item -> !target.getActors().contains(item))\n\t\t\t.forEach(item -> target.addActor(item));\n\t\t// Añade las categorias que faltan\n\t\ttarget.getCategories().stream()\n\t\t\t.filter(item -> !getCategories().contains(item))\n\t\t\t.forEach(item -> target.removeCategory(item));\n\t\t// Borra las categorias que sobran\n\t\tgetCategories().stream()\n\t\t\t.filter(item -> !target.getCategories().contains(item))\n\t\t\t.forEach(item -> target.addCategory(item));\n\t\treturn target;\n\t}\n}" }, { "identifier": "FilmActor", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/FilmActor.java", "snippet": "@Entity\n@Table(name=\"film_actor\")\n@NamedQuery(name=\"FilmActor.findAll\", query=\"SELECT f FROM FilmActor f\")\npublic class FilmActor implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\n\t@EmbeddedId\n\tprivate FilmActorPK id;\n\n\t@Column(name=\"last_update\", insertable = false, updatable = false)\n\tprivate Timestamp lastUpdate;\n\n\t//bi-directional many-to-one association to Actor\n\t@ManyToOne\n\t@JoinColumn(name=\"actor_id\", insertable=false, updatable=false)\n\tprivate Actor actor;\n\n\t//bi-directional many-to-one association to Film\n\t@ManyToOne\n\t@JoinColumn(name=\"film_id\", insertable=false, updatable=false)\n\tprivate Film film;\n\n\tpublic FilmActor() {\n\t}\n\n\tpublic FilmActor(Film film, Actor actor) {\n\t\tsuper();\n\t\tthis.film = film;\n\t\tthis.actor = actor;\n\t}\n\n\tpublic FilmActorPK getId() {\n\t\treturn this.id;\n\t}\n\n\tpublic void setId(FilmActorPK id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Timestamp getLastUpdate() {\n\t\treturn this.lastUpdate;\n\t}\n\n\tpublic void setLastUpdate(Timestamp lastUpdate) {\n\t\tthis.lastUpdate = lastUpdate;\n\t}\n\n\tpublic Actor getActor() {\n\t\treturn this.actor;\n\t}\n\n\tpublic void setActor(Actor actor) {\n\t\tthis.actor = actor;\n\t}\n\n\tpublic Film getFilm() {\n\t\treturn this.film;\n\t}\n\n\tpublic void setFilm(Film film) {\n\t\tthis.film = film;\n\t}\n\t@PrePersist\n\tprivate void prePersiste() {\n\t\tif (id == null) {\n\t\t\tsetId(new FilmActorPK(film.getFilmId(), actor.getActorId()));\n\t\t}\n\t}\n}" }, { "identifier": "ActorDTO", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/ActorDTO.java", "snippet": "@Value\npublic class ActorDTO {\n\t@JsonProperty(\"id\")\n\tprivate int actorId;\n\t@JsonProperty(\"nombre\")\n\tprivate String firstName;\n\t@JsonProperty(\"apellidos\")\n\tprivate String lastName;\n\t\n\tpublic static ActorDTO from(Actor target) {\n\t\treturn new ActorDTO(target.getActorId(), target.getFirstName(), target.getLastName());\n\t}\n\n\tpublic static Actor from(ActorDTO target) {\n\t\treturn new Actor(target.getActorId(), target.getFirstName(), target.getLastName());\n\t}\n\n}" }, { "identifier": "ActorShort", "path": "REM20231023/catalogo/src/main/java/com/example/domains/entities/dtos/ActorShort.java", "snippet": "public interface ActorShort {\n\t@JsonProperty(\"id\")\n\tint getActorId();\n\t@Value(\"#{target.firstName + ' ' + target.lastName}\")\n\tString getNombre();\n}" }, { "identifier": "BadRequestException", "path": "REM20231023/catalogo/src/main/java/com/example/exceptions/BadRequestException.java", "snippet": "public class BadRequestException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tpublic BadRequestException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic BadRequestException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic BadRequestException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n}" }, { "identifier": "DuplicateKeyException", "path": "REM20231023/catalogo/src/main/java/com/example/exceptions/DuplicateKeyException.java", "snippet": "public class DuplicateKeyException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Duplicate key\";\n\t\n\tpublic DuplicateKeyException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic DuplicateKeyException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic DuplicateKeyException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic DuplicateKeyException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic DuplicateKeyException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n\n}" }, { "identifier": "InvalidDataException", "path": "REM20231023/catalogo/src/main/java/com/example/exceptions/InvalidDataException.java", "snippet": "public class InvalidDataException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Invalid data\";\n\tprivate Map<String, String> errors = null;\n\t\n\tpublic InvalidDataException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic InvalidDataException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic InvalidDataException(Map<String, String> errors) {\n\t\tthis(MESSAGE_STRING, errors);\n\t}\n\n\tpublic InvalidDataException(String message, Map<String, String> errors) {\n\t\tsuper(message);\n\t\tthis.errors = errors;\n\t}\n\n\tpublic InvalidDataException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n\n\tpublic InvalidDataException(Throwable cause, Map<String, String> errors) {\n\t\tthis(MESSAGE_STRING, cause, errors);\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause, Map<String, String> errors) {\n\t\tsuper(message, cause);\n\t\tthis.errors = errors;\n\t}\n\n\tpublic InvalidDataException(String message, Throwable cause, Map<String, String> errors, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t\tthis.errors = errors;\n\t}\n\n\tpublic boolean hasErrors() { return errors != null; }\n\tpublic Map<String, String> getErrors() { return errors; }\n\t\n\t\n}" }, { "identifier": "NotFoundException", "path": "REM20231023/catalogo/src/main/java/com/example/exceptions/NotFoundException.java", "snippet": "public class NotFoundException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final static String MESSAGE_STRING = \"Not found\";\n\t\n\tpublic NotFoundException() {\n\t\tthis(MESSAGE_STRING);\n\t}\n\n\tpublic NotFoundException(String message) {\n\t\tsuper(message);\n\t}\n\n\tpublic NotFoundException(Throwable cause) {\n\t\tthis(MESSAGE_STRING, cause);\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n\n\tpublic NotFoundException(String message, Throwable cause, boolean enableSuppression,\n\t\t\tboolean writableStackTrace) {\n\t\tsuper(message, cause, enableSuppression, writableStackTrace);\n\t}\n}" } ]
import java.net.URI; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; 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.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.example.domains.contracts.services.ActorService; import com.example.domains.entities.Film; import com.example.domains.entities.FilmActor; import com.example.domains.entities.dtos.ActorDTO; import com.example.domains.entities.dtos.ActorShort; import com.example.exceptions.BadRequestException; import com.example.exceptions.DuplicateKeyException; import com.example.exceptions.InvalidDataException; import com.example.exceptions.NotFoundException; import jakarta.validation.Valid;
5,421
package com.example.application.resources; @RestController @RequestMapping("/api/actores/v1") public class ActorResource { @Autowired private ActorService srv; @GetMapping public List<ActorShort> getAll() { return srv.getByProjection(ActorShort.class); } @GetMapping(params = "page") public Page<ActorDTO> getAll(Pageable page) { return srv.getByProjection(page, ActorDTO.class); } @GetMapping(path = "/{id}") public ActorDTO getOne(@PathVariable int id) throws NotFoundException { var item = srv.getOne(id); if(item.isEmpty()) throw new NotFoundException(); return ActorDTO.from(item.get()); } record Peli(int id, String titulo) {} @GetMapping(path = "/{id}/pelis") public List<Peli> getPelis(@PathVariable int id) throws NotFoundException { var item = srv.getOne(id); if(item.isEmpty()) throw new NotFoundException(); return item.get().getFilmActors().stream() .map(f->new Peli(f.getFilm().getFilmId(), f.getFilm().getTitle())) .toList(); } @PutMapping(path = "/{id}/jubilacion") @ResponseStatus(HttpStatus.ACCEPTED) public void jubilate(@PathVariable int id) throws NotFoundException { var item = srv.getOne(id); if(item.isEmpty()) throw new NotFoundException(); item.get().jubilate(); } @PostMapping public ResponseEntity<Object> create(@Valid @RequestBody ActorDTO item) throws DuplicateKeyException, InvalidDataException { var newItem = srv.add(ActorDTO.from(item)); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(newItem.getActorId()).toUri(); return ResponseEntity.created(location).build(); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT)
package com.example.application.resources; @RestController @RequestMapping("/api/actores/v1") public class ActorResource { @Autowired private ActorService srv; @GetMapping public List<ActorShort> getAll() { return srv.getByProjection(ActorShort.class); } @GetMapping(params = "page") public Page<ActorDTO> getAll(Pageable page) { return srv.getByProjection(page, ActorDTO.class); } @GetMapping(path = "/{id}") public ActorDTO getOne(@PathVariable int id) throws NotFoundException { var item = srv.getOne(id); if(item.isEmpty()) throw new NotFoundException(); return ActorDTO.from(item.get()); } record Peli(int id, String titulo) {} @GetMapping(path = "/{id}/pelis") public List<Peli> getPelis(@PathVariable int id) throws NotFoundException { var item = srv.getOne(id); if(item.isEmpty()) throw new NotFoundException(); return item.get().getFilmActors().stream() .map(f->new Peli(f.getFilm().getFilmId(), f.getFilm().getTitle())) .toList(); } @PutMapping(path = "/{id}/jubilacion") @ResponseStatus(HttpStatus.ACCEPTED) public void jubilate(@PathVariable int id) throws NotFoundException { var item = srv.getOne(id); if(item.isEmpty()) throw new NotFoundException(); item.get().jubilate(); } @PostMapping public ResponseEntity<Object> create(@Valid @RequestBody ActorDTO item) throws DuplicateKeyException, InvalidDataException { var newItem = srv.add(ActorDTO.from(item)); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(newItem.getActorId()).toUri(); return ResponseEntity.created(location).build(); } @PutMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT)
public void update(@PathVariable int id, @Valid @RequestBody ActorDTO item) throws BadRequestException, NotFoundException, InvalidDataException {
5
2023-10-24 14:35:15+00:00
8k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/cases/filters/impl/SummaryFilter.java
[ { "identifier": "Item", "path": "src/main/java/org/msh/etbm/commons/Item.java", "snippet": "public class Item<E> implements IsItem<E>, Displayable {\n\n private E id;\n private String name;\n\n /**\n * Default constructor\n */\n public Item() {\n super();\n }\n\n /**\n * Constructor passing ID and text\n *\n * @param id the id of the item\n * @param name the display name\n */\n public Item(E id, String name) {\n this.id = id;\n this.name = name;\n }\n\n @Override\n public String toString() {\n return \"Item{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n '}';\n }\n\n public E getId() {\n return id;\n }\n\n public void setId(E id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Override\n @JsonIgnore\n public String getDisplayString() {\n return name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n Item<?> item = (Item<?>) o;\n\n return id.equals(item.id);\n }\n\n @Override\n public int hashCode() {\n return id.hashCode();\n }\n}" }, { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static final String REQUIRED = \"NotNull\";\n public static final String NOT_NULL = \"NotNull\";\n public static final String NOT_VALID = \"NotValid\";\n public static final String NOT_VALID_EMAIL = \"NotValidEmail\";\n public static final String NOT_VALID_WORKSPACE = \"NotValidWorkspace\";\n public static final String NOT_UNIQUE_USER = \"NotUniqueUser\";\n public static final String NOT_VALID_OPTION = \"NotValidOption\";\n\n public static final String MAX_SIZE = \"javax.validation.constraints.Max.message\";\n public static final String MIN_SIZE = \"javax.validation.constraints.Min.message\";\n\n public static final String PERIOD_INIDATE_BEFORE = \"period.msgdt1\";\n\n public static final String UNDEFINED = \"global.notdef\";\n\n /**\n * keys in the message bundle to get information about date format in the selected locale\n */\n // convert from string to date\n public static final String LOCALE_DATE_FORMAT = \"locale.dateFormat\";\n // mask in editing control\n public static final String LOCALE_DATE_MASK = \"locale.dateMask\";\n // hint to be displayed as a place holder in date controls\n public static final String LOCALE_DATE_HINT = \"locale.dateHint\";\n // convert a date to a displayable string\n public static final String LOCALE_DISPLAY_DATE_FORMAT = \"locale.displayDateFormat\";\n\n\n /**\n * The pattern to get the keys to be replaced inside the string\n */\n public static final Pattern EXP_PATTERN = Pattern.compile(\"\\\\$\\\\{(.*?)\\\\}\");\n\n\n @Resource\n MessageSource messageSource;\n\n /**\n * Get the message by its key\n *\n * @param key the message key\n * @return the message to be displayed to the user\n */\n public String get(String key) {\n Locale locale = LocaleContextHolder.getLocale();\n try {\n return messageSource.getMessage(key, null, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"No message found for \" + key + \" in the locale \" + locale.getDisplayName());\n return key;\n }\n }\n\n\n /**\n * Get the message using a message source resolvable object\n *\n * @param res instance of the MessageSourceResolvable interface containing the message\n * @return the string message\n */\n public String get(MessageSourceResolvable res) {\n Locale locale = LocaleContextHolder.getLocale();\n try {\n return messageSource.getMessage(res, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"No message found for \" + res.getDefaultMessage() + \" in the locale \" + locale.getDisplayName());\n }\n return res.getDefaultMessage();\n }\n\n\n /**\n * Evaluate a string and replace message keys between ${key} by the message in the resource bundle file\n * @param text the string to be evaluated\n * @return the new evaluated string\n */\n public String eval(String text) {\n Matcher matcher = EXP_PATTERN.matcher(text);\n while (matcher.find()) {\n String s = matcher.group();\n String key = s.substring(2, s.length() - 1);\n\n text = text.replace(s, get(key));\n }\n\n return text;\n }\n\n\n /**\n * Get the message from the given key and process the arguments inside the message\n * @param msg\n * @param args\n * @return\n */\n public String format(String msg, Object... args) {\n Object[] dest = new Object[args.length];\n int index = 0;\n for (Object obj: args) {\n Object obj2 = obj instanceof Date ? dateToDisplay((Date)obj) : obj;\n dest[index++] = obj2;\n }\n\n return MessageFormat.format(msg, dest);\n }\n\n\n /**\n * Convert a date object to a displayable string\n * @param dt the date to be displayed\n * @return\n */\n public String dateToDisplay(Date dt) {\n Locale locale = LocaleContextHolder.getLocale();\n String pattern;\n try {\n pattern = messageSource.getMessage(LOCALE_DISPLAY_DATE_FORMAT, null, locale);\n } catch (NoSuchMessageException e) {\n LOGGER.info(\"Date format key in message bunldle not found for key \" + LOCALE_DISPLAY_DATE_FORMAT +\n \" in locale \" + locale.getDisplayName());\n pattern = \"dd-MMM-yyyy\";\n }\n\n SimpleDateFormat format = new SimpleDateFormat(pattern);\n return format.format(dt);\n }\n}" }, { "identifier": "Filter", "path": "src/main/java/org/msh/etbm/commons/filters/Filter.java", "snippet": "public interface Filter {\n\n /**\n * Initialize the filter passing the instance of the ApplicationContext.\n * This is called just once when filter is created and before any other method,\n * in order to give the filter the possibility to get beans\n * @param context instance of ApplicationContext interface\n */\n void initialize(ApplicationContext context);\n\n /**\n * Prepare the query to apply the filters\n * @param def the object to enter SQL information\n * @param value the value to be applied to the filter\n * @param params optional parameters sent and interpreted by the filter\n */\n void prepareFilterQuery(QueryDefs def, Object value, Map<String, Object> params);\n\n /**\n * Return a String identification of the filter's type\n * @return filter's type\n */\n String getFilterType();\n\n /**\n * Return the resources to be sent to the client in order to display the filter control\n * @param params the params sent from the client. Null if called during initialization\n * @return the resources to be sent to the client\n */\n Map<String, Object> getResources(Map<String, Object> params);\n\n /**\n * Return a displayable string of the filter value\n * @param value the filter value\n * @return string representation of the value to be displayed\n */\n String valueToDisplay(Object value);\n}" }, { "identifier": "FilterException", "path": "src/main/java/org/msh/etbm/commons/filters/FilterException.java", "snippet": "public class FilterException extends RuntimeException {\n public FilterException() {\n }\n\n public FilterException(String message) {\n super(message);\n }\n\n public FilterException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public FilterException(Throwable cause) {\n super(cause);\n }\n\n public FilterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n}" }, { "identifier": "QueryDefs", "path": "src/main/java/org/msh/etbm/commons/sqlquery/QueryDefs.java", "snippet": "public interface QueryDefs {\n\n /**\n * Add a restriction to the SQL statement that will be included in the WHERE clause\n * @param sqlexpr the SQL expression that will be included in the where clause\n * @return instance of {@link QueryDefs}\n */\n QueryDefs restrict(String sqlexpr);\n\n /**\n * Add a restriction to the SQL statement that will be included in the WHERE clause,\n * with the possibility to also include parameters that will replace the ? in the\n * given SQL expression\n * @param sqlexpr the SQL expression that will be included in the where clause\n * @return instance of {@link QueryDefs}\n */\n QueryDefs restrict(String sqlexpr, Object... parameters);\n\n /**\n * Include a table and its relation (on) to be added as a join operation in the SQL. When declaring\n * the ON expression, you may declare fields \"table.fieldName\", where table may be\n * @param tableName the table name\n * @param on the ON SQL instruction of the JOIN operation\n * @return instance of {@link QueryDefs}\n */\n QueryDefs join(String tableName, String on);\n\n\n /**\n * Include a table and its relation (sql ON) in the SQL declaration as a left join.\n * @param tableName the table name to be included\n * @param on the ON SQL statement of the LEFT JOIN operation\n * @return instance of {@link QueryDefs}\n */\n QueryDefs leftJoin(String tableName, String on);\n\n /**\n * Makes reference to an existing join by its join name\n * @param joinName the name of the join defined in the join definition\n * @return instance of {@link QueryDefs}\n */\n QueryDefs join(String joinName);\n\n /**\n * Add the fields to be included in the SQL SELECT statement\n * @param fields the list of fields separated by comma\n * @return instance of {@link QueryDefs}\n */\n QueryDefs select(String fields);\n\n /**\n * Return the main table used in the query\n * @return the name of the main table\n */\n String getMainTable();\n}" }, { "identifier": "CaseFilters", "path": "src/main/java/org/msh/etbm/services/cases/filters/CaseFilters.java", "snippet": "@Service\npublic class CaseFilters {\n\n public static final VariableOutput VAROUT_CASES = new VariableOutput(\"cases\", \"${cases}\");\n public static final VariableOutput VAROUT_EXAMS = new VariableOutput(\"exams\", \"${exams}\");\n\n public static final String CASE_STATE = \"case-state\";\n public static final String CASE_CLASSIFICATION = \"classification\";\n public static final String INFECTION_SITE = \"infection-site\";\n public static final String DIAGNOSIS_TYPE = \"diagnosis-type\";\n public static final String NATIONALITY = \"nationality\";\n public static final String GENDER = \"gender\";\n public static final String OUTCOME = \"outcome\";\n public static final String REGISTRATION_GROUP = \"registration-group\";\n public static final String DRUG_RESISTANCE_TYPE = \"drug-resistance-type\";\n public static final String PULMONARY_FORMS = \"pulmonary-forms\";\n public static final String EXTRAPULMONARY_FORMS = \"extrapulmonary-forms\";\n public static final String TAG = \"tag\";\n public static final String SUMMARY = \"summary\";\n public static final String CASE_DEFINITION = \"case-definition\";\n public static final String AGE_RANGE = \"age-range\";\n public static final String HIV_RESULT = \"hiv-result\";\n public static final String CULTURE_RESULT_GROUP = \"culture-res-group\";\n public static final String DIAGNOSIS_DATE = \"diagnosis-date\";\n public static final String INI_TREATMENT_DATE = \"ini-treat-date\";\n public static final String END_TREATMENT_DATE = \"end-treat-date\";\n public static final String OUTCOME_DATE = \"outcome-date\";\n public static final String MONTH_OF_TREAT = \"month-of-treat\";\n public static final String PRESC_MEDICINE = \"presc-medicine\";\n\n @Autowired\n ApplicationContext applicationContext;\n\n @Autowired\n Messages messages;\n\n\n public List<FilterGroup> groups;\n\n\n /**\n * Declare the filters and variables of the case data group\n * @param grp\n */\n private void createCaseDataFilters(FilterGroup grp) {\n grp.add(new EnumFilter(CASE_CLASSIFICATION,\n CaseClassification.class, \"${CaseClassification}\", \"tbcase.classification\"));\n\n grp.add(new ModelFieldOptionsFilter(GENDER, \"${Gender}\", \"patient\", \"gender\"));\n\n grp.add(new EnumFilter(DIAGNOSIS_TYPE, DiagnosisType.class, \"${DiagnosisType}\", \"tbcase.diagnosisType\"));\n\n grp.add(new EnumFilter(CASE_STATE, CaseState.class, \"${CaseState}\", \"tbcase.state\"));\n\n grp.add(new EnumFilter(INFECTION_SITE, InfectionSite.class, \"${InfectionSite}\", \"tbcase.infectionSite\"));\n\n grp.add(new ModelFieldOptionsFilter(NATIONALITY, \"${Nationality}\", \"tbcase\", \"nationality\"));\n\n grp.add(new ModelFieldOptionsFilter(REGISTRATION_GROUP,\n \"${TbCase.registrationGroup}\", \"tbcase\", \"registrationGroup\"));\n\n grp.add(new ModelFieldOptionsFilter(DRUG_RESISTANCE_TYPE,\n \"${DrugResistanceType}\", \"tbcase\", \"drugResistanceType\"));\n\n grp.add(new ModelFieldOptionsFilter(PULMONARY_FORMS,\n \"${TbCase.pulmonaryType}\", \"tbcase\", \"pulmonaryType\"));\n\n grp.add(new ModelFieldOptionsFilter(EXTRAPULMONARY_FORMS,\n \"${TbCase.extrapulmonaryType}\", \"tbcase\", \"extrapulmonaryType\"));\n\n grp.add(new EnumFilter(CASE_DEFINITION, CaseDefinition.class, \"${CaseDefinition}\", \"tbcase.caseDefinition\"));\n\n grp.add(new AgeRangeFilter());\n\n grp.add(new PeriodFilter(DIAGNOSIS_DATE, \"${TbCase.diagnosisDate}\", \"tbcase.diagnosisDate\", PeriodFilter.PeriodVariableType.MONTHLY));\n\n }\n\n /**\n * Declare the filters and variables of the treatment group\n * @param grp the group to include the filters\n */\n private void createTreatmentFilters(FilterGroup grp) {\n grp.add(new ModelFieldOptionsFilter(OUTCOME, \"${TbCase.outcome}\", \"tbcase\", \"outcome\"));\n\n grp.add(new PeriodFilter(INI_TREATMENT_DATE, \"${TbCase.iniTreatmentDate}\", \"tbcase.iniTreatmentDate\",\n PeriodFilter.PeriodVariableType.MONTHLY));\n\n grp.add(new PeriodFilter(END_TREATMENT_DATE, \"${TbCase.endTreatmentDate}\", \"tbcase.endTreatmentDate\",\n PeriodFilter.PeriodVariableType.MONTHLY));\n\n grp.add(new PeriodFilter(OUTCOME_DATE, \"${TbCase.outcomeDate}\", \"tbcase.outcomeDate\",\n PeriodFilter.PeriodVariableType.MONTHLY));\n\n grp.add(new MonthOfTreatFilter());\n\n grp.add(new PrescribedMedicineFilter());\n }\n\n private void createHivGroup(FilterGroup grp) {\n grp.add(new HIVResultFilter());\n }\n\n private void createMicroscopyFilters(FilterGroup grp) {\n }\n\n private void createCultureFilters(FilterGroup grp) {\n\n }\n\n private void createOtherFilters(FilterGroup grp) {\n grp.add(new TagFilter());\n grp.add(new SummaryFilter());\n }\n\n private FilterGroup createGroup(String messageKey) {\n FilterGroup grp = new FilterGroup(messageKey);\n groups.add(grp);\n return grp;\n }\n\n /**\n * Initialize the filters passing the instance of ApplicationContext to allow them to\n * interact with spring beans\n */\n private void initFilters() {\n groups.stream().forEach(grp -> {\n grp.getFilters().forEach(filter -> filter.initialize(applicationContext));\n grp.getVariables().forEach(variable -> variable.initialize(applicationContext));\n });\n }\n\n protected void add(Map<String, Filter> filters, FilterItem filter) {\n filters.put(filter.getId(), filter);\n }\n\n /**\n * Search a filter by its ID\n * @param id the filter ID\n * @return the filter that matches the ID\n */\n public FilterItem filterById(String id) {\n createFiltersVariables();\n\n for (FilterGroup grp: groups) {\n for (FilterItem filter: grp.getFilters()) {\n if (filter.getId().equals(id)) {\n return filter;\n }\n }\n }\n\n return null;\n }\n\n /**\n * Search for a variable by its id\n * @param id the variable ID\n * @return\n */\n public Variable variableById(String id) {\n createFiltersVariables();\n\n for (FilterGroup grp: groups) {\n for (Variable var: grp.getVariables()) {\n if (var.getId().equals(id)) {\n return var;\n }\n }\n }\n\n return null;\n }\n\n\n /**\n * Return the list of filters\n * @return\n */\n public List<FilterGroupData> getFiltersData() {\n createFiltersVariables();\n\n List<FilterGroupData> res = new ArrayList<>();\n\n for (FilterGroup grp: groups) {\n if (grp.getFilters().size() > 0) {\n String grpLabel = messages.eval(grp.getLabel());\n\n FilterGroupData grpdata = new FilterGroupData();\n grpdata.setLabel(grpLabel);\n\n List<FilterData> lst = new ArrayList<>();\n for (FilterItem filter: grp.getFilters()) {\n String label = messages.eval(filter.getName());\n Map<String, Object> resources = filter.getResources(null);\n FilterData fdata = new FilterData(filter.getId(), label, resources);\n fdata.setType(filter.getFilterType());\n\n lst.add(fdata);\n }\n\n grpdata.setFilters(lst);\n\n res.add(grpdata);\n }\n }\n\n return res;\n }\n\n\n /**\n * Return variable information ready for client serialization\n * @return List of {@link VariableGroupData} containing the variable groups\n */\n public List<VariableGroupData> getVariablesData() {\n createFiltersVariables();\n\n List<VariableGroupData> res = groups.stream()\n .filter(grp -> grp.getVariables() != null && grp.getVariables().size() > 0)\n .map(grp -> {\n VariableGroupData vgd = new VariableGroupData();\n vgd.setLabel(messages.eval(grp.getLabel()));\n\n vgd.setVariables(grp.getVariables().stream()\n .map(v -> new VariableData(v.getId(), v.getName(),\n v.isGrouped(),\n v.isTotalEnabled()))\n .collect(Collectors.toList()));\n\n return vgd;\n })\n .collect(Collectors.toList());\n\n return res;\n }\n\n protected void createFiltersVariables() {\n if (groups != null) {\n return;\n }\n\n groups = new ArrayList<>();\n\n createCaseDataFilters(createGroup(\"${cases.details.case}\"));\n createMicroscopyFilters(createGroup(\"${cases.exammicroscopy}\"));\n createCultureFilters(createGroup(\"${cases.examculture}\"));\n createHivGroup(createGroup(\"${cases.examhiv}\"));\n createOtherFilters(createGroup(\"${cases.filters.others}\"));\n createTreatmentFilters(createGroup(\"${cases.details.treatment}\"));\n\n initFilters();\n }\n\n\n /**\n * Convert a filter to its display representation\n * @param filterId\n * @param value\n * @return\n */\n public FilterDisplay filterToDisplay(String filterId, Object value) {\n FilterItem filter = filterById(filterId);\n if (filter == null) {\n return null;\n }\n\n String name = messages.eval(filter.getName());\n String valueDisplay = filter.valueToDisplay(value);\n\n FilterDisplay f = new FilterDisplay(name, valueDisplay);\n\n return f;\n }\n\n}" }, { "identifier": "SummaryItem", "path": "src/main/java/org/msh/etbm/services/cases/summary/SummaryItem.java", "snippet": "public class SummaryItem extends Item<String> {\n\n private Map<String, Object> filters;\n\n public SummaryItem() {\n }\n\n public SummaryItem(String id, String name, Map<String, Object> filters) {\n super(id, name);\n this.filters = filters;\n }\n\n public Map<String, Object> getFilters() {\n return filters;\n }\n\n public void setFilters(Map<String, Object> filters) {\n this.filters = filters;\n }\n}" }, { "identifier": "SummaryService", "path": "src/main/java/org/msh/etbm/services/cases/summary/SummaryService.java", "snippet": "@Service\npublic class SummaryService {\n\n @Autowired\n CaseSearchService caseSearchService;\n\n @Autowired\n Messages messages;\n\n @Value(\"${development:false}\")\n boolean development;\n\n private List<SummaryItem> items;\n\n\n /**\n * Generate the report summary\n * @param req\n * @return list of {@link SummaryReportData} with the summary report\n */\n @DbCache(updateAt = \"2:30:00\")\n public List<SummaryReportData> generateSummary(SummaryRequest req) {\n if (development) {\n // force reloading the summary.json on every report generation\n items = null;\n }\n\n List<SummaryReportData> summary = new ArrayList<>();\n\n for (SummaryItem item: getItems()) {\n SummaryReportData data = calcSummaryItem(req, item);\n summary.add(data);\n }\n\n return summary;\n }\n\n /**\n * Calculate the number of cases for a summary item\n * @param req the instance of {@link SummaryRequest} submitted by the client\n * @param item the instance of {@link SummaryItem} with filters to apply to the query\n * @return instance of {@link SummaryReportData}\n */\n private SummaryReportData calcSummaryItem(SummaryRequest req, SummaryItem item) {\n\n Map<String, Object> filters = new HashMap<>();\n\n filters.putAll(item.getFilters());\n\n CaseSearchRequest csreq = new CaseSearchRequest();\n csreq.setFilters(filters);\n csreq.setResultType(ResultType.COUNT_ONLY);\n csreq.setScope(req.getScope());\n csreq.setScopeId(req.getScopeId());\n\n QueryResult<CaseData> res = caseSearchService.execute(csreq);\n\n String name = messages.eval(item.getName());\n\n return new SummaryReportData(item.getId(), name, res.getCount());\n }\n\n /**\n * Return the items of the summary report\n * @return list of {@link SummaryItem} objects\n */\n public List<SummaryItem> getItems() {\n if (items == null) {\n items = loadItems();\n }\n return items;\n }\n\n /**\n * Load the items of the summary\n * @return list of {@link SummaryItem} objects\n */\n protected List<SummaryItem> loadItems() {\n ClassPathResource res = new ClassPathResource(\"/templates/json/summary.json\");\n\n try {\n InputStream in = res.getInputStream();\n ObjectMapper mapper = new ObjectMapper();\n TypeFactory typeFactory = mapper.getTypeFactory();\n return mapper.readValue(in, typeFactory.constructCollectionType(List.class, SummaryItem.class));\n } catch (Exception e) {\n throw new JsonParserException(e);\n }\n\n }\n}" } ]
import org.msh.etbm.commons.Item; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.filters.Filter; import org.msh.etbm.commons.filters.FilterException; import org.msh.etbm.commons.sqlquery.QueryDefs; import org.msh.etbm.services.cases.filters.CaseFilters; import org.msh.etbm.services.cases.summary.SummaryItem; import org.msh.etbm.services.cases.summary.SummaryService; import org.springframework.context.ApplicationContext; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors;
6,072
package org.msh.etbm.services.cases.filters.impl; /** * Implementation of a {@link Filter} for an specific item of the case summary * * Created by rmemoria on 21/9/16. */ public class SummaryFilter extends AbstractFilter { private SummaryService summaryService; private CaseFilters filters; public SummaryFilter() { super("summary", "${global.summary}"); } @Override public void initialize(ApplicationContext context) { super.initialize(context); summaryService = context.getBean(SummaryService.class); filters = context.getBean(CaseFilters.class); } @Override public void prepareFilterQuery(QueryDefs def, Object value, Map<String, Object> params) { if (value == null) { return; } String summaryId = value.toString();
package org.msh.etbm.services.cases.filters.impl; /** * Implementation of a {@link Filter} for an specific item of the case summary * * Created by rmemoria on 21/9/16. */ public class SummaryFilter extends AbstractFilter { private SummaryService summaryService; private CaseFilters filters; public SummaryFilter() { super("summary", "${global.summary}"); } @Override public void initialize(ApplicationContext context) { super.initialize(context); summaryService = context.getBean(SummaryService.class); filters = context.getBean(CaseFilters.class); } @Override public void prepareFilterQuery(QueryDefs def, Object value, Map<String, Object> params) { if (value == null) { return; } String summaryId = value.toString();
Optional<SummaryItem> res = summaryService.getItems().stream()
6
2023-10-23 13:47:54+00:00
8k
exagonsoft/drones-management-board-backend
src/test/java/exagonsoft/drones/service/DroneServiceTest.java
[ { "identifier": "BatteryLevelDto", "path": "src/main/java/exagonsoft/drones/dto/BatteryLevelDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class BatteryLevelDto {\n private int batteryLevel;\n}" }, { "identifier": "DroneDto", "path": "src/main/java/exagonsoft/drones/dto/DroneDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class DroneDto {\n private Long id;\n private String serial_number;\n private ModelType model;\n private Integer max_weight;\n private Integer battery_capacity;\n private StateType state;\n}" }, { "identifier": "MedicationDto", "path": "src/main/java/exagonsoft/drones/dto/MedicationDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MedicationDto {\n private Long id;\n private String name;\n private Integer weight;\n private String code;\n private String imageUrl;\n}" }, { "identifier": "Drone", "path": "src/main/java/exagonsoft/drones/entity/Drone.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"drones\")\npublic class Drone {\n\n public enum ModelType {\n Lightweight,\n Middleweight,\n Cruiserweight,\n Heavyweight\n }\n\n public enum StateType {\n IDLE,\n LOADING,\n LOADED,\n DELIVERING,\n DELIVERED,\n RETURNING\n }\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"serial_number\", nullable = false, unique = true, length = 100)\n private String serial_number;\n\n @Column(name = \"model\", nullable = false)\n @Enumerated(EnumType.STRING)\n private ModelType model;\n\n @Column(name = \"max_weight\", nullable = false)\n @Max(value = 500, message = \"Maximum weight cannot exceed 500gr\")\n private Integer max_weight;\n\n @Column(name = \"battery_capacity\", nullable = false)\n @Max(value = 100, message = \"Battery capacity cannot exceed 100%\")\n private Integer battery_capacity;\n\n @Column(name = \"state\", nullable = false)\n @Enumerated(EnumType.STRING)\n private StateType state;\n}" }, { "identifier": "MockData", "path": "src/main/java/exagonsoft/drones/mock/MockData.java", "snippet": "public class MockData {\n\n public static Drone mockDrone() {\n Drone drone = new Drone();\n drone.setId(1L);\n drone.setSerial_number(\"mxzn6789\");\n drone.setMax_weight(250);\n drone.setModel(ModelType.Cruiserweight);\n drone.setBattery_capacity(100);\n drone.setState(StateType.IDLE);\n return drone;\n }\n\n public static DroneDto mockDroneDto(){\n DroneDto droneDto = new DroneDto();\n droneDto.setId(1L);\n droneDto.setSerial_number(\"mxzn6789\");\n droneDto.setMax_weight(250);\n droneDto.setModel(ModelType.Cruiserweight);\n droneDto.setBattery_capacity(100);\n droneDto.setState(StateType.IDLE);\n return droneDto;\n }\n\n public static DroneDto mockUpdatedDroneDto(){\n DroneDto droneDto = new DroneDto();\n droneDto.setId(1L);\n droneDto.setSerial_number(\"mxzn6789\");\n droneDto.setMax_weight(250);\n droneDto.setModel(ModelType.Cruiserweight);\n droneDto.setBattery_capacity(90);\n droneDto.setState(StateType.DELIVERED);\n return droneDto;\n }\n\n public static Medication mockMedications(){\n Medication medication = new Medication();\n medication.setId(1L);\n medication.setName(\"Test_Medication\");\n medication.setWeight(10);\n medication.setCode(\"GNXT_42_ZFYTUPL\");\n medication.setImageUrl(\"/uploads/samplePicture.png\");\n return medication;\n }\n\n public static MedicationDto mockMedicationDto(){\n MedicationDto medicationDto = new MedicationDto();\n medicationDto.setId(1L);\n medicationDto.setName(\"Test_Medication\");\n medicationDto.setWeight(10);\n medicationDto.setCode(\"GNXT_42_ZFYTUPL\");\n medicationDto.setImageUrl(\"/uploads/samplePicture.png\");\n return medicationDto;\n }\n\n public static DroneMedications mockDroneMedications(){\n DroneMedications droneMedications = new DroneMedications();\n droneMedications.setId(1L);\n droneMedications.setDroneId(1L);\n droneMedications.setMedicationId(1L);\n return droneMedications;\n }\n\n public static DroneMedicationDto mockDroneMedicationDto(){\n DroneMedicationDto droneMedicationDto = new DroneMedicationDto();\n droneMedicationDto.setId(1L);\n droneMedicationDto.setDroneId(1L);\n droneMedicationDto.setMedicationId(1L);\n return droneMedicationDto;\n }\n\n public static AuditLog mockAuditLog(){\n AuditLog auditLog = new AuditLog();\n auditLog.setId(1L);\n auditLog.setDrone_id(1L);\n auditLog.setMessage(\"Sample Message\");\n auditLog.setTimestamp(new java.sql.Date(System.currentTimeMillis()));\n return auditLog;\n }\n\n public static AuditLogDto mockAuditLogDto() {\n AuditLogDto auditLogDto = new AuditLogDto();\n auditLogDto.setId(1L);\n auditLogDto.setDrone_id(1L);\n auditLogDto.setMessage(\"Sample Message\");\n auditLogDto.setTimestamp(new java.sql.Date(System.currentTimeMillis()));\n return auditLogDto;\n }\n\n public static BatteryLevelDto mockBatteryLevelDto(){\n BatteryLevelDto batteryLevelDto = new BatteryLevelDto();\n batteryLevelDto.setBatteryLevel(100);\n return batteryLevelDto;\n }\n}" }, { "identifier": "DroneRepository", "path": "src/main/java/exagonsoft/drones/repository/DroneRepository.java", "snippet": "public interface DroneRepository extends JpaRepository<Drone, Long> {\n @Query(value = \"SELECT * FROM drones WHERE battery_capacity >= 25 AND state = 'IDLE'\", nativeQuery = true)\n List<Drone> findAvailableDrones();\n\n @Query(value = \"SELECT serial_number, battery_capacity, id FROM drones\" , nativeQuery = true)\n List<Object[]> getAllDronesBatteryLevel();\n}" }, { "identifier": "DroneServiceImpl", "path": "src/main/java/exagonsoft/drones/service/impl/DroneServiceImpl.java", "snippet": "@Service\n@AllArgsConstructor\npublic class DroneServiceImpl implements DroneService {\n\n private DroneRepository droneRepository;\n private DroneMedicationService droneMedicationService;\n private MedicationService medicationService;\n\n @Override\n public DroneDto createDrone(DroneDto droneDto) {\n\n try {\n // *Validate the Drone Data*/\n UtilFunctions.validateDrone(droneDto);\n\n Drone drone = DroneMapper.mapToDrone(droneDto);\n\n Drone savedDrone = droneRepository.save(drone);\n\n return DroneMapper.mapToDroneDto(savedDrone);\n } catch (DataIntegrityViolationException e) {\n throw new DuplicateSerialNumberException(\"Serial Number already exists!\");\n }\n\n }\n\n @Override\n public DroneDto getDroneByID(Long droneID) {\n Drone drone = droneRepository.findById(droneID)\n .orElseThrow(() -> new ResourceNotFoundException(\"Drone not found with given id: \" + droneID));\n\n return DroneMapper.mapToDroneDto(drone);\n }\n\n @Override\n public List<DroneDto> listAllDrones() {\n try {\n List<Drone> drones = droneRepository.findAll();\n\n return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone))\n .collect(Collectors.toList());\n } catch (Exception e) {\n throw new RuntimeException(\"Something went wrong!\");\n }\n\n }\n\n @Override\n public DroneDto updateDrone(Long droneId, DroneDto updatedDrone) {\n\n try {\n // *Validate the Drone Data*/\n UtilFunctions.validateDrone(updatedDrone);\n UtilFunctions.validateDroneManagement(updatedDrone);\n\n Drone drone = droneRepository.findById(droneId)\n .orElseThrow(() -> new ResourceNotFoundException(\"Drone not found with given id: \" + droneId));\n\n drone.setMax_weight(updatedDrone.getMax_weight());\n drone.setModel(updatedDrone.getModel());\n drone.setBattery_capacity(updatedDrone.getBattery_capacity());\n drone.setState(updatedDrone.getState());\n\n Drone updatedDroneObj = droneRepository.save(drone);\n\n return DroneMapper.mapToDroneDto(updatedDroneObj);\n } catch (Exception e) {\n throw e;\n }\n }\n\n @Override\n public List<DroneDto> listAvailableDrones() {\n try {\n List<Drone> drones = droneRepository.findAvailableDrones();\n\n return drones.stream().map((drone) -> DroneMapper.mapToDroneDto(drone))\n .collect(Collectors.toList());\n } catch (Exception e) {\n throw new RuntimeException(\"Something went wrong!\");\n }\n }\n\n @Override\n public BatteryLevelDto checkDroneBatteryLevel(Long droneID) {\n try {\n Drone drone = droneRepository.findById(droneID)\n .orElseThrow(() -> new ResourceNotFoundException(\"Drone not found with given id: \" + droneID));\n\n BatteryLevelDto batteryLevelDto = new BatteryLevelDto(drone.getBattery_capacity());\n\n return batteryLevelDto;\n } catch (Exception e) {\n throw e;\n }\n\n }\n\n @Override\n public List<MedicationDto> listDroneMedications(Long droneID) {\n try {\n droneRepository.findById(droneID)\n .orElseThrow(() -> new ResourceNotFoundException(\"Drone not found with given id: \" + droneID));\n\n List<DroneMedications> droneMedications = droneMedicationService.listAllDroneMedications(droneID);\n\n List<MedicationDto> medicationDtoList = droneMedications.stream()\n .map((_drone_medication) -> medicationService.getMedication(_drone_medication.getMedicationId()))\n .collect(Collectors.toList());\n\n return medicationDtoList;\n } catch (Exception e) {\n throw e;\n }\n }\n\n @Override\n public boolean loadDroneMedications(Long droneID, List<Long> medicationsIds) {\n\n try {\n Drone drone = droneRepository.findById(droneID)\n .orElseThrow(() -> new ResourceNotFoundException(\"Drone not found with given id: \" + droneID));\n\n List<Medication> medicationList = medicationService.getMedicationsListByIds(medicationsIds);\n\n UtilFunctions.validateDroneLoad(drone.getMax_weight(), medicationList, drone.getState());\n drone.setState(StateType.LOADING);\n UtilFunctions.validateDroneManagement(DroneMapper.mapToDroneDto(drone));\n\n droneRepository.save(drone);\n droneMedicationService.cleanupDroneMedication(droneID);\n for (Medication medication : medicationList) {\n DroneMedications droneMedication = new DroneMedications();\n droneMedication.setDroneId(droneID);\n droneMedication.setMedicationId(medication.getId());\n droneMedicationService.createDroneMedication(droneMedication);\n }\n\n return true;\n } catch (Exception e) {\n throw e;\n }\n }\n\n}" } ]
import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.boot.test.context.SpringBootTest; import exagonsoft.drones.dto.BatteryLevelDto; import exagonsoft.drones.dto.DroneDto; import exagonsoft.drones.dto.MedicationDto; import exagonsoft.drones.entity.Drone; import exagonsoft.drones.mock.MockData; import exagonsoft.drones.repository.DroneRepository; import exagonsoft.drones.service.impl.DroneServiceImpl; import java.util.Collections; import java.util.List; import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*;
3,611
package exagonsoft.drones.service; @SpringBootTest public class DroneServiceTest { @InjectMocks private DroneServiceImpl droneService; @Mock private DroneRepository droneRepository; @Mock private DroneMedicationService droneMedicationService; @Mock private MedicationService medicationService; @Test public void testCreateDrone() { // Arrange DroneDto droneDto = MockData.mockDroneDto(); Drone savedDrone = MockData.mockDrone(); when(droneRepository.save(any(Drone.class))).thenReturn(savedDrone); // Act DroneDto createdDrone = droneService.createDrone(droneDto); // Assert assertNotNull(createdDrone); assertEquals(savedDrone.getId(), createdDrone.getId()); } @Test public void testGetDroneByID() { // Arrange Long droneId = 1L; Drone drone = MockData.mockDrone(); when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone)); // Act DroneDto retrievedDrone = droneService.getDroneByID(droneId); // Assert assertNotNull(retrievedDrone); assertEquals(droneId, retrievedDrone.getId()); } @Test public void testListAllDrones() { // Arrange List<Drone> drones = Collections.singletonList(MockData.mockDrone()); when(droneRepository.findAll()).thenReturn(drones); // Act List<DroneDto> droneDtoList = droneService.listAllDrones(); // Assert assertNotNull(droneDtoList); assertEquals(1, droneDtoList.size()); } @Test public void testUpdateDrone() { // Arrange Long droneId = 1L; DroneDto updatedDroneDto = MockData.mockUpdatedDroneDto(); Drone existingDrone = MockData.mockDrone(); when(droneRepository.findById(droneId)).thenReturn(Optional.of(existingDrone)); when(droneRepository.save(any(Drone.class))).thenReturn(existingDrone); // Act DroneDto updatedDrone = droneService.updateDrone(droneId, updatedDroneDto); // Assert assertNotNull(updatedDrone); assertEquals(updatedDroneDto.getMax_weight(), updatedDrone.getMax_weight()); assertEquals(updatedDroneDto.getModel(), updatedDrone.getModel()); assertEquals(updatedDroneDto.getBattery_capacity(), updatedDrone.getBattery_capacity()); assertEquals(updatedDroneDto.getState(), updatedDrone.getState()); } @Test public void testListAvailableDrones() { // Arrange List<Drone> availableDrones = Collections.singletonList(MockData.mockDrone()); when(droneRepository.findAvailableDrones()).thenReturn(availableDrones); // Act List<DroneDto> availableDroneDtoList = droneService.listAvailableDrones(); // Assert assertNotNull(availableDroneDtoList); assertEquals(1, availableDroneDtoList.size()); } @Test public void testCheckDroneBatteryLevel() { // Arrange Long droneId = 1L; Drone drone = MockData.mockDrone(); when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone)); // Act
package exagonsoft.drones.service; @SpringBootTest public class DroneServiceTest { @InjectMocks private DroneServiceImpl droneService; @Mock private DroneRepository droneRepository; @Mock private DroneMedicationService droneMedicationService; @Mock private MedicationService medicationService; @Test public void testCreateDrone() { // Arrange DroneDto droneDto = MockData.mockDroneDto(); Drone savedDrone = MockData.mockDrone(); when(droneRepository.save(any(Drone.class))).thenReturn(savedDrone); // Act DroneDto createdDrone = droneService.createDrone(droneDto); // Assert assertNotNull(createdDrone); assertEquals(savedDrone.getId(), createdDrone.getId()); } @Test public void testGetDroneByID() { // Arrange Long droneId = 1L; Drone drone = MockData.mockDrone(); when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone)); // Act DroneDto retrievedDrone = droneService.getDroneByID(droneId); // Assert assertNotNull(retrievedDrone); assertEquals(droneId, retrievedDrone.getId()); } @Test public void testListAllDrones() { // Arrange List<Drone> drones = Collections.singletonList(MockData.mockDrone()); when(droneRepository.findAll()).thenReturn(drones); // Act List<DroneDto> droneDtoList = droneService.listAllDrones(); // Assert assertNotNull(droneDtoList); assertEquals(1, droneDtoList.size()); } @Test public void testUpdateDrone() { // Arrange Long droneId = 1L; DroneDto updatedDroneDto = MockData.mockUpdatedDroneDto(); Drone existingDrone = MockData.mockDrone(); when(droneRepository.findById(droneId)).thenReturn(Optional.of(existingDrone)); when(droneRepository.save(any(Drone.class))).thenReturn(existingDrone); // Act DroneDto updatedDrone = droneService.updateDrone(droneId, updatedDroneDto); // Assert assertNotNull(updatedDrone); assertEquals(updatedDroneDto.getMax_weight(), updatedDrone.getMax_weight()); assertEquals(updatedDroneDto.getModel(), updatedDrone.getModel()); assertEquals(updatedDroneDto.getBattery_capacity(), updatedDrone.getBattery_capacity()); assertEquals(updatedDroneDto.getState(), updatedDrone.getState()); } @Test public void testListAvailableDrones() { // Arrange List<Drone> availableDrones = Collections.singletonList(MockData.mockDrone()); when(droneRepository.findAvailableDrones()).thenReturn(availableDrones); // Act List<DroneDto> availableDroneDtoList = droneService.listAvailableDrones(); // Assert assertNotNull(availableDroneDtoList); assertEquals(1, availableDroneDtoList.size()); } @Test public void testCheckDroneBatteryLevel() { // Arrange Long droneId = 1L; Drone drone = MockData.mockDrone(); when(droneRepository.findById(droneId)).thenReturn(Optional.of(drone)); // Act
BatteryLevelDto batteryLevelDto = droneService.checkDroneBatteryLevel(droneId);
0
2023-10-16 08:32:39+00:00
8k